Return ConstantVector to 2.5 API.
[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 #include "X86.h"
16 #include "X86InstrBuilder.h"
17 #include "X86ISelLowering.h"
18 #include "X86TargetMachine.h"
19 #include "llvm/CallingConv.h"
20 #include "llvm/Constants.h"
21 #include "llvm/DerivedTypes.h"
22 #include "llvm/GlobalAlias.h"
23 #include "llvm/GlobalVariable.h"
24 #include "llvm/Function.h"
25 #include "llvm/Instructions.h"
26 #include "llvm/Intrinsics.h"
27 #include "llvm/LLVMContext.h"
28 #include "llvm/ADT/BitVector.h"
29 #include "llvm/ADT/VectorExtras.h"
30 #include "llvm/CodeGen/MachineFrameInfo.h"
31 #include "llvm/CodeGen/MachineFunction.h"
32 #include "llvm/CodeGen/MachineInstrBuilder.h"
33 #include "llvm/CodeGen/MachineModuleInfo.h"
34 #include "llvm/CodeGen/MachineRegisterInfo.h"
35 #include "llvm/CodeGen/PseudoSourceValue.h"
36 #include "llvm/Support/MathExtras.h"
37 #include "llvm/Support/Debug.h"
38 #include "llvm/Support/ErrorHandling.h"
39 #include "llvm/Target/TargetLoweringObjectFile.h"
40 #include "llvm/Target/TargetOptions.h"
41 #include "llvm/ADT/SmallSet.h"
42 #include "llvm/ADT/StringExtras.h"
43 #include "llvm/Support/CommandLine.h"
44 #include "llvm/Support/raw_ostream.h"
45 using namespace llvm;
46
47 static cl::opt<bool>
48 DisableMMX("disable-mmx", cl::Hidden, cl::desc("Disable use of MMX"));
49
50 // Forward declarations.
51 static SDValue getMOVL(SelectionDAG &DAG, DebugLoc dl, MVT VT, SDValue V1,
52                        SDValue V2);
53
54 static TargetLoweringObjectFile *createTLOF(X86TargetMachine &TM) {
55   switch (TM.getSubtarget<X86Subtarget>().TargetType) {
56   default: llvm_unreachable("unknown subtarget type");
57   case X86Subtarget::isDarwin:
58     return new TargetLoweringObjectFileMachO(TM);
59   case X86Subtarget::isELF:
60     return new TargetLoweringObjectFileELF();
61   case X86Subtarget::isMingw:
62   case X86Subtarget::isCygwin:
63   case X86Subtarget::isWindows:
64     return new TargetLoweringObjectFileCOFF();
65   }
66   
67 }
68
69 X86TargetLowering::X86TargetLowering(X86TargetMachine &TM)
70   : TargetLowering(TM, createTLOF(TM)) {
71   Subtarget = &TM.getSubtarget<X86Subtarget>();
72   X86ScalarSSEf64 = Subtarget->hasSSE2();
73   X86ScalarSSEf32 = Subtarget->hasSSE1();
74   X86StackPtr = Subtarget->is64Bit() ? X86::RSP : X86::ESP;
75
76   RegInfo = TM.getRegisterInfo();
77   TD = getTargetData();
78
79   // Set up the TargetLowering object.
80
81   // X86 is weird, it always uses i8 for shift amounts and setcc results.
82   setShiftAmountType(MVT::i8);
83   setBooleanContents(ZeroOrOneBooleanContent);
84   setSchedulingPreference(SchedulingForRegPressure);
85   setStackPointerRegisterToSaveRestore(X86StackPtr);
86
87   if (Subtarget->isTargetDarwin()) {
88     // Darwin should use _setjmp/_longjmp instead of setjmp/longjmp.
89     setUseUnderscoreSetJmp(false);
90     setUseUnderscoreLongJmp(false);
91   } else if (Subtarget->isTargetMingw()) {
92     // MS runtime is weird: it exports _setjmp, but longjmp!
93     setUseUnderscoreSetJmp(true);
94     setUseUnderscoreLongJmp(false);
95   } else {
96     setUseUnderscoreSetJmp(true);
97     setUseUnderscoreLongJmp(true);
98   }
99
100   // Set up the register classes.
101   addRegisterClass(MVT::i8, X86::GR8RegisterClass);
102   addRegisterClass(MVT::i16, X86::GR16RegisterClass);
103   addRegisterClass(MVT::i32, X86::GR32RegisterClass);
104   if (Subtarget->is64Bit())
105     addRegisterClass(MVT::i64, X86::GR64RegisterClass);
106
107   setLoadExtAction(ISD::SEXTLOAD, MVT::i1, Promote);
108
109   // We don't accept any truncstore of integer registers.
110   setTruncStoreAction(MVT::i64, MVT::i32, Expand);
111   setTruncStoreAction(MVT::i64, MVT::i16, Expand);
112   setTruncStoreAction(MVT::i64, MVT::i8 , Expand);
113   setTruncStoreAction(MVT::i32, MVT::i16, Expand);
114   setTruncStoreAction(MVT::i32, MVT::i8 , Expand);
115   setTruncStoreAction(MVT::i16, MVT::i8,  Expand);
116
117   // SETOEQ and SETUNE require checking two conditions.
118   setCondCodeAction(ISD::SETOEQ, MVT::f32, Expand);
119   setCondCodeAction(ISD::SETOEQ, MVT::f64, Expand);
120   setCondCodeAction(ISD::SETOEQ, MVT::f80, Expand);
121   setCondCodeAction(ISD::SETUNE, MVT::f32, Expand);
122   setCondCodeAction(ISD::SETUNE, MVT::f64, Expand);
123   setCondCodeAction(ISD::SETUNE, MVT::f80, Expand);
124
125   // Promote all UINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have this
126   // operation.
127   setOperationAction(ISD::UINT_TO_FP       , MVT::i1   , Promote);
128   setOperationAction(ISD::UINT_TO_FP       , MVT::i8   , Promote);
129   setOperationAction(ISD::UINT_TO_FP       , MVT::i16  , Promote);
130
131   if (Subtarget->is64Bit()) {
132     setOperationAction(ISD::UINT_TO_FP     , MVT::i32  , Promote);
133     setOperationAction(ISD::UINT_TO_FP     , MVT::i64  , Expand);
134   } else if (!UseSoftFloat) {
135     if (X86ScalarSSEf64) {
136       // We have an impenetrably clever algorithm for ui64->double only.
137       setOperationAction(ISD::UINT_TO_FP   , MVT::i64  , Custom);
138     }
139     // We have an algorithm for SSE2, and we turn this into a 64-bit
140     // FILD for other targets.
141     setOperationAction(ISD::UINT_TO_FP   , MVT::i32  , Custom);
142   }
143
144   // Promote i1/i8 SINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have
145   // this operation.
146   setOperationAction(ISD::SINT_TO_FP       , MVT::i1   , Promote);
147   setOperationAction(ISD::SINT_TO_FP       , MVT::i8   , Promote);
148
149   if (!UseSoftFloat) {
150     // SSE has no i16 to fp conversion, only i32
151     if (X86ScalarSSEf32) {
152       setOperationAction(ISD::SINT_TO_FP     , MVT::i16  , Promote);
153       // f32 and f64 cases are Legal, f80 case is not
154       setOperationAction(ISD::SINT_TO_FP     , MVT::i32  , Custom);
155     } else {
156       setOperationAction(ISD::SINT_TO_FP     , MVT::i16  , Custom);
157       setOperationAction(ISD::SINT_TO_FP     , MVT::i32  , Custom);
158     }
159   } else {
160     setOperationAction(ISD::SINT_TO_FP     , MVT::i16  , Promote);
161     setOperationAction(ISD::SINT_TO_FP     , MVT::i32  , Promote);
162   }
163
164   // In 32-bit mode these are custom lowered.  In 64-bit mode F32 and F64
165   // are Legal, f80 is custom lowered.
166   setOperationAction(ISD::FP_TO_SINT     , MVT::i64  , Custom);
167   setOperationAction(ISD::SINT_TO_FP     , MVT::i64  , Custom);
168
169   // Promote i1/i8 FP_TO_SINT to larger FP_TO_SINTS's, as X86 doesn't have
170   // this operation.
171   setOperationAction(ISD::FP_TO_SINT       , MVT::i1   , Promote);
172   setOperationAction(ISD::FP_TO_SINT       , MVT::i8   , Promote);
173
174   if (X86ScalarSSEf32) {
175     setOperationAction(ISD::FP_TO_SINT     , MVT::i16  , Promote);
176     // f32 and f64 cases are Legal, f80 case is not
177     setOperationAction(ISD::FP_TO_SINT     , MVT::i32  , Custom);
178   } else {
179     setOperationAction(ISD::FP_TO_SINT     , MVT::i16  , Custom);
180     setOperationAction(ISD::FP_TO_SINT     , MVT::i32  , Custom);
181   }
182
183   // Handle FP_TO_UINT by promoting the destination to a larger signed
184   // conversion.
185   setOperationAction(ISD::FP_TO_UINT       , MVT::i1   , Promote);
186   setOperationAction(ISD::FP_TO_UINT       , MVT::i8   , Promote);
187   setOperationAction(ISD::FP_TO_UINT       , MVT::i16  , Promote);
188
189   if (Subtarget->is64Bit()) {
190     setOperationAction(ISD::FP_TO_UINT     , MVT::i64  , Expand);
191     setOperationAction(ISD::FP_TO_UINT     , MVT::i32  , Promote);
192   } else if (!UseSoftFloat) {
193     if (X86ScalarSSEf32 && !Subtarget->hasSSE3())
194       // Expand FP_TO_UINT into a select.
195       // FIXME: We would like to use a Custom expander here eventually to do
196       // the optimal thing for SSE vs. the default expansion in the legalizer.
197       setOperationAction(ISD::FP_TO_UINT   , MVT::i32  , Expand);
198     else
199       // With SSE3 we can use fisttpll to convert to a signed i64; without
200       // SSE, we're stuck with a fistpll.
201       setOperationAction(ISD::FP_TO_UINT   , MVT::i32  , Custom);
202   }
203
204   // TODO: when we have SSE, these could be more efficient, by using movd/movq.
205   if (!X86ScalarSSEf64) {
206     setOperationAction(ISD::BIT_CONVERT      , MVT::f32  , Expand);
207     setOperationAction(ISD::BIT_CONVERT      , MVT::i32  , Expand);
208   }
209
210   // Scalar integer divide and remainder are lowered to use operations that
211   // produce two results, to match the available instructions. This exposes
212   // the two-result form to trivial CSE, which is able to combine x/y and x%y
213   // into a single instruction.
214   //
215   // Scalar integer multiply-high is also lowered to use two-result
216   // operations, to match the available instructions. However, plain multiply
217   // (low) operations are left as Legal, as there are single-result
218   // instructions for this in x86. Using the two-result multiply instructions
219   // when both high and low results are needed must be arranged by dagcombine.
220   setOperationAction(ISD::MULHS           , MVT::i8    , Expand);
221   setOperationAction(ISD::MULHU           , MVT::i8    , Expand);
222   setOperationAction(ISD::SDIV            , MVT::i8    , Expand);
223   setOperationAction(ISD::UDIV            , MVT::i8    , Expand);
224   setOperationAction(ISD::SREM            , MVT::i8    , Expand);
225   setOperationAction(ISD::UREM            , MVT::i8    , Expand);
226   setOperationAction(ISD::MULHS           , MVT::i16   , Expand);
227   setOperationAction(ISD::MULHU           , MVT::i16   , Expand);
228   setOperationAction(ISD::SDIV            , MVT::i16   , Expand);
229   setOperationAction(ISD::UDIV            , MVT::i16   , Expand);
230   setOperationAction(ISD::SREM            , MVT::i16   , Expand);
231   setOperationAction(ISD::UREM            , MVT::i16   , Expand);
232   setOperationAction(ISD::MULHS           , MVT::i32   , Expand);
233   setOperationAction(ISD::MULHU           , MVT::i32   , Expand);
234   setOperationAction(ISD::SDIV            , MVT::i32   , Expand);
235   setOperationAction(ISD::UDIV            , MVT::i32   , Expand);
236   setOperationAction(ISD::SREM            , MVT::i32   , Expand);
237   setOperationAction(ISD::UREM            , MVT::i32   , Expand);
238   setOperationAction(ISD::MULHS           , MVT::i64   , Expand);
239   setOperationAction(ISD::MULHU           , MVT::i64   , Expand);
240   setOperationAction(ISD::SDIV            , MVT::i64   , Expand);
241   setOperationAction(ISD::UDIV            , MVT::i64   , Expand);
242   setOperationAction(ISD::SREM            , MVT::i64   , Expand);
243   setOperationAction(ISD::UREM            , MVT::i64   , Expand);
244
245   setOperationAction(ISD::BR_JT            , MVT::Other, Expand);
246   setOperationAction(ISD::BRCOND           , MVT::Other, Custom);
247   setOperationAction(ISD::BR_CC            , MVT::Other, Expand);
248   setOperationAction(ISD::SELECT_CC        , MVT::Other, Expand);
249   if (Subtarget->is64Bit())
250     setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i32, Legal);
251   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16  , Legal);
252   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8   , Legal);
253   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1   , Expand);
254   setOperationAction(ISD::FP_ROUND_INREG   , MVT::f32  , Expand);
255   setOperationAction(ISD::FREM             , MVT::f32  , Expand);
256   setOperationAction(ISD::FREM             , MVT::f64  , Expand);
257   setOperationAction(ISD::FREM             , MVT::f80  , Expand);
258   setOperationAction(ISD::FLT_ROUNDS_      , MVT::i32  , Custom);
259
260   setOperationAction(ISD::CTPOP            , MVT::i8   , Expand);
261   setOperationAction(ISD::CTTZ             , MVT::i8   , Custom);
262   setOperationAction(ISD::CTLZ             , MVT::i8   , Custom);
263   setOperationAction(ISD::CTPOP            , MVT::i16  , Expand);
264   setOperationAction(ISD::CTTZ             , MVT::i16  , Custom);
265   setOperationAction(ISD::CTLZ             , MVT::i16  , Custom);
266   setOperationAction(ISD::CTPOP            , MVT::i32  , Expand);
267   setOperationAction(ISD::CTTZ             , MVT::i32  , Custom);
268   setOperationAction(ISD::CTLZ             , MVT::i32  , Custom);
269   if (Subtarget->is64Bit()) {
270     setOperationAction(ISD::CTPOP          , MVT::i64  , Expand);
271     setOperationAction(ISD::CTTZ           , MVT::i64  , Custom);
272     setOperationAction(ISD::CTLZ           , MVT::i64  , Custom);
273   }
274
275   setOperationAction(ISD::READCYCLECOUNTER , MVT::i64  , Custom);
276   setOperationAction(ISD::BSWAP            , MVT::i16  , Expand);
277
278   // These should be promoted to a larger select which is supported.
279   setOperationAction(ISD::SELECT           , MVT::i1   , Promote);
280   setOperationAction(ISD::SELECT           , MVT::i8   , Promote);
281   // X86 wants to expand cmov itself.
282   setOperationAction(ISD::SELECT          , MVT::i16  , Custom);
283   setOperationAction(ISD::SELECT          , MVT::i32  , Custom);
284   setOperationAction(ISD::SELECT          , MVT::f32  , Custom);
285   setOperationAction(ISD::SELECT          , MVT::f64  , Custom);
286   setOperationAction(ISD::SELECT          , MVT::f80  , Custom);
287   setOperationAction(ISD::SETCC           , MVT::i8   , Custom);
288   setOperationAction(ISD::SETCC           , MVT::i16  , Custom);
289   setOperationAction(ISD::SETCC           , MVT::i32  , Custom);
290   setOperationAction(ISD::SETCC           , MVT::f32  , Custom);
291   setOperationAction(ISD::SETCC           , MVT::f64  , Custom);
292   setOperationAction(ISD::SETCC           , MVT::f80  , Custom);
293   if (Subtarget->is64Bit()) {
294     setOperationAction(ISD::SELECT        , MVT::i64  , Custom);
295     setOperationAction(ISD::SETCC         , MVT::i64  , Custom);
296   }
297   // X86 ret instruction may pop stack.
298   setOperationAction(ISD::RET             , MVT::Other, Custom);
299   setOperationAction(ISD::EH_RETURN       , MVT::Other, Custom);
300
301   // Darwin ABI issue.
302   setOperationAction(ISD::ConstantPool    , MVT::i32  , Custom);
303   setOperationAction(ISD::JumpTable       , MVT::i32  , Custom);
304   setOperationAction(ISD::GlobalAddress   , MVT::i32  , Custom);
305   setOperationAction(ISD::GlobalTLSAddress, MVT::i32  , Custom);
306   if (Subtarget->is64Bit())
307     setOperationAction(ISD::GlobalTLSAddress, MVT::i64, Custom);
308   setOperationAction(ISD::ExternalSymbol  , MVT::i32  , Custom);
309   if (Subtarget->is64Bit()) {
310     setOperationAction(ISD::ConstantPool  , MVT::i64  , Custom);
311     setOperationAction(ISD::JumpTable     , MVT::i64  , Custom);
312     setOperationAction(ISD::GlobalAddress , MVT::i64  , Custom);
313     setOperationAction(ISD::ExternalSymbol, MVT::i64  , Custom);
314   }
315   // 64-bit addm sub, shl, sra, srl (iff 32-bit x86)
316   setOperationAction(ISD::SHL_PARTS       , MVT::i32  , Custom);
317   setOperationAction(ISD::SRA_PARTS       , MVT::i32  , Custom);
318   setOperationAction(ISD::SRL_PARTS       , MVT::i32  , Custom);
319   if (Subtarget->is64Bit()) {
320     setOperationAction(ISD::SHL_PARTS     , MVT::i64  , Custom);
321     setOperationAction(ISD::SRA_PARTS     , MVT::i64  , Custom);
322     setOperationAction(ISD::SRL_PARTS     , MVT::i64  , Custom);
323   }
324
325   if (Subtarget->hasSSE1())
326     setOperationAction(ISD::PREFETCH      , MVT::Other, Legal);
327
328   if (!Subtarget->hasSSE2())
329     setOperationAction(ISD::MEMBARRIER    , MVT::Other, Expand);
330
331   // Expand certain atomics
332   setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i8, Custom);
333   setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i16, Custom);
334   setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i32, Custom);
335   setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i64, Custom);
336
337   setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i8, Custom);
338   setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i16, Custom);
339   setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i32, Custom);
340   setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i64, Custom);
341
342   if (!Subtarget->is64Bit()) {
343     setOperationAction(ISD::ATOMIC_LOAD_ADD, MVT::i64, Custom);
344     setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i64, Custom);
345     setOperationAction(ISD::ATOMIC_LOAD_AND, MVT::i64, Custom);
346     setOperationAction(ISD::ATOMIC_LOAD_OR, MVT::i64, Custom);
347     setOperationAction(ISD::ATOMIC_LOAD_XOR, MVT::i64, Custom);
348     setOperationAction(ISD::ATOMIC_LOAD_NAND, MVT::i64, Custom);
349     setOperationAction(ISD::ATOMIC_SWAP, MVT::i64, Custom);
350   }
351
352   // Use the default ISD::DBG_STOPPOINT, ISD::DECLARE expansion.
353   setOperationAction(ISD::DBG_STOPPOINT, MVT::Other, Expand);
354   // FIXME - use subtarget debug flags
355   if (!Subtarget->isTargetDarwin() &&
356       !Subtarget->isTargetELF() &&
357       !Subtarget->isTargetCygMing()) {
358     setOperationAction(ISD::DBG_LABEL, MVT::Other, Expand);
359     setOperationAction(ISD::EH_LABEL, MVT::Other, Expand);
360   }
361
362   setOperationAction(ISD::EXCEPTIONADDR, MVT::i64, Expand);
363   setOperationAction(ISD::EHSELECTION,   MVT::i64, Expand);
364   setOperationAction(ISD::EXCEPTIONADDR, MVT::i32, Expand);
365   setOperationAction(ISD::EHSELECTION,   MVT::i32, Expand);
366   if (Subtarget->is64Bit()) {
367     setExceptionPointerRegister(X86::RAX);
368     setExceptionSelectorRegister(X86::RDX);
369   } else {
370     setExceptionPointerRegister(X86::EAX);
371     setExceptionSelectorRegister(X86::EDX);
372   }
373   setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i32, Custom);
374   setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i64, Custom);
375
376   setOperationAction(ISD::TRAMPOLINE, MVT::Other, Custom);
377
378   setOperationAction(ISD::TRAP, MVT::Other, Legal);
379
380   // VASTART needs to be custom lowered to use the VarArgsFrameIndex
381   setOperationAction(ISD::VASTART           , MVT::Other, Custom);
382   setOperationAction(ISD::VAEND             , MVT::Other, Expand);
383   if (Subtarget->is64Bit()) {
384     setOperationAction(ISD::VAARG           , MVT::Other, Custom);
385     setOperationAction(ISD::VACOPY          , MVT::Other, Custom);
386   } else {
387     setOperationAction(ISD::VAARG           , MVT::Other, Expand);
388     setOperationAction(ISD::VACOPY          , MVT::Other, Expand);
389   }
390
391   setOperationAction(ISD::STACKSAVE,          MVT::Other, Expand);
392   setOperationAction(ISD::STACKRESTORE,       MVT::Other, Expand);
393   if (Subtarget->is64Bit())
394     setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i64, Expand);
395   if (Subtarget->isTargetCygMing())
396     setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Custom);
397   else
398     setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Expand);
399
400   if (!UseSoftFloat && X86ScalarSSEf64) {
401     // f32 and f64 use SSE.
402     // Set up the FP register classes.
403     addRegisterClass(MVT::f32, X86::FR32RegisterClass);
404     addRegisterClass(MVT::f64, X86::FR64RegisterClass);
405
406     // Use ANDPD to simulate FABS.
407     setOperationAction(ISD::FABS , MVT::f64, Custom);
408     setOperationAction(ISD::FABS , MVT::f32, Custom);
409
410     // Use XORP to simulate FNEG.
411     setOperationAction(ISD::FNEG , MVT::f64, Custom);
412     setOperationAction(ISD::FNEG , MVT::f32, Custom);
413
414     // Use ANDPD and ORPD to simulate FCOPYSIGN.
415     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
416     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
417
418     // We don't support sin/cos/fmod
419     setOperationAction(ISD::FSIN , MVT::f64, Expand);
420     setOperationAction(ISD::FCOS , MVT::f64, Expand);
421     setOperationAction(ISD::FSIN , MVT::f32, Expand);
422     setOperationAction(ISD::FCOS , MVT::f32, Expand);
423
424     // Expand FP immediates into loads from the stack, except for the special
425     // cases we handle.
426     addLegalFPImmediate(APFloat(+0.0)); // xorpd
427     addLegalFPImmediate(APFloat(+0.0f)); // xorps
428   } else if (!UseSoftFloat && X86ScalarSSEf32) {
429     // Use SSE for f32, x87 for f64.
430     // Set up the FP register classes.
431     addRegisterClass(MVT::f32, X86::FR32RegisterClass);
432     addRegisterClass(MVT::f64, X86::RFP64RegisterClass);
433
434     // Use ANDPS to simulate FABS.
435     setOperationAction(ISD::FABS , MVT::f32, Custom);
436
437     // Use XORP to simulate FNEG.
438     setOperationAction(ISD::FNEG , MVT::f32, Custom);
439
440     setOperationAction(ISD::UNDEF,     MVT::f64, Expand);
441
442     // Use ANDPS and ORPS to simulate FCOPYSIGN.
443     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
444     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
445
446     // We don't support sin/cos/fmod
447     setOperationAction(ISD::FSIN , MVT::f32, Expand);
448     setOperationAction(ISD::FCOS , MVT::f32, Expand);
449
450     // Special cases we handle for FP constants.
451     addLegalFPImmediate(APFloat(+0.0f)); // xorps
452     addLegalFPImmediate(APFloat(+0.0)); // FLD0
453     addLegalFPImmediate(APFloat(+1.0)); // FLD1
454     addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
455     addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
456
457     if (!UnsafeFPMath) {
458       setOperationAction(ISD::FSIN           , MVT::f64  , Expand);
459       setOperationAction(ISD::FCOS           , MVT::f64  , Expand);
460     }
461   } else if (!UseSoftFloat) {
462     // f32 and f64 in x87.
463     // Set up the FP register classes.
464     addRegisterClass(MVT::f64, X86::RFP64RegisterClass);
465     addRegisterClass(MVT::f32, X86::RFP32RegisterClass);
466
467     setOperationAction(ISD::UNDEF,     MVT::f64, Expand);
468     setOperationAction(ISD::UNDEF,     MVT::f32, Expand);
469     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
470     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand);
471
472     if (!UnsafeFPMath) {
473       setOperationAction(ISD::FSIN           , MVT::f64  , Expand);
474       setOperationAction(ISD::FCOS           , MVT::f64  , Expand);
475     }
476     addLegalFPImmediate(APFloat(+0.0)); // FLD0
477     addLegalFPImmediate(APFloat(+1.0)); // FLD1
478     addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
479     addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
480     addLegalFPImmediate(APFloat(+0.0f)); // FLD0
481     addLegalFPImmediate(APFloat(+1.0f)); // FLD1
482     addLegalFPImmediate(APFloat(-0.0f)); // FLD0/FCHS
483     addLegalFPImmediate(APFloat(-1.0f)); // FLD1/FCHS
484   }
485
486   // Long double always uses X87.
487   if (!UseSoftFloat) {
488     addRegisterClass(MVT::f80, X86::RFP80RegisterClass);
489     setOperationAction(ISD::UNDEF,     MVT::f80, Expand);
490     setOperationAction(ISD::FCOPYSIGN, MVT::f80, Expand);
491     {
492       bool ignored;
493       APFloat TmpFlt(+0.0);
494       TmpFlt.convert(APFloat::x87DoubleExtended, APFloat::rmNearestTiesToEven,
495                      &ignored);
496       addLegalFPImmediate(TmpFlt);  // FLD0
497       TmpFlt.changeSign();
498       addLegalFPImmediate(TmpFlt);  // FLD0/FCHS
499       APFloat TmpFlt2(+1.0);
500       TmpFlt2.convert(APFloat::x87DoubleExtended, APFloat::rmNearestTiesToEven,
501                       &ignored);
502       addLegalFPImmediate(TmpFlt2);  // FLD1
503       TmpFlt2.changeSign();
504       addLegalFPImmediate(TmpFlt2);  // FLD1/FCHS
505     }
506
507     if (!UnsafeFPMath) {
508       setOperationAction(ISD::FSIN           , MVT::f80  , Expand);
509       setOperationAction(ISD::FCOS           , MVT::f80  , Expand);
510     }
511   }
512
513   // Always use a library call for pow.
514   setOperationAction(ISD::FPOW             , MVT::f32  , Expand);
515   setOperationAction(ISD::FPOW             , MVT::f64  , Expand);
516   setOperationAction(ISD::FPOW             , MVT::f80  , Expand);
517
518   setOperationAction(ISD::FLOG, MVT::f80, Expand);
519   setOperationAction(ISD::FLOG2, MVT::f80, Expand);
520   setOperationAction(ISD::FLOG10, MVT::f80, Expand);
521   setOperationAction(ISD::FEXP, MVT::f80, Expand);
522   setOperationAction(ISD::FEXP2, MVT::f80, Expand);
523
524   // First set operation action for all vector types to either promote
525   // (for widening) or expand (for scalarization). Then we will selectively
526   // turn on ones that can be effectively codegen'd.
527   for (unsigned VT = (unsigned)MVT::FIRST_VECTOR_VALUETYPE;
528        VT <= (unsigned)MVT::LAST_VECTOR_VALUETYPE; ++VT) {
529     setOperationAction(ISD::ADD , (MVT::SimpleValueType)VT, Expand);
530     setOperationAction(ISD::SUB , (MVT::SimpleValueType)VT, Expand);
531     setOperationAction(ISD::FADD, (MVT::SimpleValueType)VT, Expand);
532     setOperationAction(ISD::FNEG, (MVT::SimpleValueType)VT, Expand);
533     setOperationAction(ISD::FSUB, (MVT::SimpleValueType)VT, Expand);
534     setOperationAction(ISD::MUL , (MVT::SimpleValueType)VT, Expand);
535     setOperationAction(ISD::FMUL, (MVT::SimpleValueType)VT, Expand);
536     setOperationAction(ISD::SDIV, (MVT::SimpleValueType)VT, Expand);
537     setOperationAction(ISD::UDIV, (MVT::SimpleValueType)VT, Expand);
538     setOperationAction(ISD::FDIV, (MVT::SimpleValueType)VT, Expand);
539     setOperationAction(ISD::SREM, (MVT::SimpleValueType)VT, Expand);
540     setOperationAction(ISD::UREM, (MVT::SimpleValueType)VT, Expand);
541     setOperationAction(ISD::LOAD, (MVT::SimpleValueType)VT, Expand);
542     setOperationAction(ISD::VECTOR_SHUFFLE, (MVT::SimpleValueType)VT, Expand);
543     setOperationAction(ISD::EXTRACT_VECTOR_ELT,(MVT::SimpleValueType)VT,Expand);
544     setOperationAction(ISD::EXTRACT_SUBVECTOR,(MVT::SimpleValueType)VT,Expand);
545     setOperationAction(ISD::INSERT_VECTOR_ELT,(MVT::SimpleValueType)VT, Expand);
546     setOperationAction(ISD::FABS, (MVT::SimpleValueType)VT, Expand);
547     setOperationAction(ISD::FSIN, (MVT::SimpleValueType)VT, Expand);
548     setOperationAction(ISD::FCOS, (MVT::SimpleValueType)VT, Expand);
549     setOperationAction(ISD::FREM, (MVT::SimpleValueType)VT, Expand);
550     setOperationAction(ISD::FPOWI, (MVT::SimpleValueType)VT, Expand);
551     setOperationAction(ISD::FSQRT, (MVT::SimpleValueType)VT, Expand);
552     setOperationAction(ISD::FCOPYSIGN, (MVT::SimpleValueType)VT, Expand);
553     setOperationAction(ISD::SMUL_LOHI, (MVT::SimpleValueType)VT, Expand);
554     setOperationAction(ISD::UMUL_LOHI, (MVT::SimpleValueType)VT, Expand);
555     setOperationAction(ISD::SDIVREM, (MVT::SimpleValueType)VT, Expand);
556     setOperationAction(ISD::UDIVREM, (MVT::SimpleValueType)VT, Expand);
557     setOperationAction(ISD::FPOW, (MVT::SimpleValueType)VT, Expand);
558     setOperationAction(ISD::CTPOP, (MVT::SimpleValueType)VT, Expand);
559     setOperationAction(ISD::CTTZ, (MVT::SimpleValueType)VT, Expand);
560     setOperationAction(ISD::CTLZ, (MVT::SimpleValueType)VT, Expand);
561     setOperationAction(ISD::SHL, (MVT::SimpleValueType)VT, Expand);
562     setOperationAction(ISD::SRA, (MVT::SimpleValueType)VT, Expand);
563     setOperationAction(ISD::SRL, (MVT::SimpleValueType)VT, Expand);
564     setOperationAction(ISD::ROTL, (MVT::SimpleValueType)VT, Expand);
565     setOperationAction(ISD::ROTR, (MVT::SimpleValueType)VT, Expand);
566     setOperationAction(ISD::BSWAP, (MVT::SimpleValueType)VT, Expand);
567     setOperationAction(ISD::VSETCC, (MVT::SimpleValueType)VT, Expand);
568     setOperationAction(ISD::FLOG, (MVT::SimpleValueType)VT, Expand);
569     setOperationAction(ISD::FLOG2, (MVT::SimpleValueType)VT, Expand);
570     setOperationAction(ISD::FLOG10, (MVT::SimpleValueType)VT, Expand);
571     setOperationAction(ISD::FEXP, (MVT::SimpleValueType)VT, Expand);
572     setOperationAction(ISD::FEXP2, (MVT::SimpleValueType)VT, Expand);
573     setOperationAction(ISD::FP_TO_UINT, (MVT::SimpleValueType)VT, Expand);
574     setOperationAction(ISD::FP_TO_SINT, (MVT::SimpleValueType)VT, Expand);
575     setOperationAction(ISD::UINT_TO_FP, (MVT::SimpleValueType)VT, Expand);
576     setOperationAction(ISD::SINT_TO_FP, (MVT::SimpleValueType)VT, Expand);
577   }
578
579   // FIXME: In order to prevent SSE instructions being expanded to MMX ones
580   // with -msoft-float, disable use of MMX as well.
581   if (!UseSoftFloat && !DisableMMX && Subtarget->hasMMX()) {
582     addRegisterClass(MVT::v8i8,  X86::VR64RegisterClass);
583     addRegisterClass(MVT::v4i16, X86::VR64RegisterClass);
584     addRegisterClass(MVT::v2i32, X86::VR64RegisterClass);
585     addRegisterClass(MVT::v2f32, X86::VR64RegisterClass);
586     addRegisterClass(MVT::v1i64, X86::VR64RegisterClass);
587
588     setOperationAction(ISD::ADD,                MVT::v8i8,  Legal);
589     setOperationAction(ISD::ADD,                MVT::v4i16, Legal);
590     setOperationAction(ISD::ADD,                MVT::v2i32, Legal);
591     setOperationAction(ISD::ADD,                MVT::v1i64, Legal);
592
593     setOperationAction(ISD::SUB,                MVT::v8i8,  Legal);
594     setOperationAction(ISD::SUB,                MVT::v4i16, Legal);
595     setOperationAction(ISD::SUB,                MVT::v2i32, Legal);
596     setOperationAction(ISD::SUB,                MVT::v1i64, Legal);
597
598     setOperationAction(ISD::MULHS,              MVT::v4i16, Legal);
599     setOperationAction(ISD::MUL,                MVT::v4i16, Legal);
600
601     setOperationAction(ISD::AND,                MVT::v8i8,  Promote);
602     AddPromotedToType (ISD::AND,                MVT::v8i8,  MVT::v1i64);
603     setOperationAction(ISD::AND,                MVT::v4i16, Promote);
604     AddPromotedToType (ISD::AND,                MVT::v4i16, MVT::v1i64);
605     setOperationAction(ISD::AND,                MVT::v2i32, Promote);
606     AddPromotedToType (ISD::AND,                MVT::v2i32, MVT::v1i64);
607     setOperationAction(ISD::AND,                MVT::v1i64, Legal);
608
609     setOperationAction(ISD::OR,                 MVT::v8i8,  Promote);
610     AddPromotedToType (ISD::OR,                 MVT::v8i8,  MVT::v1i64);
611     setOperationAction(ISD::OR,                 MVT::v4i16, Promote);
612     AddPromotedToType (ISD::OR,                 MVT::v4i16, MVT::v1i64);
613     setOperationAction(ISD::OR,                 MVT::v2i32, Promote);
614     AddPromotedToType (ISD::OR,                 MVT::v2i32, MVT::v1i64);
615     setOperationAction(ISD::OR,                 MVT::v1i64, Legal);
616
617     setOperationAction(ISD::XOR,                MVT::v8i8,  Promote);
618     AddPromotedToType (ISD::XOR,                MVT::v8i8,  MVT::v1i64);
619     setOperationAction(ISD::XOR,                MVT::v4i16, Promote);
620     AddPromotedToType (ISD::XOR,                MVT::v4i16, MVT::v1i64);
621     setOperationAction(ISD::XOR,                MVT::v2i32, Promote);
622     AddPromotedToType (ISD::XOR,                MVT::v2i32, MVT::v1i64);
623     setOperationAction(ISD::XOR,                MVT::v1i64, Legal);
624
625     setOperationAction(ISD::LOAD,               MVT::v8i8,  Promote);
626     AddPromotedToType (ISD::LOAD,               MVT::v8i8,  MVT::v1i64);
627     setOperationAction(ISD::LOAD,               MVT::v4i16, Promote);
628     AddPromotedToType (ISD::LOAD,               MVT::v4i16, MVT::v1i64);
629     setOperationAction(ISD::LOAD,               MVT::v2i32, Promote);
630     AddPromotedToType (ISD::LOAD,               MVT::v2i32, MVT::v1i64);
631     setOperationAction(ISD::LOAD,               MVT::v2f32, Promote);
632     AddPromotedToType (ISD::LOAD,               MVT::v2f32, MVT::v1i64);
633     setOperationAction(ISD::LOAD,               MVT::v1i64, Legal);
634
635     setOperationAction(ISD::BUILD_VECTOR,       MVT::v8i8,  Custom);
636     setOperationAction(ISD::BUILD_VECTOR,       MVT::v4i16, Custom);
637     setOperationAction(ISD::BUILD_VECTOR,       MVT::v2i32, Custom);
638     setOperationAction(ISD::BUILD_VECTOR,       MVT::v2f32, Custom);
639     setOperationAction(ISD::BUILD_VECTOR,       MVT::v1i64, Custom);
640
641     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v8i8,  Custom);
642     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v4i16, Custom);
643     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v2i32, Custom);
644     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v1i64, Custom);
645
646     setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v2f32, Custom);
647     setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v8i8,  Custom);
648     setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v4i16, Custom);
649     setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v1i64, Custom);
650
651     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4i16, Custom);
652
653     setTruncStoreAction(MVT::v8i16,             MVT::v8i8, Expand);
654     setOperationAction(ISD::TRUNCATE,           MVT::v8i8, Expand);
655     setOperationAction(ISD::SELECT,             MVT::v8i8, Promote);
656     setOperationAction(ISD::SELECT,             MVT::v4i16, Promote);
657     setOperationAction(ISD::SELECT,             MVT::v2i32, Promote);
658     setOperationAction(ISD::SELECT,             MVT::v1i64, Custom);
659     setOperationAction(ISD::VSETCC,             MVT::v8i8, Custom);
660     setOperationAction(ISD::VSETCC,             MVT::v4i16, Custom);
661     setOperationAction(ISD::VSETCC,             MVT::v2i32, Custom);
662   }
663
664   if (!UseSoftFloat && Subtarget->hasSSE1()) {
665     addRegisterClass(MVT::v4f32, X86::VR128RegisterClass);
666
667     setOperationAction(ISD::FADD,               MVT::v4f32, Legal);
668     setOperationAction(ISD::FSUB,               MVT::v4f32, Legal);
669     setOperationAction(ISD::FMUL,               MVT::v4f32, Legal);
670     setOperationAction(ISD::FDIV,               MVT::v4f32, Legal);
671     setOperationAction(ISD::FSQRT,              MVT::v4f32, Legal);
672     setOperationAction(ISD::FNEG,               MVT::v4f32, Custom);
673     setOperationAction(ISD::LOAD,               MVT::v4f32, Legal);
674     setOperationAction(ISD::BUILD_VECTOR,       MVT::v4f32, Custom);
675     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v4f32, Custom);
676     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
677     setOperationAction(ISD::SELECT,             MVT::v4f32, Custom);
678     setOperationAction(ISD::VSETCC,             MVT::v4f32, Custom);
679   }
680
681   if (!UseSoftFloat && Subtarget->hasSSE2()) {
682     addRegisterClass(MVT::v2f64, X86::VR128RegisterClass);
683
684     // FIXME: Unfortunately -soft-float and -no-implicit-float means XMM
685     // registers cannot be used even for integer operations.
686     addRegisterClass(MVT::v16i8, X86::VR128RegisterClass);
687     addRegisterClass(MVT::v8i16, X86::VR128RegisterClass);
688     addRegisterClass(MVT::v4i32, X86::VR128RegisterClass);
689     addRegisterClass(MVT::v2i64, X86::VR128RegisterClass);
690
691     setOperationAction(ISD::ADD,                MVT::v16i8, Legal);
692     setOperationAction(ISD::ADD,                MVT::v8i16, Legal);
693     setOperationAction(ISD::ADD,                MVT::v4i32, Legal);
694     setOperationAction(ISD::ADD,                MVT::v2i64, Legal);
695     setOperationAction(ISD::MUL,                MVT::v2i64, Custom);
696     setOperationAction(ISD::SUB,                MVT::v16i8, Legal);
697     setOperationAction(ISD::SUB,                MVT::v8i16, Legal);
698     setOperationAction(ISD::SUB,                MVT::v4i32, Legal);
699     setOperationAction(ISD::SUB,                MVT::v2i64, Legal);
700     setOperationAction(ISD::MUL,                MVT::v8i16, Legal);
701     setOperationAction(ISD::FADD,               MVT::v2f64, Legal);
702     setOperationAction(ISD::FSUB,               MVT::v2f64, Legal);
703     setOperationAction(ISD::FMUL,               MVT::v2f64, Legal);
704     setOperationAction(ISD::FDIV,               MVT::v2f64, Legal);
705     setOperationAction(ISD::FSQRT,              MVT::v2f64, Legal);
706     setOperationAction(ISD::FNEG,               MVT::v2f64, Custom);
707
708     setOperationAction(ISD::VSETCC,             MVT::v2f64, Custom);
709     setOperationAction(ISD::VSETCC,             MVT::v16i8, Custom);
710     setOperationAction(ISD::VSETCC,             MVT::v8i16, Custom);
711     setOperationAction(ISD::VSETCC,             MVT::v4i32, Custom);
712
713     setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v16i8, Custom);
714     setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v8i16, Custom);
715     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v8i16, Custom);
716     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4i32, Custom);
717     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4f32, Custom);
718
719     // Custom lower build_vector, vector_shuffle, and extract_vector_elt.
720     for (unsigned i = (unsigned)MVT::v16i8; i != (unsigned)MVT::v2i64; ++i) {
721       MVT VT = (MVT::SimpleValueType)i;
722       // Do not attempt to custom lower non-power-of-2 vectors
723       if (!isPowerOf2_32(VT.getVectorNumElements()))
724         continue;
725       // Do not attempt to custom lower non-128-bit vectors
726       if (!VT.is128BitVector())
727         continue;
728       setOperationAction(ISD::BUILD_VECTOR,       VT, Custom);
729       setOperationAction(ISD::VECTOR_SHUFFLE,     VT, Custom);
730       setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
731     }
732
733     setOperationAction(ISD::BUILD_VECTOR,       MVT::v2f64, Custom);
734     setOperationAction(ISD::BUILD_VECTOR,       MVT::v2i64, Custom);
735     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v2f64, Custom);
736     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v2i64, Custom);
737     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2f64, Custom);
738     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Custom);
739
740     if (Subtarget->is64Bit()) {
741       setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2i64, Custom);
742       setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
743     }
744
745     // Promote v16i8, v8i16, v4i32 load, select, and, or, xor to v2i64.
746     for (unsigned i = (unsigned)MVT::v16i8; i != (unsigned)MVT::v2i64; i++) {
747       MVT VT = (MVT::SimpleValueType)i;
748
749       // Do not attempt to promote non-128-bit vectors
750       if (!VT.is128BitVector()) {
751         continue;
752       }
753       setOperationAction(ISD::AND,    VT, Promote);
754       AddPromotedToType (ISD::AND,    VT, MVT::v2i64);
755       setOperationAction(ISD::OR,     VT, Promote);
756       AddPromotedToType (ISD::OR,     VT, MVT::v2i64);
757       setOperationAction(ISD::XOR,    VT, Promote);
758       AddPromotedToType (ISD::XOR,    VT, MVT::v2i64);
759       setOperationAction(ISD::LOAD,   VT, Promote);
760       AddPromotedToType (ISD::LOAD,   VT, MVT::v2i64);
761       setOperationAction(ISD::SELECT, VT, Promote);
762       AddPromotedToType (ISD::SELECT, VT, MVT::v2i64);
763     }
764
765     setTruncStoreAction(MVT::f64, MVT::f32, Expand);
766
767     // Custom lower v2i64 and v2f64 selects.
768     setOperationAction(ISD::LOAD,               MVT::v2f64, Legal);
769     setOperationAction(ISD::LOAD,               MVT::v2i64, Legal);
770     setOperationAction(ISD::SELECT,             MVT::v2f64, Custom);
771     setOperationAction(ISD::SELECT,             MVT::v2i64, Custom);
772
773     setOperationAction(ISD::FP_TO_SINT,         MVT::v4i32, Legal);
774     setOperationAction(ISD::SINT_TO_FP,         MVT::v4i32, Legal);
775     if (!DisableMMX && Subtarget->hasMMX()) {
776       setOperationAction(ISD::FP_TO_SINT,         MVT::v2i32, Custom);
777       setOperationAction(ISD::SINT_TO_FP,         MVT::v2i32, Custom);
778     }
779   }
780
781   if (Subtarget->hasSSE41()) {
782     // FIXME: Do we need to handle scalar-to-vector here?
783     setOperationAction(ISD::MUL,                MVT::v4i32, Legal);
784
785     // i8 and i16 vectors are custom , because the source register and source
786     // source memory operand types are not the same width.  f32 vectors are
787     // custom since the immediate controlling the insert encodes additional
788     // information.
789     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v16i8, Custom);
790     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v8i16, Custom);
791     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4i32, Custom);
792     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4f32, Custom);
793
794     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i8, Custom);
795     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i16, Custom);
796     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i32, Custom);
797     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
798
799     if (Subtarget->is64Bit()) {
800       setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2i64, Legal);
801       setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Legal);
802     }
803   }
804
805   if (Subtarget->hasSSE42()) {
806     setOperationAction(ISD::VSETCC,             MVT::v2i64, Custom);
807   }
808
809   if (!UseSoftFloat && Subtarget->hasAVX()) {
810     addRegisterClass(MVT::v8f32, X86::VR256RegisterClass);
811     addRegisterClass(MVT::v4f64, X86::VR256RegisterClass);
812     addRegisterClass(MVT::v8i32, X86::VR256RegisterClass);
813     addRegisterClass(MVT::v4i64, X86::VR256RegisterClass);
814
815     setOperationAction(ISD::LOAD,               MVT::v8f32, Legal);
816     setOperationAction(ISD::LOAD,               MVT::v8i32, Legal);
817     setOperationAction(ISD::LOAD,               MVT::v4f64, Legal);
818     setOperationAction(ISD::LOAD,               MVT::v4i64, Legal);
819     setOperationAction(ISD::FADD,               MVT::v8f32, Legal);
820     setOperationAction(ISD::FSUB,               MVT::v8f32, Legal);
821     setOperationAction(ISD::FMUL,               MVT::v8f32, Legal);
822     setOperationAction(ISD::FDIV,               MVT::v8f32, Legal);
823     setOperationAction(ISD::FSQRT,              MVT::v8f32, Legal);
824     setOperationAction(ISD::FNEG,               MVT::v8f32, Custom);
825     //setOperationAction(ISD::BUILD_VECTOR,       MVT::v8f32, Custom);
826     //setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v8f32, Custom);
827     //setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8f32, Custom);
828     //setOperationAction(ISD::SELECT,             MVT::v8f32, Custom);
829     //setOperationAction(ISD::VSETCC,             MVT::v8f32, Custom);
830
831     // Operations to consider commented out -v16i16 v32i8
832     //setOperationAction(ISD::ADD,                MVT::v16i16, Legal);
833     setOperationAction(ISD::ADD,                MVT::v8i32, Custom);
834     setOperationAction(ISD::ADD,                MVT::v4i64, Custom);
835     //setOperationAction(ISD::SUB,                MVT::v32i8, Legal);
836     //setOperationAction(ISD::SUB,                MVT::v16i16, Legal);
837     setOperationAction(ISD::SUB,                MVT::v8i32, Custom);
838     setOperationAction(ISD::SUB,                MVT::v4i64, Custom);
839     //setOperationAction(ISD::MUL,                MVT::v16i16, Legal);
840     setOperationAction(ISD::FADD,               MVT::v4f64, Legal);
841     setOperationAction(ISD::FSUB,               MVT::v4f64, Legal);
842     setOperationAction(ISD::FMUL,               MVT::v4f64, Legal);
843     setOperationAction(ISD::FDIV,               MVT::v4f64, Legal);
844     setOperationAction(ISD::FSQRT,              MVT::v4f64, Legal);
845     setOperationAction(ISD::FNEG,               MVT::v4f64, Custom);
846
847     setOperationAction(ISD::VSETCC,             MVT::v4f64, Custom);
848     // setOperationAction(ISD::VSETCC,             MVT::v32i8, Custom);
849     // setOperationAction(ISD::VSETCC,             MVT::v16i16, Custom);
850     setOperationAction(ISD::VSETCC,             MVT::v8i32, Custom);
851
852     // setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v32i8, Custom);
853     // setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v16i16, Custom);
854     // setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v16i16, Custom);
855     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v8i32, Custom);
856     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v8f32, Custom);
857
858     setOperationAction(ISD::BUILD_VECTOR,       MVT::v4f64, Custom);
859     setOperationAction(ISD::BUILD_VECTOR,       MVT::v4i64, Custom);
860     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v4f64, Custom);
861     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v4i64, Custom);
862     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4f64, Custom);
863     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f64, Custom);
864
865 #if 0
866     // Not sure we want to do this since there are no 256-bit integer
867     // operations in AVX
868
869     // Custom lower build_vector, vector_shuffle, and extract_vector_elt.
870     // This includes 256-bit vectors
871     for (unsigned i = (unsigned)MVT::v16i8; i != (unsigned)MVT::v4i64; ++i) {
872       MVT VT = (MVT::SimpleValueType)i;
873
874       // Do not attempt to custom lower non-power-of-2 vectors
875       if (!isPowerOf2_32(VT.getVectorNumElements()))
876         continue;
877
878       setOperationAction(ISD::BUILD_VECTOR,       VT, Custom);
879       setOperationAction(ISD::VECTOR_SHUFFLE,     VT, Custom);
880       setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
881     }
882
883     if (Subtarget->is64Bit()) {
884       setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4i64, Custom);
885       setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i64, Custom);
886     }    
887 #endif
888
889 #if 0
890     // Not sure we want to do this since there are no 256-bit integer
891     // operations in AVX
892
893     // Promote v32i8, v16i16, v8i32 load, select, and, or, xor to v4i64.
894     // Including 256-bit vectors
895     for (unsigned i = (unsigned)MVT::v16i8; i != (unsigned)MVT::v4i64; i++) {
896       MVT VT = (MVT::SimpleValueType)i;
897
898       if (!VT.is256BitVector()) {
899         continue;
900       }
901       setOperationAction(ISD::AND,    VT, Promote);
902       AddPromotedToType (ISD::AND,    VT, MVT::v4i64);
903       setOperationAction(ISD::OR,     VT, Promote);
904       AddPromotedToType (ISD::OR,     VT, MVT::v4i64);
905       setOperationAction(ISD::XOR,    VT, Promote);
906       AddPromotedToType (ISD::XOR,    VT, MVT::v4i64);
907       setOperationAction(ISD::LOAD,   VT, Promote);
908       AddPromotedToType (ISD::LOAD,   VT, MVT::v4i64);
909       setOperationAction(ISD::SELECT, VT, Promote);
910       AddPromotedToType (ISD::SELECT, VT, MVT::v4i64);
911     }
912
913     setTruncStoreAction(MVT::f64, MVT::f32, Expand);
914 #endif
915   }
916
917   // We want to custom lower some of our intrinsics.
918   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
919
920   // Add/Sub/Mul with overflow operations are custom lowered.
921   setOperationAction(ISD::SADDO, MVT::i32, Custom);
922   setOperationAction(ISD::SADDO, MVT::i64, Custom);
923   setOperationAction(ISD::UADDO, MVT::i32, Custom);
924   setOperationAction(ISD::UADDO, MVT::i64, Custom);
925   setOperationAction(ISD::SSUBO, MVT::i32, Custom);
926   setOperationAction(ISD::SSUBO, MVT::i64, Custom);
927   setOperationAction(ISD::USUBO, MVT::i32, Custom);
928   setOperationAction(ISD::USUBO, MVT::i64, Custom);
929   setOperationAction(ISD::SMULO, MVT::i32, Custom);
930   setOperationAction(ISD::SMULO, MVT::i64, Custom);
931
932   if (!Subtarget->is64Bit()) {
933     // These libcalls are not available in 32-bit.
934     setLibcallName(RTLIB::SHL_I128, 0);
935     setLibcallName(RTLIB::SRL_I128, 0);
936     setLibcallName(RTLIB::SRA_I128, 0);
937   }
938
939   // We have target-specific dag combine patterns for the following nodes:
940   setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
941   setTargetDAGCombine(ISD::BUILD_VECTOR);
942   setTargetDAGCombine(ISD::SELECT);
943   setTargetDAGCombine(ISD::SHL);
944   setTargetDAGCombine(ISD::SRA);
945   setTargetDAGCombine(ISD::SRL);
946   setTargetDAGCombine(ISD::STORE);
947   setTargetDAGCombine(ISD::MEMBARRIER);
948   if (Subtarget->is64Bit())
949     setTargetDAGCombine(ISD::MUL);
950
951   computeRegisterProperties();
952
953   // FIXME: These should be based on subtarget info. Plus, the values should
954   // be smaller when we are in optimizing for size mode.
955   maxStoresPerMemset = 16; // For @llvm.memset -> sequence of stores
956   maxStoresPerMemcpy = 16; // For @llvm.memcpy -> sequence of stores
957   maxStoresPerMemmove = 3; // For @llvm.memmove -> sequence of stores
958   allowUnalignedMemoryAccesses = true; // x86 supports it!
959   setPrefLoopAlignment(16);
960   benefitFromCodePlacementOpt = true;
961 }
962
963
964 MVT X86TargetLowering::getSetCCResultType(MVT VT) const {
965   return MVT::i8;
966 }
967
968
969 /// getMaxByValAlign - Helper for getByValTypeAlignment to determine
970 /// the desired ByVal argument alignment.
971 static void getMaxByValAlign(const Type *Ty, unsigned &MaxAlign) {
972   if (MaxAlign == 16)
973     return;
974   if (const VectorType *VTy = dyn_cast<VectorType>(Ty)) {
975     if (VTy->getBitWidth() == 128)
976       MaxAlign = 16;
977   } else if (const ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
978     unsigned EltAlign = 0;
979     getMaxByValAlign(ATy->getElementType(), EltAlign);
980     if (EltAlign > MaxAlign)
981       MaxAlign = EltAlign;
982   } else if (const StructType *STy = dyn_cast<StructType>(Ty)) {
983     for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
984       unsigned EltAlign = 0;
985       getMaxByValAlign(STy->getElementType(i), EltAlign);
986       if (EltAlign > MaxAlign)
987         MaxAlign = EltAlign;
988       if (MaxAlign == 16)
989         break;
990     }
991   }
992   return;
993 }
994
995 /// getByValTypeAlignment - Return the desired alignment for ByVal aggregate
996 /// function arguments in the caller parameter area. For X86, aggregates
997 /// that contain SSE vectors are placed at 16-byte boundaries while the rest
998 /// are at 4-byte boundaries.
999 unsigned X86TargetLowering::getByValTypeAlignment(const Type *Ty) const {
1000   if (Subtarget->is64Bit()) {
1001     // Max of 8 and alignment of type.
1002     unsigned TyAlign = TD->getABITypeAlignment(Ty);
1003     if (TyAlign > 8)
1004       return TyAlign;
1005     return 8;
1006   }
1007
1008   unsigned Align = 4;
1009   if (Subtarget->hasSSE1())
1010     getMaxByValAlign(Ty, Align);
1011   return Align;
1012 }
1013
1014 /// getOptimalMemOpType - Returns the target specific optimal type for load
1015 /// and store operations as a result of memset, memcpy, and memmove
1016 /// lowering. It returns MVT::iAny if SelectionDAG should be responsible for
1017 /// determining it.
1018 MVT
1019 X86TargetLowering::getOptimalMemOpType(uint64_t Size, unsigned Align,
1020                                        bool isSrcConst, bool isSrcStr,
1021                                        SelectionDAG &DAG) const {
1022   // FIXME: This turns off use of xmm stores for memset/memcpy on targets like
1023   // linux.  This is because the stack realignment code can't handle certain
1024   // cases like PR2962.  This should be removed when PR2962 is fixed.
1025   const Function *F = DAG.getMachineFunction().getFunction();
1026   bool NoImplicitFloatOps = F->hasFnAttr(Attribute::NoImplicitFloat);
1027   if (!NoImplicitFloatOps && Subtarget->getStackAlignment() >= 16) {
1028     if ((isSrcConst || isSrcStr) && Subtarget->hasSSE2() && Size >= 16)
1029       return MVT::v4i32;
1030     if ((isSrcConst || isSrcStr) && Subtarget->hasSSE1() && Size >= 16)
1031       return MVT::v4f32;
1032   }
1033   if (Subtarget->is64Bit() && Size >= 8)
1034     return MVT::i64;
1035   return MVT::i32;
1036 }
1037
1038 /// getPICJumpTableRelocaBase - Returns relocation base for the given PIC
1039 /// jumptable.
1040 SDValue X86TargetLowering::getPICJumpTableRelocBase(SDValue Table,
1041                                                       SelectionDAG &DAG) const {
1042   if (usesGlobalOffsetTable())
1043     return DAG.getGLOBAL_OFFSET_TABLE(getPointerTy());
1044   if (!Subtarget->is64Bit())
1045     // This doesn't have DebugLoc associated with it, but is not really the
1046     // same as a Register.
1047     return DAG.getNode(X86ISD::GlobalBaseReg, DebugLoc::getUnknownLoc(),
1048                        getPointerTy());
1049   return Table;
1050 }
1051
1052 /// getFunctionAlignment - Return the Log2 alignment of this function.
1053 unsigned X86TargetLowering::getFunctionAlignment(const Function *F) const {
1054   return F->hasFnAttr(Attribute::OptimizeForSize) ? 1 : 4;
1055 }
1056
1057 //===----------------------------------------------------------------------===//
1058 //               Return Value Calling Convention Implementation
1059 //===----------------------------------------------------------------------===//
1060
1061 #include "X86GenCallingConv.inc"
1062
1063 /// LowerRET - Lower an ISD::RET node.
1064 SDValue X86TargetLowering::LowerRET(SDValue Op, SelectionDAG &DAG) {
1065   DebugLoc dl = Op.getDebugLoc();
1066   assert((Op.getNumOperands() & 1) == 1 && "ISD::RET should have odd # args");
1067
1068   SmallVector<CCValAssign, 16> RVLocs;
1069   unsigned CC = DAG.getMachineFunction().getFunction()->getCallingConv();
1070   bool isVarArg = DAG.getMachineFunction().getFunction()->isVarArg();
1071   CCState CCInfo(CC, isVarArg, getTargetMachine(), RVLocs, *DAG.getContext());
1072   CCInfo.AnalyzeReturn(Op.getNode(), RetCC_X86);
1073
1074   // If this is the first return lowered for this function, add the regs to the
1075   // liveout set for the function.
1076   if (DAG.getMachineFunction().getRegInfo().liveout_empty()) {
1077     for (unsigned i = 0; i != RVLocs.size(); ++i)
1078       if (RVLocs[i].isRegLoc())
1079         DAG.getMachineFunction().getRegInfo().addLiveOut(RVLocs[i].getLocReg());
1080   }
1081   SDValue Chain = Op.getOperand(0);
1082
1083   // Handle tail call return.
1084   Chain = GetPossiblePreceedingTailCall(Chain, X86ISD::TAILCALL);
1085   if (Chain.getOpcode() == X86ISD::TAILCALL) {
1086     SDValue TailCall = Chain;
1087     SDValue TargetAddress = TailCall.getOperand(1);
1088     SDValue StackAdjustment = TailCall.getOperand(2);
1089     assert(((TargetAddress.getOpcode() == ISD::Register &&
1090                (cast<RegisterSDNode>(TargetAddress)->getReg() == X86::EAX ||
1091                 cast<RegisterSDNode>(TargetAddress)->getReg() == X86::R11)) ||
1092               TargetAddress.getOpcode() == ISD::TargetExternalSymbol ||
1093               TargetAddress.getOpcode() == ISD::TargetGlobalAddress) &&
1094              "Expecting an global address, external symbol, or register");
1095     assert(StackAdjustment.getOpcode() == ISD::Constant &&
1096            "Expecting a const value");
1097
1098     SmallVector<SDValue,8> Operands;
1099     Operands.push_back(Chain.getOperand(0));
1100     Operands.push_back(TargetAddress);
1101     Operands.push_back(StackAdjustment);
1102     // Copy registers used by the call. Last operand is a flag so it is not
1103     // copied.
1104     for (unsigned i=3; i < TailCall.getNumOperands()-1; i++) {
1105       Operands.push_back(Chain.getOperand(i));
1106     }
1107     return DAG.getNode(X86ISD::TC_RETURN, dl, MVT::Other, &Operands[0],
1108                        Operands.size());
1109   }
1110
1111   // Regular return.
1112   SDValue Flag;
1113
1114   SmallVector<SDValue, 6> RetOps;
1115   RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
1116   // Operand #1 = Bytes To Pop
1117   RetOps.push_back(DAG.getConstant(getBytesToPopOnReturn(), MVT::i16));
1118
1119   // Copy the result values into the output registers.
1120   for (unsigned i = 0; i != RVLocs.size(); ++i) {
1121     CCValAssign &VA = RVLocs[i];
1122     assert(VA.isRegLoc() && "Can only return in registers!");
1123     SDValue ValToCopy = Op.getOperand(i*2+1);
1124
1125     // Returns in ST0/ST1 are handled specially: these are pushed as operands to
1126     // the RET instruction and handled by the FP Stackifier.
1127     if (VA.getLocReg() == X86::ST0 ||
1128         VA.getLocReg() == X86::ST1) {
1129       // If this is a copy from an xmm register to ST(0), use an FPExtend to
1130       // change the value to the FP stack register class.
1131       if (isScalarFPTypeInSSEReg(VA.getValVT()))
1132         ValToCopy = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f80, ValToCopy);
1133       RetOps.push_back(ValToCopy);
1134       // Don't emit a copytoreg.
1135       continue;
1136     }
1137
1138     // 64-bit vector (MMX) values are returned in XMM0 / XMM1 except for v1i64
1139     // which is returned in RAX / RDX.
1140     if (Subtarget->is64Bit()) {
1141       MVT ValVT = ValToCopy.getValueType();
1142       if (ValVT.isVector() && ValVT.getSizeInBits() == 64) {
1143         ValToCopy = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::i64, ValToCopy);
1144         if (VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1)
1145           ValToCopy = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64, ValToCopy);
1146       }
1147     }
1148
1149     Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), ValToCopy, Flag);
1150     Flag = Chain.getValue(1);
1151   }
1152
1153   // The x86-64 ABI for returning structs by value requires that we copy
1154   // the sret argument into %rax for the return. We saved the argument into
1155   // a virtual register in the entry block, so now we copy the value out
1156   // and into %rax.
1157   if (Subtarget->is64Bit() &&
1158       DAG.getMachineFunction().getFunction()->hasStructRetAttr()) {
1159     MachineFunction &MF = DAG.getMachineFunction();
1160     X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1161     unsigned Reg = FuncInfo->getSRetReturnReg();
1162     if (!Reg) {
1163       Reg = MF.getRegInfo().createVirtualRegister(getRegClassFor(MVT::i64));
1164       FuncInfo->setSRetReturnReg(Reg);
1165     }
1166     SDValue Val = DAG.getCopyFromReg(Chain, dl, Reg, getPointerTy());
1167
1168     Chain = DAG.getCopyToReg(Chain, dl, X86::RAX, Val, Flag);
1169     Flag = Chain.getValue(1);
1170   }
1171
1172   RetOps[0] = Chain;  // Update chain.
1173
1174   // Add the flag if we have it.
1175   if (Flag.getNode())
1176     RetOps.push_back(Flag);
1177
1178   return DAG.getNode(X86ISD::RET_FLAG, dl,
1179                      MVT::Other, &RetOps[0], RetOps.size());
1180 }
1181
1182
1183 /// LowerCallResult - Lower the result values of an ISD::CALL into the
1184 /// appropriate copies out of appropriate physical registers.  This assumes that
1185 /// Chain/InFlag are the input chain/flag to use, and that TheCall is the call
1186 /// being lowered.  The returns a SDNode with the same number of values as the
1187 /// ISD::CALL.
1188 SDNode *X86TargetLowering::
1189 LowerCallResult(SDValue Chain, SDValue InFlag, CallSDNode *TheCall,
1190                 unsigned CallingConv, SelectionDAG &DAG) {
1191
1192   DebugLoc dl = TheCall->getDebugLoc();
1193   // Assign locations to each value returned by this call.
1194   SmallVector<CCValAssign, 16> RVLocs;
1195   bool isVarArg = TheCall->isVarArg();
1196   bool Is64Bit = Subtarget->is64Bit();
1197   CCState CCInfo(CallingConv, isVarArg, getTargetMachine(),
1198                  RVLocs, *DAG.getContext());
1199   CCInfo.AnalyzeCallResult(TheCall, RetCC_X86);
1200
1201   SmallVector<SDValue, 8> ResultVals;
1202
1203   // Copy all of the result registers out of their specified physreg.
1204   for (unsigned i = 0; i != RVLocs.size(); ++i) {
1205     CCValAssign &VA = RVLocs[i];
1206     MVT CopyVT = VA.getValVT();
1207
1208     // If this is x86-64, and we disabled SSE, we can't return FP values
1209     if ((CopyVT == MVT::f32 || CopyVT == MVT::f64) &&
1210         ((Is64Bit || TheCall->isInreg()) && !Subtarget->hasSSE1())) {
1211       llvm_report_error("SSE register return with SSE disabled");
1212     }
1213
1214     // If this is a call to a function that returns an fp value on the floating
1215     // point stack, but where we prefer to use the value in xmm registers, copy
1216     // it out as F80 and use a truncate to move it from fp stack reg to xmm reg.
1217     if ((VA.getLocReg() == X86::ST0 ||
1218          VA.getLocReg() == X86::ST1) &&
1219         isScalarFPTypeInSSEReg(VA.getValVT())) {
1220       CopyVT = MVT::f80;
1221     }
1222
1223     SDValue Val;
1224     if (Is64Bit && CopyVT.isVector() && CopyVT.getSizeInBits() == 64) {
1225       // For x86-64, MMX values are returned in XMM0 / XMM1 except for v1i64.
1226       if (VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) {
1227         Chain = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(),
1228                                    MVT::v2i64, InFlag).getValue(1);
1229         Val = Chain.getValue(0);
1230         Val = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i64,
1231                           Val, DAG.getConstant(0, MVT::i64));        
1232       } else {
1233         Chain = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(),
1234                                    MVT::i64, InFlag).getValue(1);
1235         Val = Chain.getValue(0);
1236       }
1237       Val = DAG.getNode(ISD::BIT_CONVERT, dl, CopyVT, Val);
1238     } else {
1239       Chain = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(),
1240                                  CopyVT, InFlag).getValue(1);
1241       Val = Chain.getValue(0);
1242     }
1243     InFlag = Chain.getValue(2);
1244
1245     if (CopyVT != VA.getValVT()) {
1246       // Round the F80 the right size, which also moves to the appropriate xmm
1247       // register.
1248       Val = DAG.getNode(ISD::FP_ROUND, dl, VA.getValVT(), Val,
1249                         // This truncation won't change the value.
1250                         DAG.getIntPtrConstant(1));
1251     }
1252
1253     ResultVals.push_back(Val);
1254   }
1255
1256   // Merge everything together with a MERGE_VALUES node.
1257   ResultVals.push_back(Chain);
1258   return DAG.getNode(ISD::MERGE_VALUES, dl, TheCall->getVTList(),
1259                      &ResultVals[0], ResultVals.size()).getNode();
1260 }
1261
1262
1263 //===----------------------------------------------------------------------===//
1264 //                C & StdCall & Fast Calling Convention implementation
1265 //===----------------------------------------------------------------------===//
1266 //  StdCall calling convention seems to be standard for many Windows' API
1267 //  routines and around. It differs from C calling convention just a little:
1268 //  callee should clean up the stack, not caller. Symbols should be also
1269 //  decorated in some fancy way :) It doesn't support any vector arguments.
1270 //  For info on fast calling convention see Fast Calling Convention (tail call)
1271 //  implementation LowerX86_32FastCCCallTo.
1272
1273 /// CallIsStructReturn - Determines whether a CALL node uses struct return
1274 /// semantics.
1275 static bool CallIsStructReturn(CallSDNode *TheCall) {
1276   unsigned NumOps = TheCall->getNumArgs();
1277   if (!NumOps)
1278     return false;
1279
1280   return TheCall->getArgFlags(0).isSRet();
1281 }
1282
1283 /// ArgsAreStructReturn - Determines whether a FORMAL_ARGUMENTS node uses struct
1284 /// return semantics.
1285 static bool ArgsAreStructReturn(SDValue Op) {
1286   unsigned NumArgs = Op.getNode()->getNumValues() - 1;
1287   if (!NumArgs)
1288     return false;
1289
1290   return cast<ARG_FLAGSSDNode>(Op.getOperand(3))->getArgFlags().isSRet();
1291 }
1292
1293 /// IsCalleePop - Determines whether a CALL or FORMAL_ARGUMENTS node requires
1294 /// the callee to pop its own arguments. Callee pop is necessary to support tail
1295 /// calls.
1296 bool X86TargetLowering::IsCalleePop(bool IsVarArg, unsigned CallingConv) {
1297   if (IsVarArg)
1298     return false;
1299
1300   switch (CallingConv) {
1301   default:
1302     return false;
1303   case CallingConv::X86_StdCall:
1304     return !Subtarget->is64Bit();
1305   case CallingConv::X86_FastCall:
1306     return !Subtarget->is64Bit();
1307   case CallingConv::Fast:
1308     return PerformTailCallOpt;
1309   }
1310 }
1311
1312 /// CCAssignFnForNode - Selects the correct CCAssignFn for a the
1313 /// given CallingConvention value.
1314 CCAssignFn *X86TargetLowering::CCAssignFnForNode(unsigned CC) const {
1315   if (Subtarget->is64Bit()) {
1316     if (Subtarget->isTargetWin64())
1317       return CC_X86_Win64_C;
1318     else
1319       return CC_X86_64_C;
1320   }
1321
1322   if (CC == CallingConv::X86_FastCall)
1323     return CC_X86_32_FastCall;
1324   else if (CC == CallingConv::Fast)
1325     return CC_X86_32_FastCC;
1326   else
1327     return CC_X86_32_C;
1328 }
1329
1330 /// NameDecorationForFORMAL_ARGUMENTS - Selects the appropriate decoration to
1331 /// apply to a MachineFunction containing a given FORMAL_ARGUMENTS node.
1332 NameDecorationStyle
1333 X86TargetLowering::NameDecorationForFORMAL_ARGUMENTS(SDValue Op) {
1334   unsigned CC = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
1335   if (CC == CallingConv::X86_FastCall)
1336     return FastCall;
1337   else if (CC == CallingConv::X86_StdCall)
1338     return StdCall;
1339   return None;
1340 }
1341
1342
1343 /// CreateCopyOfByValArgument - Make a copy of an aggregate at address specified
1344 /// by "Src" to address "Dst" with size and alignment information specified by
1345 /// the specific parameter attribute. The copy will be passed as a byval
1346 /// function parameter.
1347 static SDValue
1348 CreateCopyOfByValArgument(SDValue Src, SDValue Dst, SDValue Chain,
1349                           ISD::ArgFlagsTy Flags, SelectionDAG &DAG,
1350                           DebugLoc dl) {
1351   SDValue SizeNode     = DAG.getConstant(Flags.getByValSize(), MVT::i32);
1352   return DAG.getMemcpy(Chain, dl, Dst, Src, SizeNode, Flags.getByValAlign(),
1353                        /*AlwaysInline=*/true, NULL, 0, NULL, 0);
1354 }
1355
1356 SDValue X86TargetLowering::LowerMemArgument(SDValue Op, SelectionDAG &DAG,
1357                                               const CCValAssign &VA,
1358                                               MachineFrameInfo *MFI,
1359                                               unsigned CC,
1360                                               SDValue Root, unsigned i) {
1361   // Create the nodes corresponding to a load from this parameter slot.
1362   ISD::ArgFlagsTy Flags =
1363     cast<ARG_FLAGSSDNode>(Op.getOperand(3 + i))->getArgFlags();
1364   bool AlwaysUseMutable = (CC==CallingConv::Fast) && PerformTailCallOpt;
1365   bool isImmutable = !AlwaysUseMutable && !Flags.isByVal();
1366
1367   // FIXME: For now, all byval parameter objects are marked mutable. This can be
1368   // changed with more analysis.
1369   // In case of tail call optimization mark all arguments mutable. Since they
1370   // could be overwritten by lowering of arguments in case of a tail call.
1371   int FI = MFI->CreateFixedObject(VA.getValVT().getSizeInBits()/8,
1372                                   VA.getLocMemOffset(), isImmutable);
1373   SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
1374   if (Flags.isByVal())
1375     return FIN;
1376   return DAG.getLoad(VA.getValVT(), Op.getDebugLoc(), Root, FIN,
1377                      PseudoSourceValue::getFixedStack(FI), 0);
1378 }
1379
1380 SDValue
1381 X86TargetLowering::LowerFORMAL_ARGUMENTS(SDValue Op, SelectionDAG &DAG) {
1382   MachineFunction &MF = DAG.getMachineFunction();
1383   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1384   DebugLoc dl = Op.getDebugLoc();
1385
1386   const Function* Fn = MF.getFunction();
1387   if (Fn->hasExternalLinkage() &&
1388       Subtarget->isTargetCygMing() &&
1389       Fn->getName() == "main")
1390     FuncInfo->setForceFramePointer(true);
1391
1392   // Decorate the function name.
1393   FuncInfo->setDecorationStyle(NameDecorationForFORMAL_ARGUMENTS(Op));
1394
1395   MachineFrameInfo *MFI = MF.getFrameInfo();
1396   SDValue Root = Op.getOperand(0);
1397   bool isVarArg = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue() != 0;
1398   unsigned CC = MF.getFunction()->getCallingConv();
1399   bool Is64Bit = Subtarget->is64Bit();
1400   bool IsWin64 = Subtarget->isTargetWin64();
1401
1402   assert(!(isVarArg && CC == CallingConv::Fast) &&
1403          "Var args not supported with calling convention fastcc");
1404
1405   // Assign locations to all of the incoming arguments.
1406   SmallVector<CCValAssign, 16> ArgLocs;
1407   CCState CCInfo(CC, isVarArg, getTargetMachine(), ArgLocs, *DAG.getContext());
1408   CCInfo.AnalyzeFormalArguments(Op.getNode(), CCAssignFnForNode(CC));
1409
1410   SmallVector<SDValue, 8> ArgValues;
1411   unsigned LastVal = ~0U;
1412   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
1413     CCValAssign &VA = ArgLocs[i];
1414     // TODO: If an arg is passed in two places (e.g. reg and stack), skip later
1415     // places.
1416     assert(VA.getValNo() != LastVal &&
1417            "Don't support value assigned to multiple locs yet");
1418     LastVal = VA.getValNo();
1419
1420     if (VA.isRegLoc()) {
1421       MVT RegVT = VA.getLocVT();
1422       TargetRegisterClass *RC = NULL;
1423       if (RegVT == MVT::i32)
1424         RC = X86::GR32RegisterClass;
1425       else if (Is64Bit && RegVT == MVT::i64)
1426         RC = X86::GR64RegisterClass;
1427       else if (RegVT == MVT::f32)
1428         RC = X86::FR32RegisterClass;
1429       else if (RegVT == MVT::f64)
1430         RC = X86::FR64RegisterClass;
1431       else if (RegVT.isVector() && RegVT.getSizeInBits() == 128)
1432         RC = X86::VR128RegisterClass;
1433       else if (RegVT.isVector()) {
1434         assert(RegVT.getSizeInBits() == 64);
1435         if (!Is64Bit)
1436           RC = X86::VR64RegisterClass;     // MMX values are passed in MMXs.
1437         else {
1438           // Darwin calling convention passes MMX values in either GPRs or
1439           // XMMs in x86-64. Other targets pass them in memory.
1440           if (RegVT != MVT::v1i64 && Subtarget->hasSSE2()) {
1441             RC = X86::VR128RegisterClass;  // MMX values are passed in XMMs.
1442             RegVT = MVT::v2i64;
1443           } else {
1444             RC = X86::GR64RegisterClass;   // v1i64 values are passed in GPRs.
1445             RegVT = MVT::i64;
1446           }
1447         }
1448       } else {
1449         llvm_unreachable("Unknown argument type!");
1450       }
1451
1452       unsigned Reg = DAG.getMachineFunction().addLiveIn(VA.getLocReg(), RC);
1453       SDValue ArgValue = DAG.getCopyFromReg(Root, dl, Reg, RegVT);
1454
1455       // If this is an 8 or 16-bit value, it is really passed promoted to 32
1456       // bits.  Insert an assert[sz]ext to capture this, then truncate to the
1457       // right size.
1458       if (VA.getLocInfo() == CCValAssign::SExt)
1459         ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
1460                                DAG.getValueType(VA.getValVT()));
1461       else if (VA.getLocInfo() == CCValAssign::ZExt)
1462         ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
1463                                DAG.getValueType(VA.getValVT()));
1464
1465       if (VA.getLocInfo() != CCValAssign::Full)
1466         ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
1467
1468       // Handle MMX values passed in GPRs.
1469       if (Is64Bit && RegVT != VA.getLocVT()) {
1470         if (RegVT.getSizeInBits() == 64 && RC == X86::GR64RegisterClass)
1471           ArgValue = DAG.getNode(ISD::BIT_CONVERT, dl, VA.getLocVT(), ArgValue);
1472         else if (RC == X86::VR128RegisterClass) {
1473           ArgValue = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i64,
1474                                  ArgValue, DAG.getConstant(0, MVT::i64));
1475           ArgValue = DAG.getNode(ISD::BIT_CONVERT, dl, VA.getLocVT(), ArgValue);
1476         }
1477       }
1478
1479       ArgValues.push_back(ArgValue);
1480     } else {
1481       assert(VA.isMemLoc());
1482       ArgValues.push_back(LowerMemArgument(Op, DAG, VA, MFI, CC, Root, i));
1483     }
1484   }
1485
1486   // The x86-64 ABI for returning structs by value requires that we copy
1487   // the sret argument into %rax for the return. Save the argument into
1488   // a virtual register so that we can access it from the return points.
1489   if (Is64Bit && DAG.getMachineFunction().getFunction()->hasStructRetAttr()) {
1490     MachineFunction &MF = DAG.getMachineFunction();
1491     X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1492     unsigned Reg = FuncInfo->getSRetReturnReg();
1493     if (!Reg) {
1494       Reg = MF.getRegInfo().createVirtualRegister(getRegClassFor(MVT::i64));
1495       FuncInfo->setSRetReturnReg(Reg);
1496     }
1497     SDValue Copy = DAG.getCopyToReg(DAG.getEntryNode(), dl, Reg, ArgValues[0]);
1498     Root = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Copy, Root);
1499   }
1500
1501   unsigned StackSize = CCInfo.getNextStackOffset();
1502   // align stack specially for tail calls
1503   if (PerformTailCallOpt && CC == CallingConv::Fast)
1504     StackSize = GetAlignedArgumentStackSize(StackSize, DAG);
1505
1506   // If the function takes variable number of arguments, make a frame index for
1507   // the start of the first vararg value... for expansion of llvm.va_start.
1508   if (isVarArg) {
1509     if (Is64Bit || CC != CallingConv::X86_FastCall) {
1510       VarArgsFrameIndex = MFI->CreateFixedObject(1, StackSize);
1511     }
1512     if (Is64Bit) {
1513       unsigned TotalNumIntRegs = 0, TotalNumXMMRegs = 0;
1514
1515       // FIXME: We should really autogenerate these arrays
1516       static const unsigned GPR64ArgRegsWin64[] = {
1517         X86::RCX, X86::RDX, X86::R8,  X86::R9
1518       };
1519       static const unsigned XMMArgRegsWin64[] = {
1520         X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3
1521       };
1522       static const unsigned GPR64ArgRegs64Bit[] = {
1523         X86::RDI, X86::RSI, X86::RDX, X86::RCX, X86::R8, X86::R9
1524       };
1525       static const unsigned XMMArgRegs64Bit[] = {
1526         X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
1527         X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
1528       };
1529       const unsigned *GPR64ArgRegs, *XMMArgRegs;
1530
1531       if (IsWin64) {
1532         TotalNumIntRegs = 4; TotalNumXMMRegs = 4;
1533         GPR64ArgRegs = GPR64ArgRegsWin64;
1534         XMMArgRegs = XMMArgRegsWin64;
1535       } else {
1536         TotalNumIntRegs = 6; TotalNumXMMRegs = 8;
1537         GPR64ArgRegs = GPR64ArgRegs64Bit;
1538         XMMArgRegs = XMMArgRegs64Bit;
1539       }
1540       unsigned NumIntRegs = CCInfo.getFirstUnallocated(GPR64ArgRegs,
1541                                                        TotalNumIntRegs);
1542       unsigned NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs,
1543                                                        TotalNumXMMRegs);
1544
1545       bool NoImplicitFloatOps = Fn->hasFnAttr(Attribute::NoImplicitFloat);
1546       assert(!(NumXMMRegs && !Subtarget->hasSSE1()) &&
1547              "SSE register cannot be used when SSE is disabled!");
1548       assert(!(NumXMMRegs && UseSoftFloat && NoImplicitFloatOps) &&
1549              "SSE register cannot be used when SSE is disabled!");
1550       if (UseSoftFloat || NoImplicitFloatOps || !Subtarget->hasSSE1())
1551         // Kernel mode asks for SSE to be disabled, so don't push them
1552         // on the stack.
1553         TotalNumXMMRegs = 0;
1554
1555       // For X86-64, if there are vararg parameters that are passed via
1556       // registers, then we must store them to their spots on the stack so they
1557       // may be loaded by deferencing the result of va_next.
1558       VarArgsGPOffset = NumIntRegs * 8;
1559       VarArgsFPOffset = TotalNumIntRegs * 8 + NumXMMRegs * 16;
1560       RegSaveFrameIndex = MFI->CreateStackObject(TotalNumIntRegs * 8 +
1561                                                  TotalNumXMMRegs * 16, 16);
1562
1563       // Store the integer parameter registers.
1564       SmallVector<SDValue, 8> MemOps;
1565       SDValue RSFIN = DAG.getFrameIndex(RegSaveFrameIndex, getPointerTy());
1566       SDValue FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(), RSFIN,
1567                                   DAG.getIntPtrConstant(VarArgsGPOffset));
1568       for (; NumIntRegs != TotalNumIntRegs; ++NumIntRegs) {
1569         unsigned VReg = MF.addLiveIn(GPR64ArgRegs[NumIntRegs],
1570                                      X86::GR64RegisterClass);
1571         SDValue Val = DAG.getCopyFromReg(Root, dl, VReg, MVT::i64);
1572         SDValue Store =
1573           DAG.getStore(Val.getValue(1), dl, Val, FIN,
1574                        PseudoSourceValue::getFixedStack(RegSaveFrameIndex), 0);
1575         MemOps.push_back(Store);
1576         FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(), FIN,
1577                           DAG.getIntPtrConstant(8));
1578       }
1579
1580       // Now store the XMM (fp + vector) parameter registers.
1581       FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(), RSFIN,
1582                         DAG.getIntPtrConstant(VarArgsFPOffset));
1583       for (; NumXMMRegs != TotalNumXMMRegs; ++NumXMMRegs) {
1584         unsigned VReg = MF.addLiveIn(XMMArgRegs[NumXMMRegs],
1585                                      X86::VR128RegisterClass);
1586         SDValue Val = DAG.getCopyFromReg(Root, dl, VReg, MVT::v4f32);
1587         SDValue Store =
1588           DAG.getStore(Val.getValue(1), dl, Val, FIN,
1589                        PseudoSourceValue::getFixedStack(RegSaveFrameIndex), 0);
1590         MemOps.push_back(Store);
1591         FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(), FIN,
1592                           DAG.getIntPtrConstant(16));
1593       }
1594       if (!MemOps.empty())
1595           Root = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
1596                              &MemOps[0], MemOps.size());
1597     }
1598   }
1599
1600   ArgValues.push_back(Root);
1601
1602   // Some CCs need callee pop.
1603   if (IsCalleePop(isVarArg, CC)) {
1604     BytesToPopOnReturn  = StackSize; // Callee pops everything.
1605     BytesCallerReserves = 0;
1606   } else {
1607     BytesToPopOnReturn  = 0; // Callee pops nothing.
1608     // If this is an sret function, the return should pop the hidden pointer.
1609     if (!Is64Bit && CC != CallingConv::Fast && ArgsAreStructReturn(Op))
1610       BytesToPopOnReturn = 4;
1611     BytesCallerReserves = StackSize;
1612   }
1613
1614   if (!Is64Bit) {
1615     RegSaveFrameIndex = 0xAAAAAAA;   // RegSaveFrameIndex is X86-64 only.
1616     if (CC == CallingConv::X86_FastCall)
1617       VarArgsFrameIndex = 0xAAAAAAA;   // fastcc functions can't have varargs.
1618   }
1619
1620   FuncInfo->setBytesToPopOnReturn(BytesToPopOnReturn);
1621
1622   // Return the new list of results.
1623   return DAG.getNode(ISD::MERGE_VALUES, dl, Op.getNode()->getVTList(),
1624                      &ArgValues[0], ArgValues.size()).getValue(Op.getResNo());
1625 }
1626
1627 SDValue
1628 X86TargetLowering::LowerMemOpCallTo(CallSDNode *TheCall, SelectionDAG &DAG,
1629                                     const SDValue &StackPtr,
1630                                     const CCValAssign &VA,
1631                                     SDValue Chain,
1632                                     SDValue Arg, ISD::ArgFlagsTy Flags) {
1633   DebugLoc dl = TheCall->getDebugLoc();
1634   unsigned LocMemOffset = VA.getLocMemOffset();
1635   SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset);
1636   PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, PtrOff);
1637   if (Flags.isByVal()) {
1638     return CreateCopyOfByValArgument(Arg, PtrOff, Chain, Flags, DAG, dl);
1639   }
1640   return DAG.getStore(Chain, dl, Arg, PtrOff,
1641                       PseudoSourceValue::getStack(), LocMemOffset);
1642 }
1643
1644 /// EmitTailCallLoadRetAddr - Emit a load of return address if tail call
1645 /// optimization is performed and it is required.
1646 SDValue
1647 X86TargetLowering::EmitTailCallLoadRetAddr(SelectionDAG &DAG,
1648                                            SDValue &OutRetAddr,
1649                                            SDValue Chain,
1650                                            bool IsTailCall,
1651                                            bool Is64Bit,
1652                                            int FPDiff,
1653                                            DebugLoc dl) {
1654   if (!IsTailCall || FPDiff==0) return Chain;
1655
1656   // Adjust the Return address stack slot.
1657   MVT VT = getPointerTy();
1658   OutRetAddr = getReturnAddressFrameIndex(DAG);
1659
1660   // Load the "old" Return address.
1661   OutRetAddr = DAG.getLoad(VT, dl, Chain, OutRetAddr, NULL, 0);
1662   return SDValue(OutRetAddr.getNode(), 1);
1663 }
1664
1665 /// EmitTailCallStoreRetAddr - Emit a store of the return adress if tail call
1666 /// optimization is performed and it is required (FPDiff!=0).
1667 static SDValue
1668 EmitTailCallStoreRetAddr(SelectionDAG & DAG, MachineFunction &MF,
1669                          SDValue Chain, SDValue RetAddrFrIdx,
1670                          bool Is64Bit, int FPDiff, DebugLoc dl) {
1671   // Store the return address to the appropriate stack slot.
1672   if (!FPDiff) return Chain;
1673   // Calculate the new stack slot for the return address.
1674   int SlotSize = Is64Bit ? 8 : 4;
1675   int NewReturnAddrFI =
1676     MF.getFrameInfo()->CreateFixedObject(SlotSize, FPDiff-SlotSize);
1677   MVT VT = Is64Bit ? MVT::i64 : MVT::i32;
1678   SDValue NewRetAddrFrIdx = DAG.getFrameIndex(NewReturnAddrFI, VT);
1679   Chain = DAG.getStore(Chain, dl, RetAddrFrIdx, NewRetAddrFrIdx,
1680                        PseudoSourceValue::getFixedStack(NewReturnAddrFI), 0);
1681   return Chain;
1682 }
1683
1684 SDValue X86TargetLowering::LowerCALL(SDValue Op, SelectionDAG &DAG) {
1685   MachineFunction &MF = DAG.getMachineFunction();
1686   CallSDNode *TheCall = cast<CallSDNode>(Op.getNode());
1687   SDValue Chain       = TheCall->getChain();
1688   unsigned CC         = TheCall->getCallingConv();
1689   bool isVarArg       = TheCall->isVarArg();
1690   bool IsTailCall     = TheCall->isTailCall() &&
1691                         CC == CallingConv::Fast && PerformTailCallOpt;
1692   SDValue Callee      = TheCall->getCallee();
1693   bool Is64Bit        = Subtarget->is64Bit();
1694   bool IsStructRet    = CallIsStructReturn(TheCall);
1695   DebugLoc dl         = TheCall->getDebugLoc();
1696
1697   assert(!(isVarArg && CC == CallingConv::Fast) &&
1698          "Var args not supported with calling convention fastcc");
1699
1700   // Analyze operands of the call, assigning locations to each operand.
1701   SmallVector<CCValAssign, 16> ArgLocs;
1702   CCState CCInfo(CC, isVarArg, getTargetMachine(), ArgLocs, *DAG.getContext());
1703   CCInfo.AnalyzeCallOperands(TheCall, CCAssignFnForNode(CC));
1704
1705   // Get a count of how many bytes are to be pushed on the stack.
1706   unsigned NumBytes = CCInfo.getNextStackOffset();
1707   if (PerformTailCallOpt && CC == CallingConv::Fast)
1708     NumBytes = GetAlignedArgumentStackSize(NumBytes, DAG);
1709
1710   int FPDiff = 0;
1711   if (IsTailCall) {
1712     // Lower arguments at fp - stackoffset + fpdiff.
1713     unsigned NumBytesCallerPushed =
1714       MF.getInfo<X86MachineFunctionInfo>()->getBytesToPopOnReturn();
1715     FPDiff = NumBytesCallerPushed - NumBytes;
1716
1717     // Set the delta of movement of the returnaddr stackslot.
1718     // But only set if delta is greater than previous delta.
1719     if (FPDiff < (MF.getInfo<X86MachineFunctionInfo>()->getTCReturnAddrDelta()))
1720       MF.getInfo<X86MachineFunctionInfo>()->setTCReturnAddrDelta(FPDiff);
1721   }
1722
1723   Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes, true));
1724
1725   SDValue RetAddrFrIdx;
1726   // Load return adress for tail calls.
1727   Chain = EmitTailCallLoadRetAddr(DAG, RetAddrFrIdx, Chain, IsTailCall, Is64Bit,
1728                                   FPDiff, dl);
1729
1730   SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
1731   SmallVector<SDValue, 8> MemOpChains;
1732   SDValue StackPtr;
1733
1734   // Walk the register/memloc assignments, inserting copies/loads.  In the case
1735   // of tail call optimization arguments are handle later.
1736   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
1737     CCValAssign &VA = ArgLocs[i];
1738     SDValue Arg = TheCall->getArg(i);
1739     ISD::ArgFlagsTy Flags = TheCall->getArgFlags(i);
1740     bool isByVal = Flags.isByVal();
1741
1742     // Promote the value if needed.
1743     switch (VA.getLocInfo()) {
1744     default: llvm_unreachable("Unknown loc info!");
1745     case CCValAssign::Full: break;
1746     case CCValAssign::SExt:
1747       Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), Arg);
1748       break;
1749     case CCValAssign::ZExt:
1750       Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), Arg);
1751       break;
1752     case CCValAssign::AExt:
1753       Arg = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), Arg);
1754       break;
1755     }
1756
1757     if (VA.isRegLoc()) {
1758       if (Is64Bit) {
1759         MVT RegVT = VA.getLocVT();
1760         if (RegVT.isVector() && RegVT.getSizeInBits() == 64)
1761           switch (VA.getLocReg()) {
1762           default:
1763             break;
1764           case X86::RDI: case X86::RSI: case X86::RDX: case X86::RCX:
1765           case X86::R8: {
1766             // Special case: passing MMX values in GPR registers.
1767             Arg = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::i64, Arg);
1768             break;
1769           }
1770           case X86::XMM0: case X86::XMM1: case X86::XMM2: case X86::XMM3:
1771           case X86::XMM4: case X86::XMM5: case X86::XMM6: case X86::XMM7: {
1772             // Special case: passing MMX values in XMM registers.
1773             Arg = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::i64, Arg);
1774             Arg = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64, Arg);
1775             Arg = getMOVL(DAG, dl, MVT::v2i64, DAG.getUNDEF(MVT::v2i64), Arg);
1776             break;
1777           }
1778           }
1779       }
1780       RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
1781     } else {
1782       if (!IsTailCall || (IsTailCall && isByVal)) {
1783         assert(VA.isMemLoc());
1784         if (StackPtr.getNode() == 0)
1785           StackPtr = DAG.getCopyFromReg(Chain, dl, X86StackPtr, getPointerTy());
1786
1787         MemOpChains.push_back(LowerMemOpCallTo(TheCall, DAG, StackPtr, VA,
1788                                                Chain, Arg, Flags));
1789       }
1790     }
1791   }
1792
1793   if (!MemOpChains.empty())
1794     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
1795                         &MemOpChains[0], MemOpChains.size());
1796
1797   // Build a sequence of copy-to-reg nodes chained together with token chain
1798   // and flag operands which copy the outgoing args into registers.
1799   SDValue InFlag;
1800   // Tail call byval lowering might overwrite argument registers so in case of
1801   // tail call optimization the copies to registers are lowered later.
1802   if (!IsTailCall)
1803     for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
1804       Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
1805                                RegsToPass[i].second, InFlag);
1806       InFlag = Chain.getValue(1);
1807     }
1808
1809   
1810   if (Subtarget->isPICStyleGOT()) {
1811     // ELF / PIC requires GOT in the EBX register before function calls via PLT
1812     // GOT pointer.
1813     if (!IsTailCall) {
1814       Chain = DAG.getCopyToReg(Chain, dl, X86::EBX,
1815                                DAG.getNode(X86ISD::GlobalBaseReg,
1816                                            DebugLoc::getUnknownLoc(),
1817                                            getPointerTy()),
1818                                InFlag);
1819       InFlag = Chain.getValue(1);
1820     } else {
1821       // If we are tail calling and generating PIC/GOT style code load the
1822       // address of the callee into ECX. The value in ecx is used as target of
1823       // the tail jump. This is done to circumvent the ebx/callee-saved problem
1824       // for tail calls on PIC/GOT architectures. Normally we would just put the
1825       // address of GOT into ebx and then call target@PLT. But for tail calls
1826       // ebx would be restored (since ebx is callee saved) before jumping to the
1827       // target@PLT.
1828
1829       // Note: The actual moving to ECX is done further down.
1830       GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee);
1831       if (G && !G->getGlobal()->hasHiddenVisibility() &&
1832           !G->getGlobal()->hasProtectedVisibility())
1833         Callee = LowerGlobalAddress(Callee, DAG);
1834       else if (isa<ExternalSymbolSDNode>(Callee))
1835         Callee = LowerExternalSymbol(Callee, DAG);
1836     }
1837   }
1838
1839   if (Is64Bit && isVarArg) {
1840     // From AMD64 ABI document:
1841     // For calls that may call functions that use varargs or stdargs
1842     // (prototype-less calls or calls to functions containing ellipsis (...) in
1843     // the declaration) %al is used as hidden argument to specify the number
1844     // of SSE registers used. The contents of %al do not need to match exactly
1845     // the number of registers, but must be an ubound on the number of SSE
1846     // registers used and is in the range 0 - 8 inclusive.
1847
1848     // FIXME: Verify this on Win64
1849     // Count the number of XMM registers allocated.
1850     static const unsigned XMMArgRegs[] = {
1851       X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
1852       X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
1853     };
1854     unsigned NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs, 8);
1855     assert((Subtarget->hasSSE1() || !NumXMMRegs)
1856            && "SSE registers cannot be used when SSE is disabled");
1857
1858     Chain = DAG.getCopyToReg(Chain, dl, X86::AL,
1859                              DAG.getConstant(NumXMMRegs, MVT::i8), InFlag);
1860     InFlag = Chain.getValue(1);
1861   }
1862
1863
1864   // For tail calls lower the arguments to the 'real' stack slot.
1865   if (IsTailCall) {
1866     SmallVector<SDValue, 8> MemOpChains2;
1867     SDValue FIN;
1868     int FI = 0;
1869     // Do not flag preceeding copytoreg stuff together with the following stuff.
1870     InFlag = SDValue();
1871     for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
1872       CCValAssign &VA = ArgLocs[i];
1873       if (!VA.isRegLoc()) {
1874         assert(VA.isMemLoc());
1875         SDValue Arg = TheCall->getArg(i);
1876         ISD::ArgFlagsTy Flags = TheCall->getArgFlags(i);
1877         // Create frame index.
1878         int32_t Offset = VA.getLocMemOffset()+FPDiff;
1879         uint32_t OpSize = (VA.getLocVT().getSizeInBits()+7)/8;
1880         FI = MF.getFrameInfo()->CreateFixedObject(OpSize, Offset);
1881         FIN = DAG.getFrameIndex(FI, getPointerTy());
1882
1883         if (Flags.isByVal()) {
1884           // Copy relative to framepointer.
1885           SDValue Source = DAG.getIntPtrConstant(VA.getLocMemOffset());
1886           if (StackPtr.getNode() == 0)
1887             StackPtr = DAG.getCopyFromReg(Chain, dl, X86StackPtr,
1888                                           getPointerTy());
1889           Source = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, Source);
1890
1891           MemOpChains2.push_back(CreateCopyOfByValArgument(Source, FIN, Chain,
1892                                                            Flags, DAG, dl));
1893         } else {
1894           // Store relative to framepointer.
1895           MemOpChains2.push_back(
1896             DAG.getStore(Chain, dl, Arg, FIN,
1897                          PseudoSourceValue::getFixedStack(FI), 0));
1898         }
1899       }
1900     }
1901
1902     if (!MemOpChains2.empty())
1903       Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
1904                           &MemOpChains2[0], MemOpChains2.size());
1905
1906     // Copy arguments to their registers.
1907     for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
1908       Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
1909                                RegsToPass[i].second, InFlag);
1910       InFlag = Chain.getValue(1);
1911     }
1912     InFlag =SDValue();
1913
1914     // Store the return address to the appropriate stack slot.
1915     Chain = EmitTailCallStoreRetAddr(DAG, MF, Chain, RetAddrFrIdx, Is64Bit,
1916                                      FPDiff, dl);
1917   }
1918
1919   // If the callee is a GlobalAddress node (quite common, every direct call is)
1920   // turn it into a TargetGlobalAddress node so that legalize doesn't hack it.
1921   if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
1922     // We should use extra load for direct calls to dllimported functions in
1923     // non-JIT mode.
1924     GlobalValue *GV = G->getGlobal();
1925     if (!GV->hasDLLImportLinkage()) {
1926       unsigned char OpFlags = 0;
1927     
1928       // On ELF targets, in both X86-64 and X86-32 mode, direct calls to
1929       // external symbols most go through the PLT in PIC mode.  If the symbol
1930       // has hidden or protected visibility, or if it is static or local, then
1931       // we don't need to use the PLT - we can directly call it.
1932       if (Subtarget->isTargetELF() &&
1933           getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1934           GV->hasDefaultVisibility() && !GV->hasLocalLinkage()) {
1935         OpFlags = X86II::MO_PLT;
1936       } else if (Subtarget->isPICStyleStubAny() &&
1937                (GV->isDeclaration() || GV->isWeakForLinker()) &&
1938                Subtarget->getDarwinVers() < 9) {
1939         // PC-relative references to external symbols should go through $stub,
1940         // unless we're building with the leopard linker or later, which
1941         // automatically synthesizes these stubs.
1942         OpFlags = X86II::MO_DARWIN_STUB;
1943       }
1944
1945       Callee = DAG.getTargetGlobalAddress(GV, getPointerTy(),
1946                                           G->getOffset(), OpFlags);
1947     }
1948   } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
1949     unsigned char OpFlags = 0;
1950
1951     // On ELF targets, in either X86-64 or X86-32 mode, direct calls to external
1952     // symbols should go through the PLT.
1953     if (Subtarget->isTargetELF() &&
1954         getTargetMachine().getRelocationModel() == Reloc::PIC_) {
1955       OpFlags = X86II::MO_PLT;
1956     } else if (Subtarget->isPICStyleStubAny() &&
1957              Subtarget->getDarwinVers() < 9) {
1958       // PC-relative references to external symbols should go through $stub,
1959       // unless we're building with the leopard linker or later, which
1960       // automatically synthesizes these stubs.
1961       OpFlags = X86II::MO_DARWIN_STUB;
1962     }
1963       
1964     Callee = DAG.getTargetExternalSymbol(S->getSymbol(), getPointerTy(),
1965                                          OpFlags);
1966   } else if (IsTailCall) {
1967     unsigned Opc = Is64Bit ? X86::R11 : X86::EAX;
1968
1969     Chain = DAG.getCopyToReg(Chain,  dl,
1970                              DAG.getRegister(Opc, getPointerTy()),
1971                              Callee,InFlag);
1972     Callee = DAG.getRegister(Opc, getPointerTy());
1973     // Add register as live out.
1974     DAG.getMachineFunction().getRegInfo().addLiveOut(Opc);
1975   }
1976
1977   // Returns a chain & a flag for retval copy to use.
1978   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Flag);
1979   SmallVector<SDValue, 8> Ops;
1980
1981   if (IsTailCall) {
1982     Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, true),
1983                            DAG.getIntPtrConstant(0, true), InFlag);
1984     InFlag = Chain.getValue(1);
1985
1986     // Returns a chain & a flag for retval copy to use.
1987     NodeTys = DAG.getVTList(MVT::Other, MVT::Flag);
1988     Ops.clear();
1989   }
1990
1991   Ops.push_back(Chain);
1992   Ops.push_back(Callee);
1993
1994   if (IsTailCall)
1995     Ops.push_back(DAG.getConstant(FPDiff, MVT::i32));
1996
1997   // Add argument registers to the end of the list so that they are known live
1998   // into the call.
1999   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
2000     Ops.push_back(DAG.getRegister(RegsToPass[i].first,
2001                                   RegsToPass[i].second.getValueType()));
2002
2003   // Add an implicit use GOT pointer in EBX.
2004   if (!IsTailCall && Subtarget->isPICStyleGOT())
2005     Ops.push_back(DAG.getRegister(X86::EBX, getPointerTy()));
2006
2007   // Add an implicit use of AL for x86 vararg functions.
2008   if (Is64Bit && isVarArg)
2009     Ops.push_back(DAG.getRegister(X86::AL, MVT::i8));
2010
2011   if (InFlag.getNode())
2012     Ops.push_back(InFlag);
2013
2014   if (IsTailCall) {
2015     assert(InFlag.getNode() &&
2016            "Flag must be set. Depend on flag being set in LowerRET");
2017     Chain = DAG.getNode(X86ISD::TAILCALL, dl,
2018                         TheCall->getVTList(), &Ops[0], Ops.size());
2019
2020     return SDValue(Chain.getNode(), Op.getResNo());
2021   }
2022
2023   Chain = DAG.getNode(X86ISD::CALL, dl, NodeTys, &Ops[0], Ops.size());
2024   InFlag = Chain.getValue(1);
2025
2026   // Create the CALLSEQ_END node.
2027   unsigned NumBytesForCalleeToPush;
2028   if (IsCalleePop(isVarArg, CC))
2029     NumBytesForCalleeToPush = NumBytes;    // Callee pops everything
2030   else if (!Is64Bit && CC != CallingConv::Fast && IsStructRet)
2031     // If this is is a call to a struct-return function, the callee
2032     // pops the hidden struct pointer, so we have to push it back.
2033     // This is common for Darwin/X86, Linux & Mingw32 targets.
2034     NumBytesForCalleeToPush = 4;
2035   else
2036     NumBytesForCalleeToPush = 0;  // Callee pops nothing.
2037
2038   // Returns a flag for retval copy to use.
2039   Chain = DAG.getCALLSEQ_END(Chain,
2040                              DAG.getIntPtrConstant(NumBytes, true),
2041                              DAG.getIntPtrConstant(NumBytesForCalleeToPush,
2042                                                    true),
2043                              InFlag);
2044   InFlag = Chain.getValue(1);
2045
2046   // Handle result values, copying them out of physregs into vregs that we
2047   // return.
2048   return SDValue(LowerCallResult(Chain, InFlag, TheCall, CC, DAG),
2049                  Op.getResNo());
2050 }
2051
2052
2053 //===----------------------------------------------------------------------===//
2054 //                Fast Calling Convention (tail call) implementation
2055 //===----------------------------------------------------------------------===//
2056
2057 //  Like std call, callee cleans arguments, convention except that ECX is
2058 //  reserved for storing the tail called function address. Only 2 registers are
2059 //  free for argument passing (inreg). Tail call optimization is performed
2060 //  provided:
2061 //                * tailcallopt is enabled
2062 //                * caller/callee are fastcc
2063 //  On X86_64 architecture with GOT-style position independent code only local
2064 //  (within module) calls are supported at the moment.
2065 //  To keep the stack aligned according to platform abi the function
2066 //  GetAlignedArgumentStackSize ensures that argument delta is always multiples
2067 //  of stack alignment. (Dynamic linkers need this - darwin's dyld for example)
2068 //  If a tail called function callee has more arguments than the caller the
2069 //  caller needs to make sure that there is room to move the RETADDR to. This is
2070 //  achieved by reserving an area the size of the argument delta right after the
2071 //  original REtADDR, but before the saved framepointer or the spilled registers
2072 //  e.g. caller(arg1, arg2) calls callee(arg1, arg2,arg3,arg4)
2073 //  stack layout:
2074 //    arg1
2075 //    arg2
2076 //    RETADDR
2077 //    [ new RETADDR
2078 //      move area ]
2079 //    (possible EBP)
2080 //    ESI
2081 //    EDI
2082 //    local1 ..
2083
2084 /// GetAlignedArgumentStackSize - Make the stack size align e.g 16n + 12 aligned
2085 /// for a 16 byte align requirement.
2086 unsigned X86TargetLowering::GetAlignedArgumentStackSize(unsigned StackSize,
2087                                                         SelectionDAG& DAG) {
2088   MachineFunction &MF = DAG.getMachineFunction();
2089   const TargetMachine &TM = MF.getTarget();
2090   const TargetFrameInfo &TFI = *TM.getFrameInfo();
2091   unsigned StackAlignment = TFI.getStackAlignment();
2092   uint64_t AlignMask = StackAlignment - 1;
2093   int64_t Offset = StackSize;
2094   uint64_t SlotSize = TD->getPointerSize();
2095   if ( (Offset & AlignMask) <= (StackAlignment - SlotSize) ) {
2096     // Number smaller than 12 so just add the difference.
2097     Offset += ((StackAlignment - SlotSize) - (Offset & AlignMask));
2098   } else {
2099     // Mask out lower bits, add stackalignment once plus the 12 bytes.
2100     Offset = ((~AlignMask) & Offset) + StackAlignment +
2101       (StackAlignment-SlotSize);
2102   }
2103   return Offset;
2104 }
2105
2106 /// IsEligibleForTailCallElimination - Check to see whether the next instruction
2107 /// following the call is a return. A function is eligible if caller/callee
2108 /// calling conventions match, currently only fastcc supports tail calls, and
2109 /// the function CALL is immediatly followed by a RET.
2110 bool X86TargetLowering::IsEligibleForTailCallOptimization(CallSDNode *TheCall,
2111                                                       SDValue Ret,
2112                                                       SelectionDAG& DAG) const {
2113   if (!PerformTailCallOpt)
2114     return false;
2115
2116   if (CheckTailCallReturnConstraints(TheCall, Ret)) {
2117     unsigned CallerCC =
2118       DAG.getMachineFunction().getFunction()->getCallingConv();
2119     unsigned CalleeCC = TheCall->getCallingConv();
2120     if (CalleeCC == CallingConv::Fast && CallerCC == CalleeCC)
2121       return true;
2122   }
2123
2124   return false;
2125 }
2126
2127 FastISel *
2128 X86TargetLowering::createFastISel(MachineFunction &mf,
2129                                   MachineModuleInfo *mmo,
2130                                   DwarfWriter *dw,
2131                                   DenseMap<const Value *, unsigned> &vm,
2132                                   DenseMap<const BasicBlock *,
2133                                            MachineBasicBlock *> &bm,
2134                                   DenseMap<const AllocaInst *, int> &am
2135 #ifndef NDEBUG
2136                                   , SmallSet<Instruction*, 8> &cil
2137 #endif
2138                                   ) {
2139   return X86::createFastISel(mf, mmo, dw, vm, bm, am
2140 #ifndef NDEBUG
2141                              , cil
2142 #endif
2143                              );
2144 }
2145
2146
2147 //===----------------------------------------------------------------------===//
2148 //                           Other Lowering Hooks
2149 //===----------------------------------------------------------------------===//
2150
2151
2152 SDValue X86TargetLowering::getReturnAddressFrameIndex(SelectionDAG &DAG) {
2153   MachineFunction &MF = DAG.getMachineFunction();
2154   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
2155   int ReturnAddrIndex = FuncInfo->getRAIndex();
2156
2157   if (ReturnAddrIndex == 0) {
2158     // Set up a frame object for the return address.
2159     uint64_t SlotSize = TD->getPointerSize();
2160     ReturnAddrIndex = MF.getFrameInfo()->CreateFixedObject(SlotSize, -SlotSize);
2161     FuncInfo->setRAIndex(ReturnAddrIndex);
2162   }
2163
2164   return DAG.getFrameIndex(ReturnAddrIndex, getPointerTy());
2165 }
2166
2167
2168 /// TranslateX86CC - do a one to one translation of a ISD::CondCode to the X86
2169 /// specific condition code, returning the condition code and the LHS/RHS of the
2170 /// comparison to make.
2171 static unsigned TranslateX86CC(ISD::CondCode SetCCOpcode, bool isFP,
2172                                SDValue &LHS, SDValue &RHS, SelectionDAG &DAG) {
2173   if (!isFP) {
2174     if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) {
2175       if (SetCCOpcode == ISD::SETGT && RHSC->isAllOnesValue()) {
2176         // X > -1   -> X == 0, jump !sign.
2177         RHS = DAG.getConstant(0, RHS.getValueType());
2178         return X86::COND_NS;
2179       } else if (SetCCOpcode == ISD::SETLT && RHSC->isNullValue()) {
2180         // X < 0   -> X == 0, jump on sign.
2181         return X86::COND_S;
2182       } else if (SetCCOpcode == ISD::SETLT && RHSC->getZExtValue() == 1) {
2183         // X < 1   -> X <= 0
2184         RHS = DAG.getConstant(0, RHS.getValueType());
2185         return X86::COND_LE;
2186       }
2187     }
2188
2189     switch (SetCCOpcode) {
2190     default: llvm_unreachable("Invalid integer condition!");
2191     case ISD::SETEQ:  return X86::COND_E;
2192     case ISD::SETGT:  return X86::COND_G;
2193     case ISD::SETGE:  return X86::COND_GE;
2194     case ISD::SETLT:  return X86::COND_L;
2195     case ISD::SETLE:  return X86::COND_LE;
2196     case ISD::SETNE:  return X86::COND_NE;
2197     case ISD::SETULT: return X86::COND_B;
2198     case ISD::SETUGT: return X86::COND_A;
2199     case ISD::SETULE: return X86::COND_BE;
2200     case ISD::SETUGE: return X86::COND_AE;
2201     }
2202   }
2203
2204   // First determine if it is required or is profitable to flip the operands.
2205
2206   // If LHS is a foldable load, but RHS is not, flip the condition.
2207   if ((ISD::isNON_EXTLoad(LHS.getNode()) && LHS.hasOneUse()) &&
2208       !(ISD::isNON_EXTLoad(RHS.getNode()) && RHS.hasOneUse())) {
2209     SetCCOpcode = getSetCCSwappedOperands(SetCCOpcode);
2210     std::swap(LHS, RHS);
2211   }
2212
2213   switch (SetCCOpcode) {
2214   default: break;
2215   case ISD::SETOLT:
2216   case ISD::SETOLE:
2217   case ISD::SETUGT:
2218   case ISD::SETUGE:
2219     std::swap(LHS, RHS);
2220     break;
2221   }
2222
2223   // On a floating point condition, the flags are set as follows:
2224   // ZF  PF  CF   op
2225   //  0 | 0 | 0 | X > Y
2226   //  0 | 0 | 1 | X < Y
2227   //  1 | 0 | 0 | X == Y
2228   //  1 | 1 | 1 | unordered
2229   switch (SetCCOpcode) {
2230   default: llvm_unreachable("Condcode should be pre-legalized away");
2231   case ISD::SETUEQ:
2232   case ISD::SETEQ:   return X86::COND_E;
2233   case ISD::SETOLT:              // flipped
2234   case ISD::SETOGT:
2235   case ISD::SETGT:   return X86::COND_A;
2236   case ISD::SETOLE:              // flipped
2237   case ISD::SETOGE:
2238   case ISD::SETGE:   return X86::COND_AE;
2239   case ISD::SETUGT:              // flipped
2240   case ISD::SETULT:
2241   case ISD::SETLT:   return X86::COND_B;
2242   case ISD::SETUGE:              // flipped
2243   case ISD::SETULE:
2244   case ISD::SETLE:   return X86::COND_BE;
2245   case ISD::SETONE:
2246   case ISD::SETNE:   return X86::COND_NE;
2247   case ISD::SETUO:   return X86::COND_P;
2248   case ISD::SETO:    return X86::COND_NP;
2249   }
2250 }
2251
2252 /// hasFPCMov - is there a floating point cmov for the specific X86 condition
2253 /// code. Current x86 isa includes the following FP cmov instructions:
2254 /// fcmovb, fcomvbe, fcomve, fcmovu, fcmovae, fcmova, fcmovne, fcmovnu.
2255 static bool hasFPCMov(unsigned X86CC) {
2256   switch (X86CC) {
2257   default:
2258     return false;
2259   case X86::COND_B:
2260   case X86::COND_BE:
2261   case X86::COND_E:
2262   case X86::COND_P:
2263   case X86::COND_A:
2264   case X86::COND_AE:
2265   case X86::COND_NE:
2266   case X86::COND_NP:
2267     return true;
2268   }
2269 }
2270
2271 /// isUndefOrInRange - Return true if Val is undef or if its value falls within
2272 /// the specified range (L, H].
2273 static bool isUndefOrInRange(int Val, int Low, int Hi) {
2274   return (Val < 0) || (Val >= Low && Val < Hi);
2275 }
2276
2277 /// isUndefOrEqual - Val is either less than zero (undef) or equal to the
2278 /// specified value.
2279 static bool isUndefOrEqual(int Val, int CmpVal) {
2280   if (Val < 0 || Val == CmpVal)
2281     return true;
2282   return false;
2283 }
2284
2285 /// isPSHUFDMask - Return true if the node specifies a shuffle of elements that
2286 /// is suitable for input to PSHUFD or PSHUFW.  That is, it doesn't reference
2287 /// the second operand.
2288 static bool isPSHUFDMask(const SmallVectorImpl<int> &Mask, MVT VT) {
2289   if (VT == MVT::v4f32 || VT == MVT::v4i32 || VT == MVT::v4i16)
2290     return (Mask[0] < 4 && Mask[1] < 4 && Mask[2] < 4 && Mask[3] < 4);
2291   if (VT == MVT::v2f64 || VT == MVT::v2i64)
2292     return (Mask[0] < 2 && Mask[1] < 2);
2293   return false;
2294 }
2295
2296 bool X86::isPSHUFDMask(ShuffleVectorSDNode *N) {
2297   SmallVector<int, 8> M; 
2298   N->getMask(M);
2299   return ::isPSHUFDMask(M, N->getValueType(0));
2300 }
2301
2302 /// isPSHUFHWMask - Return true if the node specifies a shuffle of elements that
2303 /// is suitable for input to PSHUFHW.
2304 static bool isPSHUFHWMask(const SmallVectorImpl<int> &Mask, MVT VT) {
2305   if (VT != MVT::v8i16)
2306     return false;
2307   
2308   // Lower quadword copied in order or undef.
2309   for (int i = 0; i != 4; ++i)
2310     if (Mask[i] >= 0 && Mask[i] != i)
2311       return false;
2312   
2313   // Upper quadword shuffled.
2314   for (int i = 4; i != 8; ++i)
2315     if (Mask[i] >= 0 && (Mask[i] < 4 || Mask[i] > 7))
2316       return false;
2317   
2318   return true;
2319 }
2320
2321 bool X86::isPSHUFHWMask(ShuffleVectorSDNode *N) {
2322   SmallVector<int, 8> M; 
2323   N->getMask(M);
2324   return ::isPSHUFHWMask(M, N->getValueType(0));
2325 }
2326
2327 /// isPSHUFLWMask - Return true if the node specifies a shuffle of elements that
2328 /// is suitable for input to PSHUFLW.
2329 static bool isPSHUFLWMask(const SmallVectorImpl<int> &Mask, MVT VT) {
2330   if (VT != MVT::v8i16)
2331     return false;
2332   
2333   // Upper quadword copied in order.
2334   for (int i = 4; i != 8; ++i)
2335     if (Mask[i] >= 0 && Mask[i] != i)
2336       return false;
2337   
2338   // Lower quadword shuffled.
2339   for (int i = 0; i != 4; ++i)
2340     if (Mask[i] >= 4)
2341       return false;
2342   
2343   return true;
2344 }
2345
2346 bool X86::isPSHUFLWMask(ShuffleVectorSDNode *N) {
2347   SmallVector<int, 8> M; 
2348   N->getMask(M);
2349   return ::isPSHUFLWMask(M, N->getValueType(0));
2350 }
2351
2352 /// isSHUFPMask - Return true if the specified VECTOR_SHUFFLE operand
2353 /// specifies a shuffle of elements that is suitable for input to SHUFP*.
2354 static bool isSHUFPMask(const SmallVectorImpl<int> &Mask, MVT VT) {
2355   int NumElems = VT.getVectorNumElements();
2356   if (NumElems != 2 && NumElems != 4)
2357     return false;
2358   
2359   int Half = NumElems / 2;
2360   for (int i = 0; i < Half; ++i)
2361     if (!isUndefOrInRange(Mask[i], 0, NumElems))
2362       return false;
2363   for (int i = Half; i < NumElems; ++i)
2364     if (!isUndefOrInRange(Mask[i], NumElems, NumElems*2))
2365       return false;
2366   
2367   return true;
2368 }
2369
2370 bool X86::isSHUFPMask(ShuffleVectorSDNode *N) {
2371   SmallVector<int, 8> M;
2372   N->getMask(M);
2373   return ::isSHUFPMask(M, N->getValueType(0));
2374 }
2375
2376 /// isCommutedSHUFP - Returns true if the shuffle mask is exactly
2377 /// the reverse of what x86 shuffles want. x86 shuffles requires the lower
2378 /// half elements to come from vector 1 (which would equal the dest.) and
2379 /// the upper half to come from vector 2.
2380 static bool isCommutedSHUFPMask(const SmallVectorImpl<int> &Mask, MVT VT) {
2381   int NumElems = VT.getVectorNumElements();
2382   
2383   if (NumElems != 2 && NumElems != 4) 
2384     return false;
2385   
2386   int Half = NumElems / 2;
2387   for (int i = 0; i < Half; ++i)
2388     if (!isUndefOrInRange(Mask[i], NumElems, NumElems*2))
2389       return false;
2390   for (int i = Half; i < NumElems; ++i)
2391     if (!isUndefOrInRange(Mask[i], 0, NumElems))
2392       return false;
2393   return true;
2394 }
2395
2396 static bool isCommutedSHUFP(ShuffleVectorSDNode *N) {
2397   SmallVector<int, 8> M;
2398   N->getMask(M);
2399   return isCommutedSHUFPMask(M, N->getValueType(0));
2400 }
2401
2402 /// isMOVHLPSMask - Return true if the specified VECTOR_SHUFFLE operand
2403 /// specifies a shuffle of elements that is suitable for input to MOVHLPS.
2404 bool X86::isMOVHLPSMask(ShuffleVectorSDNode *N) {
2405   if (N->getValueType(0).getVectorNumElements() != 4)
2406     return false;
2407
2408   // Expect bit0 == 6, bit1 == 7, bit2 == 2, bit3 == 3
2409   return isUndefOrEqual(N->getMaskElt(0), 6) &&
2410          isUndefOrEqual(N->getMaskElt(1), 7) &&
2411          isUndefOrEqual(N->getMaskElt(2), 2) &&
2412          isUndefOrEqual(N->getMaskElt(3), 3);
2413 }
2414
2415 /// isMOVLPMask - Return true if the specified VECTOR_SHUFFLE operand
2416 /// specifies a shuffle of elements that is suitable for input to MOVLP{S|D}.
2417 bool X86::isMOVLPMask(ShuffleVectorSDNode *N) {
2418   unsigned NumElems = N->getValueType(0).getVectorNumElements();
2419
2420   if (NumElems != 2 && NumElems != 4)
2421     return false;
2422
2423   for (unsigned i = 0; i < NumElems/2; ++i)
2424     if (!isUndefOrEqual(N->getMaskElt(i), i + NumElems))
2425       return false;
2426
2427   for (unsigned i = NumElems/2; i < NumElems; ++i)
2428     if (!isUndefOrEqual(N->getMaskElt(i), i))
2429       return false;
2430
2431   return true;
2432 }
2433
2434 /// isMOVHPMask - Return true if the specified VECTOR_SHUFFLE operand
2435 /// specifies a shuffle of elements that is suitable for input to MOVHP{S|D}
2436 /// and MOVLHPS.
2437 bool X86::isMOVHPMask(ShuffleVectorSDNode *N) {
2438   unsigned NumElems = N->getValueType(0).getVectorNumElements();
2439
2440   if (NumElems != 2 && NumElems != 4)
2441     return false;
2442
2443   for (unsigned i = 0; i < NumElems/2; ++i)
2444     if (!isUndefOrEqual(N->getMaskElt(i), i))
2445       return false;
2446
2447   for (unsigned i = 0; i < NumElems/2; ++i)
2448     if (!isUndefOrEqual(N->getMaskElt(i + NumElems/2), i + NumElems))
2449       return false;
2450
2451   return true;
2452 }
2453
2454 /// isMOVHLPS_v_undef_Mask - Special case of isMOVHLPSMask for canonical form
2455 /// of vector_shuffle v, v, <2, 3, 2, 3>, i.e. vector_shuffle v, undef,
2456 /// <2, 3, 2, 3>
2457 bool X86::isMOVHLPS_v_undef_Mask(ShuffleVectorSDNode *N) {
2458   unsigned NumElems = N->getValueType(0).getVectorNumElements();
2459   
2460   if (NumElems != 4)
2461     return false;
2462   
2463   return isUndefOrEqual(N->getMaskElt(0), 2) && 
2464          isUndefOrEqual(N->getMaskElt(1), 3) &&
2465          isUndefOrEqual(N->getMaskElt(2), 2) && 
2466          isUndefOrEqual(N->getMaskElt(3), 3);
2467 }
2468
2469 /// isUNPCKLMask - Return true if the specified VECTOR_SHUFFLE operand
2470 /// specifies a shuffle of elements that is suitable for input to UNPCKL.
2471 static bool isUNPCKLMask(const SmallVectorImpl<int> &Mask, MVT VT,
2472                          bool V2IsSplat = false) {
2473   int NumElts = VT.getVectorNumElements();
2474   if (NumElts != 2 && NumElts != 4 && NumElts != 8 && NumElts != 16)
2475     return false;
2476   
2477   for (int i = 0, j = 0; i != NumElts; i += 2, ++j) {
2478     int BitI  = Mask[i];
2479     int BitI1 = Mask[i+1];
2480     if (!isUndefOrEqual(BitI, j))
2481       return false;
2482     if (V2IsSplat) {
2483       if (!isUndefOrEqual(BitI1, NumElts))
2484         return false;
2485     } else {
2486       if (!isUndefOrEqual(BitI1, j + NumElts))
2487         return false;
2488     }
2489   }
2490   return true;
2491 }
2492
2493 bool X86::isUNPCKLMask(ShuffleVectorSDNode *N, bool V2IsSplat) {
2494   SmallVector<int, 8> M;
2495   N->getMask(M);
2496   return ::isUNPCKLMask(M, N->getValueType(0), V2IsSplat);
2497 }
2498
2499 /// isUNPCKHMask - Return true if the specified VECTOR_SHUFFLE operand
2500 /// specifies a shuffle of elements that is suitable for input to UNPCKH.
2501 static bool isUNPCKHMask(const SmallVectorImpl<int> &Mask, MVT VT, 
2502                          bool V2IsSplat = false) {
2503   int NumElts = VT.getVectorNumElements();
2504   if (NumElts != 2 && NumElts != 4 && NumElts != 8 && NumElts != 16)
2505     return false;
2506   
2507   for (int i = 0, j = 0; i != NumElts; i += 2, ++j) {
2508     int BitI  = Mask[i];
2509     int BitI1 = Mask[i+1];
2510     if (!isUndefOrEqual(BitI, j + NumElts/2))
2511       return false;
2512     if (V2IsSplat) {
2513       if (isUndefOrEqual(BitI1, NumElts))
2514         return false;
2515     } else {
2516       if (!isUndefOrEqual(BitI1, j + NumElts/2 + NumElts))
2517         return false;
2518     }
2519   }
2520   return true;
2521 }
2522
2523 bool X86::isUNPCKHMask(ShuffleVectorSDNode *N, bool V2IsSplat) {
2524   SmallVector<int, 8> M;
2525   N->getMask(M);
2526   return ::isUNPCKHMask(M, N->getValueType(0), V2IsSplat);
2527 }
2528
2529 /// isUNPCKL_v_undef_Mask - Special case of isUNPCKLMask for canonical form
2530 /// of vector_shuffle v, v, <0, 4, 1, 5>, i.e. vector_shuffle v, undef,
2531 /// <0, 0, 1, 1>
2532 static bool isUNPCKL_v_undef_Mask(const SmallVectorImpl<int> &Mask, MVT VT) {
2533   int NumElems = VT.getVectorNumElements();
2534   if (NumElems != 2 && NumElems != 4 && NumElems != 8 && NumElems != 16)
2535     return false;
2536   
2537   for (int i = 0, j = 0; i != NumElems; i += 2, ++j) {
2538     int BitI  = Mask[i];
2539     int BitI1 = Mask[i+1];
2540     if (!isUndefOrEqual(BitI, j))
2541       return false;
2542     if (!isUndefOrEqual(BitI1, j))
2543       return false;
2544   }
2545   return true;
2546 }
2547
2548 bool X86::isUNPCKL_v_undef_Mask(ShuffleVectorSDNode *N) {
2549   SmallVector<int, 8> M;
2550   N->getMask(M);
2551   return ::isUNPCKL_v_undef_Mask(M, N->getValueType(0));
2552 }
2553
2554 /// isUNPCKH_v_undef_Mask - Special case of isUNPCKHMask for canonical form
2555 /// of vector_shuffle v, v, <2, 6, 3, 7>, i.e. vector_shuffle v, undef,
2556 /// <2, 2, 3, 3>
2557 static bool isUNPCKH_v_undef_Mask(const SmallVectorImpl<int> &Mask, MVT VT) {
2558   int NumElems = VT.getVectorNumElements();
2559   if (NumElems != 2 && NumElems != 4 && NumElems != 8 && NumElems != 16)
2560     return false;
2561   
2562   for (int i = 0, j = NumElems / 2; i != NumElems; i += 2, ++j) {
2563     int BitI  = Mask[i];
2564     int BitI1 = Mask[i+1];
2565     if (!isUndefOrEqual(BitI, j))
2566       return false;
2567     if (!isUndefOrEqual(BitI1, j))
2568       return false;
2569   }
2570   return true;
2571 }
2572
2573 bool X86::isUNPCKH_v_undef_Mask(ShuffleVectorSDNode *N) {
2574   SmallVector<int, 8> M;
2575   N->getMask(M);
2576   return ::isUNPCKH_v_undef_Mask(M, N->getValueType(0));
2577 }
2578
2579 /// isMOVLMask - Return true if the specified VECTOR_SHUFFLE operand
2580 /// specifies a shuffle of elements that is suitable for input to MOVSS,
2581 /// MOVSD, and MOVD, i.e. setting the lowest element.
2582 static bool isMOVLMask(const SmallVectorImpl<int> &Mask, MVT VT) {
2583   if (VT.getVectorElementType().getSizeInBits() < 32)
2584     return false;
2585
2586   int NumElts = VT.getVectorNumElements();
2587   
2588   if (!isUndefOrEqual(Mask[0], NumElts))
2589     return false;
2590   
2591   for (int i = 1; i < NumElts; ++i)
2592     if (!isUndefOrEqual(Mask[i], i))
2593       return false;
2594   
2595   return true;
2596 }
2597
2598 bool X86::isMOVLMask(ShuffleVectorSDNode *N) {
2599   SmallVector<int, 8> M;
2600   N->getMask(M);
2601   return ::isMOVLMask(M, N->getValueType(0));
2602 }
2603
2604 /// isCommutedMOVL - Returns true if the shuffle mask is except the reverse
2605 /// of what x86 movss want. X86 movs requires the lowest  element to be lowest
2606 /// element of vector 2 and the other elements to come from vector 1 in order.
2607 static bool isCommutedMOVLMask(const SmallVectorImpl<int> &Mask, MVT VT,
2608                                bool V2IsSplat = false, bool V2IsUndef = false) {
2609   int NumOps = VT.getVectorNumElements();
2610   if (NumOps != 2 && NumOps != 4 && NumOps != 8 && NumOps != 16)
2611     return false;
2612   
2613   if (!isUndefOrEqual(Mask[0], 0))
2614     return false;
2615   
2616   for (int i = 1; i < NumOps; ++i)
2617     if (!(isUndefOrEqual(Mask[i], i+NumOps) ||
2618           (V2IsUndef && isUndefOrInRange(Mask[i], NumOps, NumOps*2)) ||
2619           (V2IsSplat && isUndefOrEqual(Mask[i], NumOps))))
2620       return false;
2621   
2622   return true;
2623 }
2624
2625 static bool isCommutedMOVL(ShuffleVectorSDNode *N, bool V2IsSplat = false,
2626                            bool V2IsUndef = false) {
2627   SmallVector<int, 8> M;
2628   N->getMask(M);
2629   return isCommutedMOVLMask(M, N->getValueType(0), V2IsSplat, V2IsUndef);
2630 }
2631
2632 /// isMOVSHDUPMask - Return true if the specified VECTOR_SHUFFLE operand
2633 /// specifies a shuffle of elements that is suitable for input to MOVSHDUP.
2634 bool X86::isMOVSHDUPMask(ShuffleVectorSDNode *N) {
2635   if (N->getValueType(0).getVectorNumElements() != 4)
2636     return false;
2637
2638   // Expect 1, 1, 3, 3
2639   for (unsigned i = 0; i < 2; ++i) {
2640     int Elt = N->getMaskElt(i);
2641     if (Elt >= 0 && Elt != 1)
2642       return false;
2643   }
2644
2645   bool HasHi = false;
2646   for (unsigned i = 2; i < 4; ++i) {
2647     int Elt = N->getMaskElt(i);
2648     if (Elt >= 0 && Elt != 3)
2649       return false;
2650     if (Elt == 3)
2651       HasHi = true;
2652   }
2653   // Don't use movshdup if it can be done with a shufps.
2654   // FIXME: verify that matching u, u, 3, 3 is what we want.
2655   return HasHi;
2656 }
2657
2658 /// isMOVSLDUPMask - Return true if the specified VECTOR_SHUFFLE operand
2659 /// specifies a shuffle of elements that is suitable for input to MOVSLDUP.
2660 bool X86::isMOVSLDUPMask(ShuffleVectorSDNode *N) {
2661   if (N->getValueType(0).getVectorNumElements() != 4)
2662     return false;
2663
2664   // Expect 0, 0, 2, 2
2665   for (unsigned i = 0; i < 2; ++i)
2666     if (N->getMaskElt(i) > 0)
2667       return false;
2668
2669   bool HasHi = false;
2670   for (unsigned i = 2; i < 4; ++i) {
2671     int Elt = N->getMaskElt(i);
2672     if (Elt >= 0 && Elt != 2)
2673       return false;
2674     if (Elt == 2)
2675       HasHi = true;
2676   }
2677   // Don't use movsldup if it can be done with a shufps.
2678   return HasHi;
2679 }
2680
2681 /// isMOVDDUPMask - Return true if the specified VECTOR_SHUFFLE operand
2682 /// specifies a shuffle of elements that is suitable for input to MOVDDUP.
2683 bool X86::isMOVDDUPMask(ShuffleVectorSDNode *N) {
2684   int e = N->getValueType(0).getVectorNumElements() / 2;
2685   
2686   for (int i = 0; i < e; ++i)
2687     if (!isUndefOrEqual(N->getMaskElt(i), i))
2688       return false;
2689   for (int i = 0; i < e; ++i)
2690     if (!isUndefOrEqual(N->getMaskElt(e+i), i))
2691       return false;
2692   return true;
2693 }
2694
2695 /// getShuffleSHUFImmediate - Return the appropriate immediate to shuffle
2696 /// the specified isShuffleMask VECTOR_SHUFFLE mask with PSHUF* and SHUFP*
2697 /// instructions.
2698 unsigned X86::getShuffleSHUFImmediate(SDNode *N) {
2699   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
2700   int NumOperands = SVOp->getValueType(0).getVectorNumElements();
2701
2702   unsigned Shift = (NumOperands == 4) ? 2 : 1;
2703   unsigned Mask = 0;
2704   for (int i = 0; i < NumOperands; ++i) {
2705     int Val = SVOp->getMaskElt(NumOperands-i-1);
2706     if (Val < 0) Val = 0;
2707     if (Val >= NumOperands) Val -= NumOperands;
2708     Mask |= Val;
2709     if (i != NumOperands - 1)
2710       Mask <<= Shift;
2711   }
2712   return Mask;
2713 }
2714
2715 /// getShufflePSHUFHWImmediate - Return the appropriate immediate to shuffle
2716 /// the specified isShuffleMask VECTOR_SHUFFLE mask with PSHUFHW
2717 /// instructions.
2718 unsigned X86::getShufflePSHUFHWImmediate(SDNode *N) {
2719   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
2720   unsigned Mask = 0;
2721   // 8 nodes, but we only care about the last 4.
2722   for (unsigned i = 7; i >= 4; --i) {
2723     int Val = SVOp->getMaskElt(i);
2724     if (Val >= 0)
2725       Mask |= (Val - 4);
2726     if (i != 4)
2727       Mask <<= 2;
2728   }
2729   return Mask;
2730 }
2731
2732 /// getShufflePSHUFLWImmediate - Return the appropriate immediate to shuffle
2733 /// the specified isShuffleMask VECTOR_SHUFFLE mask with PSHUFLW
2734 /// instructions.
2735 unsigned X86::getShufflePSHUFLWImmediate(SDNode *N) {
2736   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
2737   unsigned Mask = 0;
2738   // 8 nodes, but we only care about the first 4.
2739   for (int i = 3; i >= 0; --i) {
2740     int Val = SVOp->getMaskElt(i);
2741     if (Val >= 0)
2742       Mask |= Val;
2743     if (i != 0)
2744       Mask <<= 2;
2745   }
2746   return Mask;
2747 }
2748
2749 /// CommuteVectorShuffle - Swap vector_shuffle operands as well as values in
2750 /// their permute mask.
2751 static SDValue CommuteVectorShuffle(ShuffleVectorSDNode *SVOp,
2752                                     SelectionDAG &DAG) {
2753   MVT VT = SVOp->getValueType(0);
2754   unsigned NumElems = VT.getVectorNumElements();
2755   SmallVector<int, 8> MaskVec;
2756   
2757   for (unsigned i = 0; i != NumElems; ++i) {
2758     int idx = SVOp->getMaskElt(i);
2759     if (idx < 0)
2760       MaskVec.push_back(idx);
2761     else if (idx < (int)NumElems)
2762       MaskVec.push_back(idx + NumElems);
2763     else
2764       MaskVec.push_back(idx - NumElems);
2765   }
2766   return DAG.getVectorShuffle(VT, SVOp->getDebugLoc(), SVOp->getOperand(1),
2767                               SVOp->getOperand(0), &MaskVec[0]);
2768 }
2769
2770 /// CommuteVectorShuffleMask - Change values in a shuffle permute mask assuming
2771 /// the two vector operands have swapped position.
2772 static void CommuteVectorShuffleMask(SmallVectorImpl<int> &Mask, MVT VT) {
2773   unsigned NumElems = VT.getVectorNumElements();
2774   for (unsigned i = 0; i != NumElems; ++i) {
2775     int idx = Mask[i];
2776     if (idx < 0)
2777       continue;
2778     else if (idx < (int)NumElems)
2779       Mask[i] = idx + NumElems;
2780     else
2781       Mask[i] = idx - NumElems;
2782   }
2783 }
2784
2785 /// ShouldXformToMOVHLPS - Return true if the node should be transformed to
2786 /// match movhlps. The lower half elements should come from upper half of
2787 /// V1 (and in order), and the upper half elements should come from the upper
2788 /// half of V2 (and in order).
2789 static bool ShouldXformToMOVHLPS(ShuffleVectorSDNode *Op) {
2790   if (Op->getValueType(0).getVectorNumElements() != 4)
2791     return false;
2792   for (unsigned i = 0, e = 2; i != e; ++i)
2793     if (!isUndefOrEqual(Op->getMaskElt(i), i+2))
2794       return false;
2795   for (unsigned i = 2; i != 4; ++i)
2796     if (!isUndefOrEqual(Op->getMaskElt(i), i+4))
2797       return false;
2798   return true;
2799 }
2800
2801 /// isScalarLoadToVector - Returns true if the node is a scalar load that
2802 /// is promoted to a vector. It also returns the LoadSDNode by reference if
2803 /// required.
2804 static bool isScalarLoadToVector(SDNode *N, LoadSDNode **LD = NULL) {
2805   if (N->getOpcode() != ISD::SCALAR_TO_VECTOR)
2806     return false;
2807   N = N->getOperand(0).getNode();
2808   if (!ISD::isNON_EXTLoad(N))
2809     return false;
2810   if (LD)
2811     *LD = cast<LoadSDNode>(N);
2812   return true;
2813 }
2814
2815 /// ShouldXformToMOVLP{S|D} - Return true if the node should be transformed to
2816 /// match movlp{s|d}. The lower half elements should come from lower half of
2817 /// V1 (and in order), and the upper half elements should come from the upper
2818 /// half of V2 (and in order). And since V1 will become the source of the
2819 /// MOVLP, it must be either a vector load or a scalar load to vector.
2820 static bool ShouldXformToMOVLP(SDNode *V1, SDNode *V2,
2821                                ShuffleVectorSDNode *Op) {
2822   if (!ISD::isNON_EXTLoad(V1) && !isScalarLoadToVector(V1))
2823     return false;
2824   // Is V2 is a vector load, don't do this transformation. We will try to use
2825   // load folding shufps op.
2826   if (ISD::isNON_EXTLoad(V2))
2827     return false;
2828
2829   unsigned NumElems = Op->getValueType(0).getVectorNumElements();
2830   
2831   if (NumElems != 2 && NumElems != 4)
2832     return false;
2833   for (unsigned i = 0, e = NumElems/2; i != e; ++i)
2834     if (!isUndefOrEqual(Op->getMaskElt(i), i))
2835       return false;
2836   for (unsigned i = NumElems/2; i != NumElems; ++i)
2837     if (!isUndefOrEqual(Op->getMaskElt(i), i+NumElems))
2838       return false;
2839   return true;
2840 }
2841
2842 /// isSplatVector - Returns true if N is a BUILD_VECTOR node whose elements are
2843 /// all the same.
2844 static bool isSplatVector(SDNode *N) {
2845   if (N->getOpcode() != ISD::BUILD_VECTOR)
2846     return false;
2847
2848   SDValue SplatValue = N->getOperand(0);
2849   for (unsigned i = 1, e = N->getNumOperands(); i != e; ++i)
2850     if (N->getOperand(i) != SplatValue)
2851       return false;
2852   return true;
2853 }
2854
2855 /// isZeroNode - Returns true if Elt is a constant zero or a floating point
2856 /// constant +0.0.
2857 static inline bool isZeroNode(SDValue Elt) {
2858   return ((isa<ConstantSDNode>(Elt) &&
2859            cast<ConstantSDNode>(Elt)->getZExtValue() == 0) ||
2860           (isa<ConstantFPSDNode>(Elt) &&
2861            cast<ConstantFPSDNode>(Elt)->getValueAPF().isPosZero()));
2862 }
2863
2864 /// isZeroShuffle - Returns true if N is a VECTOR_SHUFFLE that can be resolved
2865 /// to an zero vector. 
2866 /// FIXME: move to dag combiner / method on ShuffleVectorSDNode
2867 static bool isZeroShuffle(ShuffleVectorSDNode *N) {
2868   SDValue V1 = N->getOperand(0);
2869   SDValue V2 = N->getOperand(1);
2870   unsigned NumElems = N->getValueType(0).getVectorNumElements();
2871   for (unsigned i = 0; i != NumElems; ++i) {
2872     int Idx = N->getMaskElt(i);
2873     if (Idx >= (int)NumElems) {
2874       unsigned Opc = V2.getOpcode();
2875       if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V2.getNode()))
2876         continue;
2877       if (Opc != ISD::BUILD_VECTOR || !isZeroNode(V2.getOperand(Idx-NumElems)))
2878         return false;
2879     } else if (Idx >= 0) {
2880       unsigned Opc = V1.getOpcode();
2881       if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V1.getNode()))
2882         continue;
2883       if (Opc != ISD::BUILD_VECTOR || !isZeroNode(V1.getOperand(Idx)))
2884         return false;
2885     }
2886   }
2887   return true;
2888 }
2889
2890 /// getZeroVector - Returns a vector of specified type with all zero elements.
2891 ///
2892 static SDValue getZeroVector(MVT VT, bool HasSSE2, SelectionDAG &DAG,
2893                              DebugLoc dl) {
2894   assert(VT.isVector() && "Expected a vector type");
2895
2896   // Always build zero vectors as <4 x i32> or <2 x i32> bitcasted to their dest
2897   // type.  This ensures they get CSE'd.
2898   SDValue Vec;
2899   if (VT.getSizeInBits() == 64) { // MMX
2900     SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
2901     Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v2i32, Cst, Cst);
2902   } else if (HasSSE2) {  // SSE2
2903     SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
2904     Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
2905   } else { // SSE1
2906     SDValue Cst = DAG.getTargetConstantFP(+0.0, MVT::f32);
2907     Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4f32, Cst, Cst, Cst, Cst);
2908   }
2909   return DAG.getNode(ISD::BIT_CONVERT, dl, VT, Vec);
2910 }
2911
2912 /// getOnesVector - Returns a vector of specified type with all bits set.
2913 ///
2914 static SDValue getOnesVector(MVT VT, SelectionDAG &DAG, DebugLoc dl) {
2915   assert(VT.isVector() && "Expected a vector type");
2916
2917   // Always build ones vectors as <4 x i32> or <2 x i32> bitcasted to their dest
2918   // type.  This ensures they get CSE'd.
2919   SDValue Cst = DAG.getTargetConstant(~0U, MVT::i32);
2920   SDValue Vec;
2921   if (VT.getSizeInBits() == 64)  // MMX
2922     Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v2i32, Cst, Cst);
2923   else                                              // SSE
2924     Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
2925   return DAG.getNode(ISD::BIT_CONVERT, dl, VT, Vec);
2926 }
2927
2928
2929 /// NormalizeMask - V2 is a splat, modify the mask (if needed) so all elements
2930 /// that point to V2 points to its first element.
2931 static SDValue NormalizeMask(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
2932   MVT VT = SVOp->getValueType(0);
2933   unsigned NumElems = VT.getVectorNumElements();
2934   
2935   bool Changed = false;
2936   SmallVector<int, 8> MaskVec;
2937   SVOp->getMask(MaskVec);
2938   
2939   for (unsigned i = 0; i != NumElems; ++i) {
2940     if (MaskVec[i] > (int)NumElems) {
2941       MaskVec[i] = NumElems;
2942       Changed = true;
2943     }
2944   }
2945   if (Changed)
2946     return DAG.getVectorShuffle(VT, SVOp->getDebugLoc(), SVOp->getOperand(0),
2947                                 SVOp->getOperand(1), &MaskVec[0]);
2948   return SDValue(SVOp, 0);
2949 }
2950
2951 /// getMOVLMask - Returns a vector_shuffle mask for an movs{s|d}, movd
2952 /// operation of specified width.
2953 static SDValue getMOVL(SelectionDAG &DAG, DebugLoc dl, MVT VT, SDValue V1,
2954                        SDValue V2) {
2955   unsigned NumElems = VT.getVectorNumElements();
2956   SmallVector<int, 8> Mask;
2957   Mask.push_back(NumElems);
2958   for (unsigned i = 1; i != NumElems; ++i)
2959     Mask.push_back(i);
2960   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
2961 }
2962
2963 /// getUnpackl - Returns a vector_shuffle node for an unpackl operation.
2964 static SDValue getUnpackl(SelectionDAG &DAG, DebugLoc dl, MVT VT, SDValue V1,
2965                           SDValue V2) {
2966   unsigned NumElems = VT.getVectorNumElements();
2967   SmallVector<int, 8> Mask;
2968   for (unsigned i = 0, e = NumElems/2; i != e; ++i) {
2969     Mask.push_back(i);
2970     Mask.push_back(i + NumElems);
2971   }
2972   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
2973 }
2974
2975 /// getUnpackhMask - Returns a vector_shuffle node for an unpackh operation.
2976 static SDValue getUnpackh(SelectionDAG &DAG, DebugLoc dl, MVT VT, SDValue V1,
2977                           SDValue V2) {
2978   unsigned NumElems = VT.getVectorNumElements();
2979   unsigned Half = NumElems/2;
2980   SmallVector<int, 8> Mask;
2981   for (unsigned i = 0; i != Half; ++i) {
2982     Mask.push_back(i + Half);
2983     Mask.push_back(i + NumElems + Half);
2984   }
2985   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
2986 }
2987
2988 /// PromoteSplat - Promote a splat of v4f32, v8i16 or v16i8 to v4i32.
2989 static SDValue PromoteSplat(ShuffleVectorSDNode *SV, SelectionDAG &DAG, 
2990                             bool HasSSE2) {
2991   if (SV->getValueType(0).getVectorNumElements() <= 4)
2992     return SDValue(SV, 0);
2993   
2994   MVT PVT = MVT::v4f32;
2995   MVT VT = SV->getValueType(0);
2996   DebugLoc dl = SV->getDebugLoc();
2997   SDValue V1 = SV->getOperand(0);
2998   int NumElems = VT.getVectorNumElements();
2999   int EltNo = SV->getSplatIndex();
3000
3001   // unpack elements to the correct location
3002   while (NumElems > 4) {
3003     if (EltNo < NumElems/2) {
3004       V1 = getUnpackl(DAG, dl, VT, V1, V1);
3005     } else {
3006       V1 = getUnpackh(DAG, dl, VT, V1, V1);
3007       EltNo -= NumElems/2;
3008     }
3009     NumElems >>= 1;
3010   }
3011   
3012   // Perform the splat.
3013   int SplatMask[4] = { EltNo, EltNo, EltNo, EltNo };
3014   V1 = DAG.getNode(ISD::BIT_CONVERT, dl, PVT, V1);
3015   V1 = DAG.getVectorShuffle(PVT, dl, V1, DAG.getUNDEF(PVT), &SplatMask[0]);
3016   return DAG.getNode(ISD::BIT_CONVERT, dl, VT, V1);
3017 }
3018
3019 /// getShuffleVectorZeroOrUndef - Return a vector_shuffle of the specified
3020 /// vector of zero or undef vector.  This produces a shuffle where the low
3021 /// element of V2 is swizzled into the zero/undef vector, landing at element
3022 /// Idx.  This produces a shuffle mask like 4,1,2,3 (idx=0) or  0,1,2,4 (idx=3).
3023 static SDValue getShuffleVectorZeroOrUndef(SDValue V2, unsigned Idx,
3024                                              bool isZero, bool HasSSE2,
3025                                              SelectionDAG &DAG) {
3026   MVT VT = V2.getValueType();
3027   SDValue V1 = isZero
3028     ? getZeroVector(VT, HasSSE2, DAG, V2.getDebugLoc()) : DAG.getUNDEF(VT);
3029   unsigned NumElems = VT.getVectorNumElements();
3030   SmallVector<int, 16> MaskVec;
3031   for (unsigned i = 0; i != NumElems; ++i)
3032     // If this is the insertion idx, put the low elt of V2 here.
3033     MaskVec.push_back(i == Idx ? NumElems : i);
3034   return DAG.getVectorShuffle(VT, V2.getDebugLoc(), V1, V2, &MaskVec[0]);
3035 }
3036
3037 /// getNumOfConsecutiveZeros - Return the number of elements in a result of
3038 /// a shuffle that is zero.
3039 static
3040 unsigned getNumOfConsecutiveZeros(ShuffleVectorSDNode *SVOp, int NumElems,
3041                                   bool Low, SelectionDAG &DAG) {
3042   unsigned NumZeros = 0;
3043   for (int i = 0; i < NumElems; ++i) {
3044     unsigned Index = Low ? i : NumElems-i-1;
3045     int Idx = SVOp->getMaskElt(Index);
3046     if (Idx < 0) {
3047       ++NumZeros;
3048       continue;
3049     }
3050     SDValue Elt = DAG.getShuffleScalarElt(SVOp, Index);
3051     if (Elt.getNode() && isZeroNode(Elt))
3052       ++NumZeros;
3053     else
3054       break;
3055   }
3056   return NumZeros;
3057 }
3058
3059 /// isVectorShift - Returns true if the shuffle can be implemented as a
3060 /// logical left or right shift of a vector.
3061 /// FIXME: split into pslldqi, psrldqi, palignr variants.
3062 static bool isVectorShift(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
3063                           bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
3064   int NumElems = SVOp->getValueType(0).getVectorNumElements();
3065
3066   isLeft = true;
3067   unsigned NumZeros = getNumOfConsecutiveZeros(SVOp, NumElems, true, DAG);
3068   if (!NumZeros) {
3069     isLeft = false;
3070     NumZeros = getNumOfConsecutiveZeros(SVOp, NumElems, false, DAG);
3071     if (!NumZeros)
3072       return false;
3073   }
3074   bool SeenV1 = false;
3075   bool SeenV2 = false;
3076   for (int i = NumZeros; i < NumElems; ++i) {
3077     int Val = isLeft ? (i - NumZeros) : i;
3078     int Idx = SVOp->getMaskElt(isLeft ? i : (i - NumZeros));
3079     if (Idx < 0)
3080       continue;
3081     if (Idx < NumElems)
3082       SeenV1 = true;
3083     else {
3084       Idx -= NumElems;
3085       SeenV2 = true;
3086     }
3087     if (Idx != Val)
3088       return false;
3089   }
3090   if (SeenV1 && SeenV2)
3091     return false;
3092
3093   ShVal = SeenV1 ? SVOp->getOperand(0) : SVOp->getOperand(1);
3094   ShAmt = NumZeros;
3095   return true;
3096 }
3097
3098
3099 /// LowerBuildVectorv16i8 - Custom lower build_vector of v16i8.
3100 ///
3101 static SDValue LowerBuildVectorv16i8(SDValue Op, unsigned NonZeros,
3102                                        unsigned NumNonZero, unsigned NumZero,
3103                                        SelectionDAG &DAG, TargetLowering &TLI) {
3104   if (NumNonZero > 8)
3105     return SDValue();
3106
3107   DebugLoc dl = Op.getDebugLoc();
3108   SDValue V(0, 0);
3109   bool First = true;
3110   for (unsigned i = 0; i < 16; ++i) {
3111     bool ThisIsNonZero = (NonZeros & (1 << i)) != 0;
3112     if (ThisIsNonZero && First) {
3113       if (NumZero)
3114         V = getZeroVector(MVT::v8i16, true, DAG, dl);
3115       else
3116         V = DAG.getUNDEF(MVT::v8i16);
3117       First = false;
3118     }
3119
3120     if ((i & 1) != 0) {
3121       SDValue ThisElt(0, 0), LastElt(0, 0);
3122       bool LastIsNonZero = (NonZeros & (1 << (i-1))) != 0;
3123       if (LastIsNonZero) {
3124         LastElt = DAG.getNode(ISD::ZERO_EXTEND, dl,
3125                               MVT::i16, Op.getOperand(i-1));
3126       }
3127       if (ThisIsNonZero) {
3128         ThisElt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i16, Op.getOperand(i));
3129         ThisElt = DAG.getNode(ISD::SHL, dl, MVT::i16,
3130                               ThisElt, DAG.getConstant(8, MVT::i8));
3131         if (LastIsNonZero)
3132           ThisElt = DAG.getNode(ISD::OR, dl, MVT::i16, ThisElt, LastElt);
3133       } else
3134         ThisElt = LastElt;
3135
3136       if (ThisElt.getNode())
3137         V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, V, ThisElt,
3138                         DAG.getIntPtrConstant(i/2));
3139     }
3140   }
3141
3142   return DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v16i8, V);
3143 }
3144
3145 /// LowerBuildVectorv8i16 - Custom lower build_vector of v8i16.
3146 ///
3147 static SDValue LowerBuildVectorv8i16(SDValue Op, unsigned NonZeros,
3148                                        unsigned NumNonZero, unsigned NumZero,
3149                                        SelectionDAG &DAG, TargetLowering &TLI) {
3150   if (NumNonZero > 4)
3151     return SDValue();
3152
3153   DebugLoc dl = Op.getDebugLoc();
3154   SDValue V(0, 0);
3155   bool First = true;
3156   for (unsigned i = 0; i < 8; ++i) {
3157     bool isNonZero = (NonZeros & (1 << i)) != 0;
3158     if (isNonZero) {
3159       if (First) {
3160         if (NumZero)
3161           V = getZeroVector(MVT::v8i16, true, DAG, dl);
3162         else
3163           V = DAG.getUNDEF(MVT::v8i16);
3164         First = false;
3165       }
3166       V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl,
3167                       MVT::v8i16, V, Op.getOperand(i),
3168                       DAG.getIntPtrConstant(i));
3169     }
3170   }
3171
3172   return V;
3173 }
3174
3175 /// getVShift - Return a vector logical shift node.
3176 ///
3177 static SDValue getVShift(bool isLeft, MVT VT, SDValue SrcOp,
3178                          unsigned NumBits, SelectionDAG &DAG,
3179                          const TargetLowering &TLI, DebugLoc dl) {
3180   bool isMMX = VT.getSizeInBits() == 64;
3181   MVT ShVT = isMMX ? MVT::v1i64 : MVT::v2i64;
3182   unsigned Opc = isLeft ? X86ISD::VSHL : X86ISD::VSRL;
3183   SrcOp = DAG.getNode(ISD::BIT_CONVERT, dl, ShVT, SrcOp);
3184   return DAG.getNode(ISD::BIT_CONVERT, dl, VT,
3185                      DAG.getNode(Opc, dl, ShVT, SrcOp,
3186                              DAG.getConstant(NumBits, TLI.getShiftAmountTy())));
3187 }
3188
3189 SDValue
3190 X86TargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG) {
3191   DebugLoc dl = Op.getDebugLoc();
3192   // All zero's are handled with pxor, all one's are handled with pcmpeqd.
3193   if (ISD::isBuildVectorAllZeros(Op.getNode())
3194       || ISD::isBuildVectorAllOnes(Op.getNode())) {
3195     // Canonicalize this to either <4 x i32> or <2 x i32> (SSE vs MMX) to
3196     // 1) ensure the zero vectors are CSE'd, and 2) ensure that i64 scalars are
3197     // eliminated on x86-32 hosts.
3198     if (Op.getValueType() == MVT::v4i32 || Op.getValueType() == MVT::v2i32)
3199       return Op;
3200
3201     if (ISD::isBuildVectorAllOnes(Op.getNode()))
3202       return getOnesVector(Op.getValueType(), DAG, dl);
3203     return getZeroVector(Op.getValueType(), Subtarget->hasSSE2(), DAG, dl);
3204   }
3205
3206   MVT VT = Op.getValueType();
3207   MVT EVT = VT.getVectorElementType();
3208   unsigned EVTBits = EVT.getSizeInBits();
3209
3210   unsigned NumElems = Op.getNumOperands();
3211   unsigned NumZero  = 0;
3212   unsigned NumNonZero = 0;
3213   unsigned NonZeros = 0;
3214   bool IsAllConstants = true;
3215   SmallSet<SDValue, 8> Values;
3216   for (unsigned i = 0; i < NumElems; ++i) {
3217     SDValue Elt = Op.getOperand(i);
3218     if (Elt.getOpcode() == ISD::UNDEF)
3219       continue;
3220     Values.insert(Elt);
3221     if (Elt.getOpcode() != ISD::Constant &&
3222         Elt.getOpcode() != ISD::ConstantFP)
3223       IsAllConstants = false;
3224     if (isZeroNode(Elt))
3225       NumZero++;
3226     else {
3227       NonZeros |= (1 << i);
3228       NumNonZero++;
3229     }
3230   }
3231
3232   if (NumNonZero == 0) {
3233     // All undef vector. Return an UNDEF.  All zero vectors were handled above.
3234     return DAG.getUNDEF(VT);
3235   }
3236
3237   // Special case for single non-zero, non-undef, element.
3238   if (NumNonZero == 1) {
3239     unsigned Idx = CountTrailingZeros_32(NonZeros);
3240     SDValue Item = Op.getOperand(Idx);
3241
3242     // If this is an insertion of an i64 value on x86-32, and if the top bits of
3243     // the value are obviously zero, truncate the value to i32 and do the
3244     // insertion that way.  Only do this if the value is non-constant or if the
3245     // value is a constant being inserted into element 0.  It is cheaper to do
3246     // a constant pool load than it is to do a movd + shuffle.
3247     if (EVT == MVT::i64 && !Subtarget->is64Bit() &&
3248         (!IsAllConstants || Idx == 0)) {
3249       if (DAG.MaskedValueIsZero(Item, APInt::getBitsSet(64, 32, 64))) {
3250         // Handle MMX and SSE both.
3251         MVT VecVT = VT == MVT::v2i64 ? MVT::v4i32 : MVT::v2i32;
3252         unsigned VecElts = VT == MVT::v2i64 ? 4 : 2;
3253
3254         // Truncate the value (which may itself be a constant) to i32, and
3255         // convert it to a vector with movd (S2V+shuffle to zero extend).
3256         Item = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Item);
3257         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VecVT, Item);
3258         Item = getShuffleVectorZeroOrUndef(Item, 0, true,
3259                                            Subtarget->hasSSE2(), DAG);
3260
3261         // Now we have our 32-bit value zero extended in the low element of
3262         // a vector.  If Idx != 0, swizzle it into place.
3263         if (Idx != 0) {
3264           SmallVector<int, 4> Mask;
3265           Mask.push_back(Idx);
3266           for (unsigned i = 1; i != VecElts; ++i)
3267             Mask.push_back(i);
3268           Item = DAG.getVectorShuffle(VecVT, dl, Item,
3269                                       DAG.getUNDEF(Item.getValueType()), 
3270                                       &Mask[0]);
3271         }
3272         return DAG.getNode(ISD::BIT_CONVERT, dl, Op.getValueType(), Item);
3273       }
3274     }
3275
3276     // If we have a constant or non-constant insertion into the low element of
3277     // a vector, we can do this with SCALAR_TO_VECTOR + shuffle of zero into
3278     // the rest of the elements.  This will be matched as movd/movq/movss/movsd
3279     // depending on what the source datatype is.
3280     if (Idx == 0) {
3281       if (NumZero == 0) {
3282         return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
3283       } else if (EVT == MVT::i32 || EVT == MVT::f32 || EVT == MVT::f64 ||
3284           (EVT == MVT::i64 && Subtarget->is64Bit())) {
3285         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
3286         // Turn it into a MOVL (i.e. movss, movsd, or movd) to a zero vector.
3287         return getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget->hasSSE2(),
3288                                            DAG);
3289       } else if (EVT == MVT::i16 || EVT == MVT::i8) {
3290         Item = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, Item);
3291         MVT MiddleVT = VT.getSizeInBits() == 64 ? MVT::v2i32 : MVT::v4i32;
3292         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MiddleVT, Item);
3293         Item = getShuffleVectorZeroOrUndef(Item, 0, true,
3294                                            Subtarget->hasSSE2(), DAG);
3295         return DAG.getNode(ISD::BIT_CONVERT, dl, VT, Item);
3296       }
3297     }
3298
3299     // Is it a vector logical left shift?
3300     if (NumElems == 2 && Idx == 1 &&
3301         isZeroNode(Op.getOperand(0)) && !isZeroNode(Op.getOperand(1))) {
3302       unsigned NumBits = VT.getSizeInBits();
3303       return getVShift(true, VT,
3304                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
3305                                    VT, Op.getOperand(1)),
3306                        NumBits/2, DAG, *this, dl);
3307     }
3308
3309     if (IsAllConstants) // Otherwise, it's better to do a constpool load.
3310       return SDValue();
3311
3312     // Otherwise, if this is a vector with i32 or f32 elements, and the element
3313     // is a non-constant being inserted into an element other than the low one,
3314     // we can't use a constant pool load.  Instead, use SCALAR_TO_VECTOR (aka
3315     // movd/movss) to move this into the low element, then shuffle it into
3316     // place.
3317     if (EVTBits == 32) {
3318       Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
3319
3320       // Turn it into a shuffle of zero and zero-extended scalar to vector.
3321       Item = getShuffleVectorZeroOrUndef(Item, 0, NumZero > 0,
3322                                          Subtarget->hasSSE2(), DAG);
3323       SmallVector<int, 8> MaskVec;
3324       for (unsigned i = 0; i < NumElems; i++)
3325         MaskVec.push_back(i == Idx ? 0 : 1);
3326       return DAG.getVectorShuffle(VT, dl, Item, DAG.getUNDEF(VT), &MaskVec[0]);
3327     }
3328   }
3329
3330   // Splat is obviously ok. Let legalizer expand it to a shuffle.
3331   if (Values.size() == 1)
3332     return SDValue();
3333
3334   // A vector full of immediates; various special cases are already
3335   // handled, so this is best done with a single constant-pool load.
3336   if (IsAllConstants)
3337     return SDValue();
3338
3339   // Let legalizer expand 2-wide build_vectors.
3340   if (EVTBits == 64) {
3341     if (NumNonZero == 1) {
3342       // One half is zero or undef.
3343       unsigned Idx = CountTrailingZeros_32(NonZeros);
3344       SDValue V2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT,
3345                                  Op.getOperand(Idx));
3346       return getShuffleVectorZeroOrUndef(V2, Idx, true,
3347                                          Subtarget->hasSSE2(), DAG);
3348     }
3349     return SDValue();
3350   }
3351
3352   // If element VT is < 32 bits, convert it to inserts into a zero vector.
3353   if (EVTBits == 8 && NumElems == 16) {
3354     SDValue V = LowerBuildVectorv16i8(Op, NonZeros,NumNonZero,NumZero, DAG,
3355                                         *this);
3356     if (V.getNode()) return V;
3357   }
3358
3359   if (EVTBits == 16 && NumElems == 8) {
3360     SDValue V = LowerBuildVectorv8i16(Op, NonZeros,NumNonZero,NumZero, DAG,
3361                                         *this);
3362     if (V.getNode()) return V;
3363   }
3364
3365   // If element VT is == 32 bits, turn it into a number of shuffles.
3366   SmallVector<SDValue, 8> V;
3367   V.resize(NumElems);
3368   if (NumElems == 4 && NumZero > 0) {
3369     for (unsigned i = 0; i < 4; ++i) {
3370       bool isZero = !(NonZeros & (1 << i));
3371       if (isZero)
3372         V[i] = getZeroVector(VT, Subtarget->hasSSE2(), DAG, dl);
3373       else
3374         V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
3375     }
3376
3377     for (unsigned i = 0; i < 2; ++i) {
3378       switch ((NonZeros & (0x3 << i*2)) >> (i*2)) {
3379         default: break;
3380         case 0:
3381           V[i] = V[i*2];  // Must be a zero vector.
3382           break;
3383         case 1:
3384           V[i] = getMOVL(DAG, dl, VT, V[i*2+1], V[i*2]);
3385           break;
3386         case 2:
3387           V[i] = getMOVL(DAG, dl, VT, V[i*2], V[i*2+1]);
3388           break;
3389         case 3:
3390           V[i] = getUnpackl(DAG, dl, VT, V[i*2], V[i*2+1]);
3391           break;
3392       }
3393     }
3394
3395     SmallVector<int, 8> MaskVec;
3396     bool Reverse = (NonZeros & 0x3) == 2;
3397     for (unsigned i = 0; i < 2; ++i)
3398       MaskVec.push_back(Reverse ? 1-i : i);
3399     Reverse = ((NonZeros & (0x3 << 2)) >> 2) == 2;
3400     for (unsigned i = 0; i < 2; ++i)
3401       MaskVec.push_back(Reverse ? 1-i+NumElems : i+NumElems);
3402     return DAG.getVectorShuffle(VT, dl, V[0], V[1], &MaskVec[0]);
3403   }
3404
3405   if (Values.size() > 2) {
3406     // If we have SSE 4.1, Expand into a number of inserts unless the number of
3407     // values to be inserted is equal to the number of elements, in which case
3408     // use the unpack code below in the hopes of matching the consecutive elts
3409     // load merge pattern for shuffles. 
3410     // FIXME: We could probably just check that here directly.
3411     if (Values.size() < NumElems && VT.getSizeInBits() == 128 && 
3412         getSubtarget()->hasSSE41()) {
3413       V[0] = DAG.getUNDEF(VT);
3414       for (unsigned i = 0; i < NumElems; ++i)
3415         if (Op.getOperand(i).getOpcode() != ISD::UNDEF)
3416           V[0] = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, V[0],
3417                              Op.getOperand(i), DAG.getIntPtrConstant(i));
3418       return V[0];
3419     }
3420     // Expand into a number of unpckl*.
3421     // e.g. for v4f32
3422     //   Step 1: unpcklps 0, 2 ==> X: <?, ?, 2, 0>
3423     //         : unpcklps 1, 3 ==> Y: <?, ?, 3, 1>
3424     //   Step 2: unpcklps X, Y ==>    <3, 2, 1, 0>
3425     for (unsigned i = 0; i < NumElems; ++i)
3426       V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
3427     NumElems >>= 1;
3428     while (NumElems != 0) {
3429       for (unsigned i = 0; i < NumElems; ++i)
3430         V[i] = getUnpackl(DAG, dl, VT, V[i], V[i + NumElems]);
3431       NumElems >>= 1;
3432     }
3433     return V[0];
3434   }
3435
3436   return SDValue();
3437 }
3438
3439 // v8i16 shuffles - Prefer shuffles in the following order:
3440 // 1. [all]   pshuflw, pshufhw, optional move
3441 // 2. [ssse3] 1 x pshufb
3442 // 3. [ssse3] 2 x pshufb + 1 x por
3443 // 4. [all]   mov + pshuflw + pshufhw + N x (pextrw + pinsrw)
3444 static
3445 SDValue LowerVECTOR_SHUFFLEv8i16(ShuffleVectorSDNode *SVOp,
3446                                  SelectionDAG &DAG, X86TargetLowering &TLI) {
3447   SDValue V1 = SVOp->getOperand(0);
3448   SDValue V2 = SVOp->getOperand(1);
3449   DebugLoc dl = SVOp->getDebugLoc();
3450   SmallVector<int, 8> MaskVals;
3451
3452   // Determine if more than 1 of the words in each of the low and high quadwords
3453   // of the result come from the same quadword of one of the two inputs.  Undef
3454   // mask values count as coming from any quadword, for better codegen.
3455   SmallVector<unsigned, 4> LoQuad(4);
3456   SmallVector<unsigned, 4> HiQuad(4);
3457   BitVector InputQuads(4);
3458   for (unsigned i = 0; i < 8; ++i) {
3459     SmallVectorImpl<unsigned> &Quad = i < 4 ? LoQuad : HiQuad;
3460     int EltIdx = SVOp->getMaskElt(i);
3461     MaskVals.push_back(EltIdx);
3462     if (EltIdx < 0) {
3463       ++Quad[0];
3464       ++Quad[1];
3465       ++Quad[2];
3466       ++Quad[3];
3467       continue;
3468     }
3469     ++Quad[EltIdx / 4];
3470     InputQuads.set(EltIdx / 4);
3471   }
3472
3473   int BestLoQuad = -1;
3474   unsigned MaxQuad = 1;
3475   for (unsigned i = 0; i < 4; ++i) {
3476     if (LoQuad[i] > MaxQuad) {
3477       BestLoQuad = i;
3478       MaxQuad = LoQuad[i];
3479     }
3480   }
3481
3482   int BestHiQuad = -1;
3483   MaxQuad = 1;
3484   for (unsigned i = 0; i < 4; ++i) {
3485     if (HiQuad[i] > MaxQuad) {
3486       BestHiQuad = i;
3487       MaxQuad = HiQuad[i];
3488     }
3489   }
3490
3491   // For SSSE3, If all 8 words of the result come from only 1 quadword of each
3492   // of the two input vectors, shuffle them into one input vector so only a 
3493   // single pshufb instruction is necessary. If There are more than 2 input
3494   // quads, disable the next transformation since it does not help SSSE3.
3495   bool V1Used = InputQuads[0] || InputQuads[1];
3496   bool V2Used = InputQuads[2] || InputQuads[3];
3497   if (TLI.getSubtarget()->hasSSSE3()) {
3498     if (InputQuads.count() == 2 && V1Used && V2Used) {
3499       BestLoQuad = InputQuads.find_first();
3500       BestHiQuad = InputQuads.find_next(BestLoQuad);
3501     }
3502     if (InputQuads.count() > 2) {
3503       BestLoQuad = -1;
3504       BestHiQuad = -1;
3505     }
3506   }
3507
3508   // If BestLoQuad or BestHiQuad are set, shuffle the quads together and update
3509   // the shuffle mask.  If a quad is scored as -1, that means that it contains
3510   // words from all 4 input quadwords.
3511   SDValue NewV;
3512   if (BestLoQuad >= 0 || BestHiQuad >= 0) {
3513     SmallVector<int, 8> MaskV;
3514     MaskV.push_back(BestLoQuad < 0 ? 0 : BestLoQuad);
3515     MaskV.push_back(BestHiQuad < 0 ? 1 : BestHiQuad);
3516     NewV = DAG.getVectorShuffle(MVT::v2i64, dl, 
3517                   DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v2i64, V1),
3518                   DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v2i64, V2), &MaskV[0]);
3519     NewV = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v8i16, NewV);
3520
3521     // Rewrite the MaskVals and assign NewV to V1 if NewV now contains all the
3522     // source words for the shuffle, to aid later transformations.
3523     bool AllWordsInNewV = true;
3524     bool InOrder[2] = { true, true };
3525     for (unsigned i = 0; i != 8; ++i) {
3526       int idx = MaskVals[i];
3527       if (idx != (int)i)
3528         InOrder[i/4] = false;
3529       if (idx < 0 || (idx/4) == BestLoQuad || (idx/4) == BestHiQuad)
3530         continue;
3531       AllWordsInNewV = false;
3532       break;
3533     }
3534
3535     bool pshuflw = AllWordsInNewV, pshufhw = AllWordsInNewV;
3536     if (AllWordsInNewV) {
3537       for (int i = 0; i != 8; ++i) {
3538         int idx = MaskVals[i];
3539         if (idx < 0)
3540           continue;
3541         idx = MaskVals[i] = (idx / 4) == BestLoQuad ? (idx & 3) : (idx & 3) + 4; 
3542         if ((idx != i) && idx < 4)
3543           pshufhw = false;
3544         if ((idx != i) && idx > 3)
3545           pshuflw = false;
3546       }
3547       V1 = NewV;
3548       V2Used = false;
3549       BestLoQuad = 0;
3550       BestHiQuad = 1;
3551     }
3552
3553     // If we've eliminated the use of V2, and the new mask is a pshuflw or
3554     // pshufhw, that's as cheap as it gets.  Return the new shuffle.
3555     if ((pshufhw && InOrder[0]) || (pshuflw && InOrder[1])) {
3556       return DAG.getVectorShuffle(MVT::v8i16, dl, NewV, 
3557                                   DAG.getUNDEF(MVT::v8i16), &MaskVals[0]);
3558     }
3559   }
3560   
3561   // If we have SSSE3, and all words of the result are from 1 input vector,
3562   // case 2 is generated, otherwise case 3 is generated.  If no SSSE3
3563   // is present, fall back to case 4.
3564   if (TLI.getSubtarget()->hasSSSE3()) {
3565     SmallVector<SDValue,16> pshufbMask;
3566     
3567     // If we have elements from both input vectors, set the high bit of the
3568     // shuffle mask element to zero out elements that come from V2 in the V1 
3569     // mask, and elements that come from V1 in the V2 mask, so that the two
3570     // results can be OR'd together.
3571     bool TwoInputs = V1Used && V2Used;
3572     for (unsigned i = 0; i != 8; ++i) {
3573       int EltIdx = MaskVals[i] * 2;
3574       if (TwoInputs && (EltIdx >= 16)) {
3575         pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
3576         pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
3577         continue;
3578       }
3579       pshufbMask.push_back(DAG.getConstant(EltIdx,   MVT::i8));
3580       pshufbMask.push_back(DAG.getConstant(EltIdx+1, MVT::i8));
3581     }
3582     V1 = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v16i8, V1);
3583     V1 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V1, 
3584                      DAG.getNode(ISD::BUILD_VECTOR, dl,
3585                                  MVT::v16i8, &pshufbMask[0], 16));
3586     if (!TwoInputs)
3587       return DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v8i16, V1);
3588     
3589     // Calculate the shuffle mask for the second input, shuffle it, and
3590     // OR it with the first shuffled input.
3591     pshufbMask.clear();
3592     for (unsigned i = 0; i != 8; ++i) {
3593       int EltIdx = MaskVals[i] * 2;
3594       if (EltIdx < 16) {
3595         pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
3596         pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
3597         continue;
3598       }
3599       pshufbMask.push_back(DAG.getConstant(EltIdx - 16, MVT::i8));
3600       pshufbMask.push_back(DAG.getConstant(EltIdx - 15, MVT::i8));
3601     }
3602     V2 = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v16i8, V2);
3603     V2 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V2, 
3604                      DAG.getNode(ISD::BUILD_VECTOR, dl,
3605                                  MVT::v16i8, &pshufbMask[0], 16));
3606     V1 = DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2);
3607     return DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v8i16, V1);
3608   }
3609
3610   // If BestLoQuad >= 0, generate a pshuflw to put the low elements in order,
3611   // and update MaskVals with new element order.
3612   BitVector InOrder(8);
3613   if (BestLoQuad >= 0) {
3614     SmallVector<int, 8> MaskV;
3615     for (int i = 0; i != 4; ++i) {
3616       int idx = MaskVals[i];
3617       if (idx < 0) {
3618         MaskV.push_back(-1);
3619         InOrder.set(i);
3620       } else if ((idx / 4) == BestLoQuad) {
3621         MaskV.push_back(idx & 3);
3622         InOrder.set(i);
3623       } else {
3624         MaskV.push_back(-1);
3625       }
3626     }
3627     for (unsigned i = 4; i != 8; ++i)
3628       MaskV.push_back(i);
3629     NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::v8i16),
3630                                 &MaskV[0]);
3631   }
3632   
3633   // If BestHi >= 0, generate a pshufhw to put the high elements in order,
3634   // and update MaskVals with the new element order.
3635   if (BestHiQuad >= 0) {
3636     SmallVector<int, 8> MaskV;
3637     for (unsigned i = 0; i != 4; ++i)
3638       MaskV.push_back(i);
3639     for (unsigned i = 4; i != 8; ++i) {
3640       int idx = MaskVals[i];
3641       if (idx < 0) {
3642         MaskV.push_back(-1);
3643         InOrder.set(i);
3644       } else if ((idx / 4) == BestHiQuad) {
3645         MaskV.push_back((idx & 3) + 4);
3646         InOrder.set(i);
3647       } else {
3648         MaskV.push_back(-1);
3649       }
3650     }
3651     NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::v8i16),
3652                                 &MaskV[0]);
3653   }
3654   
3655   // In case BestHi & BestLo were both -1, which means each quadword has a word
3656   // from each of the four input quadwords, calculate the InOrder bitvector now
3657   // before falling through to the insert/extract cleanup.
3658   if (BestLoQuad == -1 && BestHiQuad == -1) {
3659     NewV = V1;
3660     for (int i = 0; i != 8; ++i)
3661       if (MaskVals[i] < 0 || MaskVals[i] == i)
3662         InOrder.set(i);
3663   }
3664   
3665   // The other elements are put in the right place using pextrw and pinsrw.
3666   for (unsigned i = 0; i != 8; ++i) {
3667     if (InOrder[i])
3668       continue;
3669     int EltIdx = MaskVals[i];
3670     if (EltIdx < 0)
3671       continue;
3672     SDValue ExtOp = (EltIdx < 8)
3673     ? DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V1,
3674                   DAG.getIntPtrConstant(EltIdx))
3675     : DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V2,
3676                   DAG.getIntPtrConstant(EltIdx - 8));
3677     NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, ExtOp,
3678                        DAG.getIntPtrConstant(i));
3679   }
3680   return NewV;
3681 }
3682
3683 // v16i8 shuffles - Prefer shuffles in the following order:
3684 // 1. [ssse3] 1 x pshufb
3685 // 2. [ssse3] 2 x pshufb + 1 x por
3686 // 3. [all]   v8i16 shuffle + N x pextrw + rotate + pinsrw
3687 static
3688 SDValue LowerVECTOR_SHUFFLEv16i8(ShuffleVectorSDNode *SVOp,
3689                                  SelectionDAG &DAG, X86TargetLowering &TLI) {
3690   SDValue V1 = SVOp->getOperand(0);
3691   SDValue V2 = SVOp->getOperand(1);
3692   DebugLoc dl = SVOp->getDebugLoc();
3693   SmallVector<int, 16> MaskVals;
3694   SVOp->getMask(MaskVals);
3695   
3696   // If we have SSSE3, case 1 is generated when all result bytes come from
3697   // one of  the inputs.  Otherwise, case 2 is generated.  If no SSSE3 is 
3698   // present, fall back to case 3.
3699   // FIXME: kill V2Only once shuffles are canonizalized by getNode.
3700   bool V1Only = true;
3701   bool V2Only = true;
3702   for (unsigned i = 0; i < 16; ++i) {
3703     int EltIdx = MaskVals[i];
3704     if (EltIdx < 0)
3705       continue;
3706     if (EltIdx < 16)
3707       V2Only = false;
3708     else
3709       V1Only = false;
3710   }
3711   
3712   // If SSSE3, use 1 pshufb instruction per vector with elements in the result.
3713   if (TLI.getSubtarget()->hasSSSE3()) {
3714     SmallVector<SDValue,16> pshufbMask;
3715     
3716     // If all result elements are from one input vector, then only translate
3717     // undef mask values to 0x80 (zero out result) in the pshufb mask. 
3718     //
3719     // Otherwise, we have elements from both input vectors, and must zero out
3720     // elements that come from V2 in the first mask, and V1 in the second mask
3721     // so that we can OR them together.
3722     bool TwoInputs = !(V1Only || V2Only);
3723     for (unsigned i = 0; i != 16; ++i) {
3724       int EltIdx = MaskVals[i];
3725       if (EltIdx < 0 || (TwoInputs && EltIdx >= 16)) {
3726         pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
3727         continue;
3728       }
3729       pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8));
3730     }
3731     // If all the elements are from V2, assign it to V1 and return after
3732     // building the first pshufb.
3733     if (V2Only)
3734       V1 = V2;
3735     V1 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V1,
3736                      DAG.getNode(ISD::BUILD_VECTOR, dl,
3737                                  MVT::v16i8, &pshufbMask[0], 16));
3738     if (!TwoInputs)
3739       return V1;
3740     
3741     // Calculate the shuffle mask for the second input, shuffle it, and
3742     // OR it with the first shuffled input.
3743     pshufbMask.clear();
3744     for (unsigned i = 0; i != 16; ++i) {
3745       int EltIdx = MaskVals[i];
3746       if (EltIdx < 16) {
3747         pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
3748         continue;
3749       }
3750       pshufbMask.push_back(DAG.getConstant(EltIdx - 16, MVT::i8));
3751     }
3752     V2 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V2,
3753                      DAG.getNode(ISD::BUILD_VECTOR, dl,
3754                                  MVT::v16i8, &pshufbMask[0], 16));
3755     return DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2);
3756   }
3757   
3758   // No SSSE3 - Calculate in place words and then fix all out of place words
3759   // With 0-16 extracts & inserts.  Worst case is 16 bytes out of order from
3760   // the 16 different words that comprise the two doublequadword input vectors.
3761   V1 = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v8i16, V1);
3762   V2 = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v8i16, V2);
3763   SDValue NewV = V2Only ? V2 : V1;
3764   for (int i = 0; i != 8; ++i) {
3765     int Elt0 = MaskVals[i*2];
3766     int Elt1 = MaskVals[i*2+1];
3767     
3768     // This word of the result is all undef, skip it.
3769     if (Elt0 < 0 && Elt1 < 0)
3770       continue;
3771     
3772     // This word of the result is already in the correct place, skip it.
3773     if (V1Only && (Elt0 == i*2) && (Elt1 == i*2+1))
3774       continue;
3775     if (V2Only && (Elt0 == i*2+16) && (Elt1 == i*2+17))
3776       continue;
3777     
3778     SDValue Elt0Src = Elt0 < 16 ? V1 : V2;
3779     SDValue Elt1Src = Elt1 < 16 ? V1 : V2;
3780     SDValue InsElt;
3781
3782     // If Elt0 and Elt1 are defined, are consecutive, and can be load
3783     // using a single extract together, load it and store it.
3784     if ((Elt0 >= 0) && ((Elt0 + 1) == Elt1) && ((Elt0 & 1) == 0)) {
3785       InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src,
3786                            DAG.getIntPtrConstant(Elt1 / 2));
3787       NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt,
3788                         DAG.getIntPtrConstant(i));
3789       continue;
3790     }
3791
3792     // If Elt1 is defined, extract it from the appropriate source.  If the
3793     // source byte is not also odd, shift the extracted word left 8 bits
3794     // otherwise clear the bottom 8 bits if we need to do an or.
3795     if (Elt1 >= 0) {
3796       InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src,
3797                            DAG.getIntPtrConstant(Elt1 / 2));
3798       if ((Elt1 & 1) == 0)
3799         InsElt = DAG.getNode(ISD::SHL, dl, MVT::i16, InsElt,
3800                              DAG.getConstant(8, TLI.getShiftAmountTy()));
3801       else if (Elt0 >= 0)
3802         InsElt = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt,
3803                              DAG.getConstant(0xFF00, MVT::i16));
3804     }
3805     // If Elt0 is defined, extract it from the appropriate source.  If the
3806     // source byte is not also even, shift the extracted word right 8 bits. If
3807     // Elt1 was also defined, OR the extracted values together before
3808     // inserting them in the result.
3809     if (Elt0 >= 0) {
3810       SDValue InsElt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16,
3811                                     Elt0Src, DAG.getIntPtrConstant(Elt0 / 2));
3812       if ((Elt0 & 1) != 0)
3813         InsElt0 = DAG.getNode(ISD::SRL, dl, MVT::i16, InsElt0,
3814                               DAG.getConstant(8, TLI.getShiftAmountTy()));
3815       else if (Elt1 >= 0)
3816         InsElt0 = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt0,
3817                              DAG.getConstant(0x00FF, MVT::i16));
3818       InsElt = Elt1 >= 0 ? DAG.getNode(ISD::OR, dl, MVT::i16, InsElt, InsElt0)
3819                          : InsElt0;
3820     }
3821     NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt,
3822                        DAG.getIntPtrConstant(i));
3823   }
3824   return DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v16i8, NewV);
3825 }
3826
3827 /// RewriteAsNarrowerShuffle - Try rewriting v8i16 and v16i8 shuffles as 4 wide
3828 /// ones, or rewriting v4i32 / v2f32 as 2 wide ones if possible. This can be
3829 /// done when every pair / quad of shuffle mask elements point to elements in
3830 /// the right sequence. e.g.
3831 /// vector_shuffle <>, <>, < 3, 4, | 10, 11, | 0, 1, | 14, 15>
3832 static
3833 SDValue RewriteAsNarrowerShuffle(ShuffleVectorSDNode *SVOp,
3834                                  SelectionDAG &DAG,
3835                                  TargetLowering &TLI, DebugLoc dl) {
3836   MVT VT = SVOp->getValueType(0);
3837   SDValue V1 = SVOp->getOperand(0);
3838   SDValue V2 = SVOp->getOperand(1);
3839   unsigned NumElems = VT.getVectorNumElements();
3840   unsigned NewWidth = (NumElems == 4) ? 2 : 4;
3841   MVT MaskVT = MVT::getIntVectorWithNumElements(NewWidth);
3842   MVT MaskEltVT = MaskVT.getVectorElementType();
3843   MVT NewVT = MaskVT;
3844   switch (VT.getSimpleVT()) {
3845   default: assert(false && "Unexpected!");
3846   case MVT::v4f32: NewVT = MVT::v2f64; break;
3847   case MVT::v4i32: NewVT = MVT::v2i64; break;
3848   case MVT::v8i16: NewVT = MVT::v4i32; break;
3849   case MVT::v16i8: NewVT = MVT::v4i32; break;
3850   }
3851
3852   if (NewWidth == 2) {
3853     if (VT.isInteger())
3854       NewVT = MVT::v2i64;
3855     else
3856       NewVT = MVT::v2f64;
3857   }
3858   int Scale = NumElems / NewWidth;
3859   SmallVector<int, 8> MaskVec;
3860   for (unsigned i = 0; i < NumElems; i += Scale) {
3861     int StartIdx = -1;
3862     for (int j = 0; j < Scale; ++j) {
3863       int EltIdx = SVOp->getMaskElt(i+j);
3864       if (EltIdx < 0)
3865         continue;
3866       if (StartIdx == -1)
3867         StartIdx = EltIdx - (EltIdx % Scale);
3868       if (EltIdx != StartIdx + j)
3869         return SDValue();
3870     }
3871     if (StartIdx == -1)
3872       MaskVec.push_back(-1);
3873     else
3874       MaskVec.push_back(StartIdx / Scale);
3875   }
3876
3877   V1 = DAG.getNode(ISD::BIT_CONVERT, dl, NewVT, V1);
3878   V2 = DAG.getNode(ISD::BIT_CONVERT, dl, NewVT, V2);
3879   return DAG.getVectorShuffle(NewVT, dl, V1, V2, &MaskVec[0]);
3880 }
3881
3882 /// getVZextMovL - Return a zero-extending vector move low node.
3883 ///
3884 static SDValue getVZextMovL(MVT VT, MVT OpVT,
3885                             SDValue SrcOp, SelectionDAG &DAG,
3886                             const X86Subtarget *Subtarget, DebugLoc dl) {
3887   if (VT == MVT::v2f64 || VT == MVT::v4f32) {
3888     LoadSDNode *LD = NULL;
3889     if (!isScalarLoadToVector(SrcOp.getNode(), &LD))
3890       LD = dyn_cast<LoadSDNode>(SrcOp);
3891     if (!LD) {
3892       // movssrr and movsdrr do not clear top bits. Try to use movd, movq
3893       // instead.
3894       MVT EVT = (OpVT == MVT::v2f64) ? MVT::i64 : MVT::i32;
3895       if ((EVT != MVT::i64 || Subtarget->is64Bit()) &&
3896           SrcOp.getOpcode() == ISD::SCALAR_TO_VECTOR &&
3897           SrcOp.getOperand(0).getOpcode() == ISD::BIT_CONVERT &&
3898           SrcOp.getOperand(0).getOperand(0).getValueType() == EVT) {
3899         // PR2108
3900         OpVT = (OpVT == MVT::v2f64) ? MVT::v2i64 : MVT::v4i32;
3901         return DAG.getNode(ISD::BIT_CONVERT, dl, VT,
3902                            DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT,
3903                                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
3904                                                    OpVT,
3905                                                    SrcOp.getOperand(0)
3906                                                           .getOperand(0))));
3907       }
3908     }
3909   }
3910
3911   return DAG.getNode(ISD::BIT_CONVERT, dl, VT,
3912                      DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT,
3913                                  DAG.getNode(ISD::BIT_CONVERT, dl,
3914                                              OpVT, SrcOp)));
3915 }
3916
3917 /// LowerVECTOR_SHUFFLE_4wide - Handle all 4 wide cases with a number of
3918 /// shuffles.
3919 static SDValue
3920 LowerVECTOR_SHUFFLE_4wide(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
3921   SDValue V1 = SVOp->getOperand(0);
3922   SDValue V2 = SVOp->getOperand(1);
3923   DebugLoc dl = SVOp->getDebugLoc();
3924   MVT VT = SVOp->getValueType(0);
3925   
3926   SmallVector<std::pair<int, int>, 8> Locs;
3927   Locs.resize(4);
3928   SmallVector<int, 8> Mask1(4U, -1);
3929   SmallVector<int, 8> PermMask;
3930   SVOp->getMask(PermMask);
3931
3932   unsigned NumHi = 0;
3933   unsigned NumLo = 0;
3934   for (unsigned i = 0; i != 4; ++i) {
3935     int Idx = PermMask[i];
3936     if (Idx < 0) {
3937       Locs[i] = std::make_pair(-1, -1);
3938     } else {
3939       assert(Idx < 8 && "Invalid VECTOR_SHUFFLE index!");
3940       if (Idx < 4) {
3941         Locs[i] = std::make_pair(0, NumLo);
3942         Mask1[NumLo] = Idx;
3943         NumLo++;
3944       } else {
3945         Locs[i] = std::make_pair(1, NumHi);
3946         if (2+NumHi < 4)
3947           Mask1[2+NumHi] = Idx;
3948         NumHi++;
3949       }
3950     }
3951   }
3952
3953   if (NumLo <= 2 && NumHi <= 2) {
3954     // If no more than two elements come from either vector. This can be
3955     // implemented with two shuffles. First shuffle gather the elements.
3956     // The second shuffle, which takes the first shuffle as both of its
3957     // vector operands, put the elements into the right order.
3958     V1 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
3959
3960     SmallVector<int, 8> Mask2(4U, -1);
3961     
3962     for (unsigned i = 0; i != 4; ++i) {
3963       if (Locs[i].first == -1)
3964         continue;
3965       else {
3966         unsigned Idx = (i < 2) ? 0 : 4;
3967         Idx += Locs[i].first * 2 + Locs[i].second;
3968         Mask2[i] = Idx;
3969       }
3970     }
3971
3972     return DAG.getVectorShuffle(VT, dl, V1, V1, &Mask2[0]);
3973   } else if (NumLo == 3 || NumHi == 3) {
3974     // Otherwise, we must have three elements from one vector, call it X, and
3975     // one element from the other, call it Y.  First, use a shufps to build an
3976     // intermediate vector with the one element from Y and the element from X
3977     // that will be in the same half in the final destination (the indexes don't
3978     // matter). Then, use a shufps to build the final vector, taking the half
3979     // containing the element from Y from the intermediate, and the other half
3980     // from X.
3981     if (NumHi == 3) {
3982       // Normalize it so the 3 elements come from V1.
3983       CommuteVectorShuffleMask(PermMask, VT);
3984       std::swap(V1, V2);
3985     }
3986
3987     // Find the element from V2.
3988     unsigned HiIndex;
3989     for (HiIndex = 0; HiIndex < 3; ++HiIndex) {
3990       int Val = PermMask[HiIndex];
3991       if (Val < 0)
3992         continue;
3993       if (Val >= 4)
3994         break;
3995     }
3996
3997     Mask1[0] = PermMask[HiIndex];
3998     Mask1[1] = -1;
3999     Mask1[2] = PermMask[HiIndex^1];
4000     Mask1[3] = -1;
4001     V2 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
4002
4003     if (HiIndex >= 2) {
4004       Mask1[0] = PermMask[0];
4005       Mask1[1] = PermMask[1];
4006       Mask1[2] = HiIndex & 1 ? 6 : 4;
4007       Mask1[3] = HiIndex & 1 ? 4 : 6;
4008       return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
4009     } else {
4010       Mask1[0] = HiIndex & 1 ? 2 : 0;
4011       Mask1[1] = HiIndex & 1 ? 0 : 2;
4012       Mask1[2] = PermMask[2];
4013       Mask1[3] = PermMask[3];
4014       if (Mask1[2] >= 0)
4015         Mask1[2] += 4;
4016       if (Mask1[3] >= 0)
4017         Mask1[3] += 4;
4018       return DAG.getVectorShuffle(VT, dl, V2, V1, &Mask1[0]);
4019     }
4020   }
4021
4022   // Break it into (shuffle shuffle_hi, shuffle_lo).
4023   Locs.clear();
4024   SmallVector<int,8> LoMask(4U, -1);
4025   SmallVector<int,8> HiMask(4U, -1);
4026
4027   SmallVector<int,8> *MaskPtr = &LoMask;
4028   unsigned MaskIdx = 0;
4029   unsigned LoIdx = 0;
4030   unsigned HiIdx = 2;
4031   for (unsigned i = 0; i != 4; ++i) {
4032     if (i == 2) {
4033       MaskPtr = &HiMask;
4034       MaskIdx = 1;
4035       LoIdx = 0;
4036       HiIdx = 2;
4037     }
4038     int Idx = PermMask[i];
4039     if (Idx < 0) {
4040       Locs[i] = std::make_pair(-1, -1);
4041     } else if (Idx < 4) {
4042       Locs[i] = std::make_pair(MaskIdx, LoIdx);
4043       (*MaskPtr)[LoIdx] = Idx;
4044       LoIdx++;
4045     } else {
4046       Locs[i] = std::make_pair(MaskIdx, HiIdx);
4047       (*MaskPtr)[HiIdx] = Idx;
4048       HiIdx++;
4049     }
4050   }
4051
4052   SDValue LoShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &LoMask[0]);
4053   SDValue HiShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &HiMask[0]);
4054   SmallVector<int, 8> MaskOps;
4055   for (unsigned i = 0; i != 4; ++i) {
4056     if (Locs[i].first == -1) {
4057       MaskOps.push_back(-1);
4058     } else {
4059       unsigned Idx = Locs[i].first * 4 + Locs[i].second;
4060       MaskOps.push_back(Idx);
4061     }
4062   }
4063   return DAG.getVectorShuffle(VT, dl, LoShuffle, HiShuffle, &MaskOps[0]);
4064 }
4065
4066 SDValue
4067 X86TargetLowering::LowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG) {
4068   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
4069   SDValue V1 = Op.getOperand(0);
4070   SDValue V2 = Op.getOperand(1);
4071   MVT VT = Op.getValueType();
4072   DebugLoc dl = Op.getDebugLoc();
4073   unsigned NumElems = VT.getVectorNumElements();
4074   bool isMMX = VT.getSizeInBits() == 64;
4075   bool V1IsUndef = V1.getOpcode() == ISD::UNDEF;
4076   bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
4077   bool V1IsSplat = false;
4078   bool V2IsSplat = false;
4079
4080   if (isZeroShuffle(SVOp))
4081     return getZeroVector(VT, Subtarget->hasSSE2(), DAG, dl);
4082
4083   // Promote splats to v4f32.
4084   if (SVOp->isSplat()) {
4085     if (isMMX || NumElems < 4) 
4086       return Op;
4087     return PromoteSplat(SVOp, DAG, Subtarget->hasSSE2());
4088   }
4089
4090   // If the shuffle can be profitably rewritten as a narrower shuffle, then
4091   // do it!
4092   if (VT == MVT::v8i16 || VT == MVT::v16i8) {
4093     SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG, *this, dl);
4094     if (NewOp.getNode())
4095       return DAG.getNode(ISD::BIT_CONVERT, dl, VT,
4096                          LowerVECTOR_SHUFFLE(NewOp, DAG));
4097   } else if ((VT == MVT::v4i32 || (VT == MVT::v4f32 && Subtarget->hasSSE2()))) {
4098     // FIXME: Figure out a cleaner way to do this.
4099     // Try to make use of movq to zero out the top part.
4100     if (ISD::isBuildVectorAllZeros(V2.getNode())) {
4101       SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG, *this, dl);
4102       if (NewOp.getNode()) {
4103         if (isCommutedMOVL(cast<ShuffleVectorSDNode>(NewOp), true, false))
4104           return getVZextMovL(VT, NewOp.getValueType(), NewOp.getOperand(0),
4105                               DAG, Subtarget, dl);
4106       }
4107     } else if (ISD::isBuildVectorAllZeros(V1.getNode())) {
4108       SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG, *this, dl);
4109       if (NewOp.getNode() && X86::isMOVLMask(cast<ShuffleVectorSDNode>(NewOp)))
4110         return getVZextMovL(VT, NewOp.getValueType(), NewOp.getOperand(1),
4111                             DAG, Subtarget, dl);
4112     }
4113   }
4114   
4115   if (X86::isPSHUFDMask(SVOp))
4116     return Op;
4117   
4118   // Check if this can be converted into a logical shift.
4119   bool isLeft = false;
4120   unsigned ShAmt = 0;
4121   SDValue ShVal;
4122   bool isShift = getSubtarget()->hasSSE2() &&
4123   isVectorShift(SVOp, DAG, isLeft, ShVal, ShAmt);
4124   if (isShift && ShVal.hasOneUse()) {
4125     // If the shifted value has multiple uses, it may be cheaper to use
4126     // v_set0 + movlhps or movhlps, etc.
4127     MVT EVT = VT.getVectorElementType();
4128     ShAmt *= EVT.getSizeInBits();
4129     return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
4130   }
4131   
4132   if (X86::isMOVLMask(SVOp)) {
4133     if (V1IsUndef)
4134       return V2;
4135     if (ISD::isBuildVectorAllZeros(V1.getNode()))
4136       return getVZextMovL(VT, VT, V2, DAG, Subtarget, dl);
4137     if (!isMMX)
4138       return Op;
4139   }
4140   
4141   // FIXME: fold these into legal mask.
4142   if (!isMMX && (X86::isMOVSHDUPMask(SVOp) ||
4143                  X86::isMOVSLDUPMask(SVOp) ||
4144                  X86::isMOVHLPSMask(SVOp) ||
4145                  X86::isMOVHPMask(SVOp) ||
4146                  X86::isMOVLPMask(SVOp)))
4147     return Op;
4148
4149   if (ShouldXformToMOVHLPS(SVOp) ||
4150       ShouldXformToMOVLP(V1.getNode(), V2.getNode(), SVOp))
4151     return CommuteVectorShuffle(SVOp, DAG);
4152
4153   if (isShift) {
4154     // No better options. Use a vshl / vsrl.
4155     MVT EVT = VT.getVectorElementType();
4156     ShAmt *= EVT.getSizeInBits();
4157     return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
4158   }
4159   
4160   bool Commuted = false;
4161   // FIXME: This should also accept a bitcast of a splat?  Be careful, not
4162   // 1,1,1,1 -> v8i16 though.
4163   V1IsSplat = isSplatVector(V1.getNode());
4164   V2IsSplat = isSplatVector(V2.getNode());
4165
4166   // Canonicalize the splat or undef, if present, to be on the RHS.
4167   if ((V1IsSplat || V1IsUndef) && !(V2IsSplat || V2IsUndef)) {
4168     Op = CommuteVectorShuffle(SVOp, DAG);
4169     SVOp = cast<ShuffleVectorSDNode>(Op);
4170     V1 = SVOp->getOperand(0);
4171     V2 = SVOp->getOperand(1);
4172     std::swap(V1IsSplat, V2IsSplat);
4173     std::swap(V1IsUndef, V2IsUndef);
4174     Commuted = true;
4175   }
4176
4177   if (isCommutedMOVL(SVOp, V2IsSplat, V2IsUndef)) {
4178     // Shuffling low element of v1 into undef, just return v1.
4179     if (V2IsUndef) 
4180       return V1;
4181     // If V2 is a splat, the mask may be malformed such as <4,3,3,3>, which
4182     // the instruction selector will not match, so get a canonical MOVL with
4183     // swapped operands to undo the commute.
4184     return getMOVL(DAG, dl, VT, V2, V1);
4185   }
4186
4187   if (X86::isUNPCKL_v_undef_Mask(SVOp) ||
4188       X86::isUNPCKH_v_undef_Mask(SVOp) ||
4189       X86::isUNPCKLMask(SVOp) ||
4190       X86::isUNPCKHMask(SVOp))
4191     return Op;
4192
4193   if (V2IsSplat) {
4194     // Normalize mask so all entries that point to V2 points to its first
4195     // element then try to match unpck{h|l} again. If match, return a
4196     // new vector_shuffle with the corrected mask.
4197     SDValue NewMask = NormalizeMask(SVOp, DAG);
4198     ShuffleVectorSDNode *NSVOp = cast<ShuffleVectorSDNode>(NewMask);
4199     if (NSVOp != SVOp) {
4200       if (X86::isUNPCKLMask(NSVOp, true)) {
4201         return NewMask;
4202       } else if (X86::isUNPCKHMask(NSVOp, true)) {
4203         return NewMask;
4204       }
4205     }
4206   }
4207
4208   if (Commuted) {
4209     // Commute is back and try unpck* again.
4210     // FIXME: this seems wrong.
4211     SDValue NewOp = CommuteVectorShuffle(SVOp, DAG);
4212     ShuffleVectorSDNode *NewSVOp = cast<ShuffleVectorSDNode>(NewOp);
4213     if (X86::isUNPCKL_v_undef_Mask(NewSVOp) ||
4214         X86::isUNPCKH_v_undef_Mask(NewSVOp) ||
4215         X86::isUNPCKLMask(NewSVOp) ||
4216         X86::isUNPCKHMask(NewSVOp))
4217       return NewOp;
4218   }
4219
4220   // FIXME: for mmx, bitcast v2i32 to v4i16 for shuffle.
4221
4222   // Normalize the node to match x86 shuffle ops if needed
4223   if (!isMMX && V2.getOpcode() != ISD::UNDEF && isCommutedSHUFP(SVOp))
4224     return CommuteVectorShuffle(SVOp, DAG);
4225
4226   // Check for legal shuffle and return?
4227   SmallVector<int, 16> PermMask;
4228   SVOp->getMask(PermMask);
4229   if (isShuffleMaskLegal(PermMask, VT))
4230     return Op;
4231   
4232   // Handle v8i16 specifically since SSE can do byte extraction and insertion.
4233   if (VT == MVT::v8i16) {
4234     SDValue NewOp = LowerVECTOR_SHUFFLEv8i16(SVOp, DAG, *this);
4235     if (NewOp.getNode())
4236       return NewOp;
4237   }
4238
4239   if (VT == MVT::v16i8) {
4240     SDValue NewOp = LowerVECTOR_SHUFFLEv16i8(SVOp, DAG, *this);
4241     if (NewOp.getNode())
4242       return NewOp;
4243   }
4244   
4245   // Handle all 4 wide cases with a number of shuffles except for MMX.
4246   if (NumElems == 4 && !isMMX)
4247     return LowerVECTOR_SHUFFLE_4wide(SVOp, DAG);
4248
4249   return SDValue();
4250 }
4251
4252 SDValue
4253 X86TargetLowering::LowerEXTRACT_VECTOR_ELT_SSE4(SDValue Op,
4254                                                 SelectionDAG &DAG) {
4255   MVT VT = Op.getValueType();
4256   DebugLoc dl = Op.getDebugLoc();
4257   if (VT.getSizeInBits() == 8) {
4258     SDValue Extract = DAG.getNode(X86ISD::PEXTRB, dl, MVT::i32,
4259                                     Op.getOperand(0), Op.getOperand(1));
4260     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
4261                                     DAG.getValueType(VT));
4262     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
4263   } else if (VT.getSizeInBits() == 16) {
4264     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
4265     // If Idx is 0, it's cheaper to do a move instead of a pextrw.
4266     if (Idx == 0)
4267       return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
4268                          DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
4269                                      DAG.getNode(ISD::BIT_CONVERT, dl,
4270                                                  MVT::v4i32,
4271                                                  Op.getOperand(0)),
4272                                      Op.getOperand(1)));
4273     SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, MVT::i32,
4274                                     Op.getOperand(0), Op.getOperand(1));
4275     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
4276                                     DAG.getValueType(VT));
4277     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
4278   } else if (VT == MVT::f32) {
4279     // EXTRACTPS outputs to a GPR32 register which will require a movd to copy
4280     // the result back to FR32 register. It's only worth matching if the
4281     // result has a single use which is a store or a bitcast to i32.  And in
4282     // the case of a store, it's not worth it if the index is a constant 0,
4283     // because a MOVSSmr can be used instead, which is smaller and faster.
4284     if (!Op.hasOneUse())
4285       return SDValue();
4286     SDNode *User = *Op.getNode()->use_begin();
4287     if ((User->getOpcode() != ISD::STORE ||
4288          (isa<ConstantSDNode>(Op.getOperand(1)) &&
4289           cast<ConstantSDNode>(Op.getOperand(1))->isNullValue())) &&
4290         (User->getOpcode() != ISD::BIT_CONVERT ||
4291          User->getValueType(0) != MVT::i32))
4292       return SDValue();
4293     SDValue Extract = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
4294                                   DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v4i32,
4295                                               Op.getOperand(0)),
4296                                               Op.getOperand(1));
4297     return DAG.getNode(ISD::BIT_CONVERT, dl, MVT::f32, Extract);
4298   } else if (VT == MVT::i32) {
4299     // ExtractPS works with constant index.
4300     if (isa<ConstantSDNode>(Op.getOperand(1)))
4301       return Op;
4302   }
4303   return SDValue();
4304 }
4305
4306
4307 SDValue
4308 X86TargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) {
4309   if (!isa<ConstantSDNode>(Op.getOperand(1)))
4310     return SDValue();
4311
4312   if (Subtarget->hasSSE41()) {
4313     SDValue Res = LowerEXTRACT_VECTOR_ELT_SSE4(Op, DAG);
4314     if (Res.getNode())
4315       return Res;
4316   }
4317
4318   MVT VT = Op.getValueType();
4319   DebugLoc dl = Op.getDebugLoc();
4320   // TODO: handle v16i8.
4321   if (VT.getSizeInBits() == 16) {
4322     SDValue Vec = Op.getOperand(0);
4323     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
4324     if (Idx == 0)
4325       return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
4326                          DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
4327                                      DAG.getNode(ISD::BIT_CONVERT, dl,
4328                                                  MVT::v4i32, Vec),
4329                                      Op.getOperand(1)));
4330     // Transform it so it match pextrw which produces a 32-bit result.
4331     MVT EVT = (MVT::SimpleValueType)(VT.getSimpleVT()+1);
4332     SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, EVT,
4333                                     Op.getOperand(0), Op.getOperand(1));
4334     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, EVT, Extract,
4335                                     DAG.getValueType(VT));
4336     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
4337   } else if (VT.getSizeInBits() == 32) {
4338     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
4339     if (Idx == 0)
4340       return Op;
4341     
4342     // SHUFPS the element to the lowest double word, then movss.
4343     int Mask[4] = { Idx, -1, -1, -1 };
4344     MVT VVT = Op.getOperand(0).getValueType();
4345     SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0), 
4346                                        DAG.getUNDEF(VVT), Mask);
4347     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
4348                        DAG.getIntPtrConstant(0));
4349   } else if (VT.getSizeInBits() == 64) {
4350     // FIXME: .td only matches this for <2 x f64>, not <2 x i64> on 32b
4351     // FIXME: seems like this should be unnecessary if mov{h,l}pd were taught
4352     //        to match extract_elt for f64.
4353     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
4354     if (Idx == 0)
4355       return Op;
4356
4357     // UNPCKHPD the element to the lowest double word, then movsd.
4358     // Note if the lower 64 bits of the result of the UNPCKHPD is then stored
4359     // to a f64mem, the whole operation is folded into a single MOVHPDmr.
4360     int Mask[2] = { 1, -1 };
4361     MVT VVT = Op.getOperand(0).getValueType();
4362     SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0), 
4363                                        DAG.getUNDEF(VVT), Mask);
4364     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
4365                        DAG.getIntPtrConstant(0));
4366   }
4367
4368   return SDValue();
4369 }
4370
4371 SDValue
4372 X86TargetLowering::LowerINSERT_VECTOR_ELT_SSE4(SDValue Op, SelectionDAG &DAG){
4373   MVT VT = Op.getValueType();
4374   MVT EVT = VT.getVectorElementType();
4375   DebugLoc dl = Op.getDebugLoc();
4376
4377   SDValue N0 = Op.getOperand(0);
4378   SDValue N1 = Op.getOperand(1);
4379   SDValue N2 = Op.getOperand(2);
4380
4381   if ((EVT.getSizeInBits() == 8 || EVT.getSizeInBits() == 16) &&
4382       isa<ConstantSDNode>(N2)) {
4383     unsigned Opc = (EVT.getSizeInBits() == 8) ? X86ISD::PINSRB
4384                                               : X86ISD::PINSRW;
4385     // Transform it so it match pinsr{b,w} which expects a GR32 as its second
4386     // argument.
4387     if (N1.getValueType() != MVT::i32)
4388       N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
4389     if (N2.getValueType() != MVT::i32)
4390       N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue());
4391     return DAG.getNode(Opc, dl, VT, N0, N1, N2);
4392   } else if (EVT == MVT::f32 && isa<ConstantSDNode>(N2)) {
4393     // Bits [7:6] of the constant are the source select.  This will always be
4394     //  zero here.  The DAG Combiner may combine an extract_elt index into these
4395     //  bits.  For example (insert (extract, 3), 2) could be matched by putting
4396     //  the '3' into bits [7:6] of X86ISD::INSERTPS.
4397     // Bits [5:4] of the constant are the destination select.  This is the
4398     //  value of the incoming immediate.
4399     // Bits [3:0] of the constant are the zero mask.  The DAG Combiner may
4400     //   combine either bitwise AND or insert of float 0.0 to set these bits.
4401     N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue() << 4);
4402     // Create this as a scalar to vector..
4403     N1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4f32, N1);
4404     return DAG.getNode(X86ISD::INSERTPS, dl, VT, N0, N1, N2);
4405   } else if (EVT == MVT::i32 && isa<ConstantSDNode>(N2)) {
4406     // PINSR* works with constant index.
4407     return Op;
4408   }
4409   return SDValue();
4410 }
4411
4412 SDValue
4413 X86TargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) {
4414   MVT VT = Op.getValueType();
4415   MVT EVT = VT.getVectorElementType();
4416
4417   if (Subtarget->hasSSE41())
4418     return LowerINSERT_VECTOR_ELT_SSE4(Op, DAG);
4419
4420   if (EVT == MVT::i8)
4421     return SDValue();
4422
4423   DebugLoc dl = Op.getDebugLoc();
4424   SDValue N0 = Op.getOperand(0);
4425   SDValue N1 = Op.getOperand(1);
4426   SDValue N2 = Op.getOperand(2);
4427
4428   if (EVT.getSizeInBits() == 16 && isa<ConstantSDNode>(N2)) {
4429     // Transform it so it match pinsrw which expects a 16-bit value in a GR32
4430     // as its second argument.
4431     if (N1.getValueType() != MVT::i32)
4432       N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
4433     if (N2.getValueType() != MVT::i32)
4434       N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue());
4435     return DAG.getNode(X86ISD::PINSRW, dl, VT, N0, N1, N2);
4436   }
4437   return SDValue();
4438 }
4439
4440 SDValue
4441 X86TargetLowering::LowerSCALAR_TO_VECTOR(SDValue Op, SelectionDAG &DAG) {
4442   DebugLoc dl = Op.getDebugLoc();
4443   if (Op.getValueType() == MVT::v2f32)
4444     return DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v2f32,
4445                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i32,
4446                                    DAG.getNode(ISD::BIT_CONVERT, dl, MVT::i32,
4447                                                Op.getOperand(0))));
4448
4449   SDValue AnyExt = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, Op.getOperand(0));
4450   MVT VT = MVT::v2i32;
4451   switch (Op.getValueType().getSimpleVT()) {
4452   default: break;
4453   case MVT::v16i8:
4454   case MVT::v8i16:
4455     VT = MVT::v4i32;
4456     break;
4457   }
4458   return DAG.getNode(ISD::BIT_CONVERT, dl, Op.getValueType(),
4459                      DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, AnyExt));
4460 }
4461
4462 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
4463 // their target countpart wrapped in the X86ISD::Wrapper node. Suppose N is
4464 // one of the above mentioned nodes. It has to be wrapped because otherwise
4465 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
4466 // be used to form addressing mode. These wrapped nodes will be selected
4467 // into MOV32ri.
4468 SDValue
4469 X86TargetLowering::LowerConstantPool(SDValue Op, SelectionDAG &DAG) {
4470   ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
4471   
4472   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
4473   // global base reg.
4474   unsigned char OpFlag = 0;
4475   unsigned WrapperKind = X86ISD::Wrapper;
4476   
4477   if (Subtarget->isPICStyleRIPRel() &&
4478       getTargetMachine().getCodeModel() == CodeModel::Small)
4479     WrapperKind = X86ISD::WrapperRIP;
4480   else if (Subtarget->isPICStyleGOT())
4481     OpFlag = X86II::MO_GOTOFF;
4482   else if (Subtarget->isPICStyleStubPIC())
4483     OpFlag = X86II::MO_PIC_BASE_OFFSET;
4484   
4485   SDValue Result = DAG.getTargetConstantPool(CP->getConstVal(), getPointerTy(),
4486                                              CP->getAlignment(),
4487                                              CP->getOffset(), OpFlag);
4488   DebugLoc DL = CP->getDebugLoc();
4489   Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
4490   // With PIC, the address is actually $g + Offset.
4491   if (OpFlag) {
4492     Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
4493                          DAG.getNode(X86ISD::GlobalBaseReg,
4494                                      DebugLoc::getUnknownLoc(), getPointerTy()),
4495                          Result);
4496   }
4497
4498   return Result;
4499 }
4500
4501 SDValue X86TargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) {
4502   JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
4503   
4504   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
4505   // global base reg.
4506   unsigned char OpFlag = 0;
4507   unsigned WrapperKind = X86ISD::Wrapper;
4508   
4509   if (Subtarget->isPICStyleRIPRel() &&
4510       getTargetMachine().getCodeModel() == CodeModel::Small)
4511     WrapperKind = X86ISD::WrapperRIP;
4512   else if (Subtarget->isPICStyleGOT())
4513     OpFlag = X86II::MO_GOTOFF;
4514   else if (Subtarget->isPICStyleStubPIC())
4515     OpFlag = X86II::MO_PIC_BASE_OFFSET;
4516   
4517   SDValue Result = DAG.getTargetJumpTable(JT->getIndex(), getPointerTy(),
4518                                           OpFlag);
4519   DebugLoc DL = JT->getDebugLoc();
4520   Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
4521   
4522   // With PIC, the address is actually $g + Offset.
4523   if (OpFlag) {
4524     Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
4525                          DAG.getNode(X86ISD::GlobalBaseReg,
4526                                      DebugLoc::getUnknownLoc(), getPointerTy()),
4527                          Result);
4528   }
4529   
4530   return Result;
4531 }
4532
4533 SDValue
4534 X86TargetLowering::LowerExternalSymbol(SDValue Op, SelectionDAG &DAG) {
4535   const char *Sym = cast<ExternalSymbolSDNode>(Op)->getSymbol();
4536   
4537   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
4538   // global base reg.
4539   unsigned char OpFlag = 0;
4540   unsigned WrapperKind = X86ISD::Wrapper;
4541   if (Subtarget->isPICStyleRIPRel() &&
4542       getTargetMachine().getCodeModel() == CodeModel::Small)
4543     WrapperKind = X86ISD::WrapperRIP;
4544   else if (Subtarget->isPICStyleGOT())
4545     OpFlag = X86II::MO_GOTOFF;
4546   else if (Subtarget->isPICStyleStubPIC())
4547     OpFlag = X86II::MO_PIC_BASE_OFFSET;
4548   
4549   SDValue Result = DAG.getTargetExternalSymbol(Sym, getPointerTy(), OpFlag);
4550   
4551   DebugLoc DL = Op.getDebugLoc();
4552   Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
4553   
4554   
4555   // With PIC, the address is actually $g + Offset.
4556   if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
4557       !Subtarget->is64Bit()) {
4558     Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
4559                          DAG.getNode(X86ISD::GlobalBaseReg,
4560                                      DebugLoc::getUnknownLoc(),
4561                                      getPointerTy()),
4562                          Result);
4563   }
4564   
4565   return Result;
4566 }
4567
4568 SDValue
4569 X86TargetLowering::LowerGlobalAddress(const GlobalValue *GV, DebugLoc dl,
4570                                       int64_t Offset,
4571                                       SelectionDAG &DAG) const {
4572   // Create the TargetGlobalAddress node, folding in the constant
4573   // offset if it is legal.
4574   unsigned char OpFlags =
4575     Subtarget->ClassifyGlobalReference(GV, getTargetMachine());
4576   SDValue Result;
4577   if (OpFlags == X86II::MO_NO_FLAG && isInt32(Offset)) {
4578     // A direct static reference to a global.
4579     Result = DAG.getTargetGlobalAddress(GV, getPointerTy(), Offset);
4580     Offset = 0;
4581   } else {
4582     Result = DAG.getTargetGlobalAddress(GV, getPointerTy(), 0, OpFlags);
4583   }
4584   
4585   if (Subtarget->isPICStyleRIPRel() &&
4586       getTargetMachine().getCodeModel() == CodeModel::Small)
4587     Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
4588   else
4589     Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
4590
4591   // With PIC, the address is actually $g + Offset.
4592   if (isGlobalRelativeToPICBase(OpFlags)) {
4593     Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
4594                          DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
4595                          Result);
4596   }
4597
4598   // For globals that require a load from a stub to get the address, emit the
4599   // load.
4600   if (isGlobalStubReference(OpFlags))
4601     Result = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Result,
4602                          PseudoSourceValue::getGOT(), 0);
4603
4604   // If there was a non-zero offset that we didn't fold, create an explicit
4605   // addition for it.
4606   if (Offset != 0)
4607     Result = DAG.getNode(ISD::ADD, dl, getPointerTy(), Result,
4608                          DAG.getConstant(Offset, getPointerTy()));
4609
4610   return Result;
4611 }
4612
4613 SDValue
4614 X86TargetLowering::LowerGlobalAddress(SDValue Op, SelectionDAG &DAG) {
4615   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
4616   int64_t Offset = cast<GlobalAddressSDNode>(Op)->getOffset();
4617   return LowerGlobalAddress(GV, Op.getDebugLoc(), Offset, DAG);
4618 }
4619
4620 static SDValue
4621 GetTLSADDR(SelectionDAG &DAG, SDValue Chain, GlobalAddressSDNode *GA,
4622            SDValue *InFlag, const MVT PtrVT, unsigned ReturnReg,
4623            unsigned char OperandFlags) {
4624   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Flag);
4625   DebugLoc dl = GA->getDebugLoc();
4626   SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(),
4627                                            GA->getValueType(0),
4628                                            GA->getOffset(),
4629                                            OperandFlags);
4630   if (InFlag) {
4631     SDValue Ops[] = { Chain,  TGA, *InFlag };
4632     Chain = DAG.getNode(X86ISD::TLSADDR, dl, NodeTys, Ops, 3);
4633   } else {
4634     SDValue Ops[]  = { Chain, TGA };
4635     Chain = DAG.getNode(X86ISD::TLSADDR, dl, NodeTys, Ops, 2);
4636   }
4637   SDValue Flag = Chain.getValue(1);
4638   return DAG.getCopyFromReg(Chain, dl, ReturnReg, PtrVT, Flag);
4639 }
4640
4641 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 32 bit
4642 static SDValue
4643 LowerToTLSGeneralDynamicModel32(GlobalAddressSDNode *GA, SelectionDAG &DAG,
4644                                 const MVT PtrVT) {
4645   SDValue InFlag;
4646   DebugLoc dl = GA->getDebugLoc();  // ? function entry point might be better
4647   SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
4648                                      DAG.getNode(X86ISD::GlobalBaseReg,
4649                                                  DebugLoc::getUnknownLoc(),
4650                                                  PtrVT), InFlag);
4651   InFlag = Chain.getValue(1);
4652
4653   return GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX, X86II::MO_TLSGD);
4654 }
4655
4656 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 64 bit
4657 static SDValue
4658 LowerToTLSGeneralDynamicModel64(GlobalAddressSDNode *GA, SelectionDAG &DAG,
4659                                 const MVT PtrVT) {
4660   return GetTLSADDR(DAG, DAG.getEntryNode(), GA, NULL, PtrVT,
4661                     X86::RAX, X86II::MO_TLSGD);
4662 }
4663
4664 // Lower ISD::GlobalTLSAddress using the "initial exec" (for no-pic) or
4665 // "local exec" model.
4666 static SDValue LowerToTLSExecModel(GlobalAddressSDNode *GA, SelectionDAG &DAG,
4667                                    const MVT PtrVT, TLSModel::Model model,
4668                                    bool is64Bit) {
4669   DebugLoc dl = GA->getDebugLoc();
4670   // Get the Thread Pointer
4671   SDValue Base = DAG.getNode(X86ISD::SegmentBaseAddress,
4672                              DebugLoc::getUnknownLoc(), PtrVT,
4673                              DAG.getRegister(is64Bit? X86::FS : X86::GS,
4674                                              MVT::i32));
4675
4676   SDValue ThreadPointer = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Base,
4677                                       NULL, 0);
4678
4679   unsigned char OperandFlags = 0;
4680   // Most TLS accesses are not RIP relative, even on x86-64.  One exception is
4681   // initialexec.
4682   unsigned WrapperKind = X86ISD::Wrapper;
4683   if (model == TLSModel::LocalExec) {
4684     OperandFlags = is64Bit ? X86II::MO_TPOFF : X86II::MO_NTPOFF;
4685   } else if (is64Bit) {
4686     assert(model == TLSModel::InitialExec);
4687     OperandFlags = X86II::MO_GOTTPOFF;
4688     WrapperKind = X86ISD::WrapperRIP;
4689   } else {
4690     assert(model == TLSModel::InitialExec);
4691     OperandFlags = X86II::MO_INDNTPOFF;
4692   }
4693   
4694   // emit "addl x@ntpoff,%eax" (local exec) or "addl x@indntpoff,%eax" (initial
4695   // exec)
4696   SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), GA->getValueType(0),
4697                                            GA->getOffset(), OperandFlags);
4698   SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
4699
4700   if (model == TLSModel::InitialExec)
4701     Offset = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Offset,
4702                          PseudoSourceValue::getGOT(), 0);
4703
4704   // The address of the thread local variable is the add of the thread
4705   // pointer with the offset of the variable.
4706   return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
4707 }
4708
4709 SDValue
4710 X86TargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) {
4711   // TODO: implement the "local dynamic" model
4712   // TODO: implement the "initial exec"model for pic executables
4713   assert(Subtarget->isTargetELF() &&
4714          "TLS not implemented for non-ELF targets");
4715   GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
4716   const GlobalValue *GV = GA->getGlobal();
4717   
4718   // If GV is an alias then use the aliasee for determining
4719   // thread-localness.
4720   if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(GV))
4721     GV = GA->resolveAliasedGlobal(false);
4722   
4723   TLSModel::Model model = getTLSModel(GV,
4724                                       getTargetMachine().getRelocationModel());
4725   
4726   switch (model) {
4727   case TLSModel::GeneralDynamic:
4728   case TLSModel::LocalDynamic: // not implemented
4729     if (Subtarget->is64Bit())
4730       return LowerToTLSGeneralDynamicModel64(GA, DAG, getPointerTy());
4731     return LowerToTLSGeneralDynamicModel32(GA, DAG, getPointerTy());
4732     
4733   case TLSModel::InitialExec:
4734   case TLSModel::LocalExec:
4735     return LowerToTLSExecModel(GA, DAG, getPointerTy(), model,
4736                                Subtarget->is64Bit());
4737   }
4738   
4739   llvm_unreachable("Unreachable");
4740   return SDValue();
4741 }
4742
4743
4744 /// LowerShift - Lower SRA_PARTS and friends, which return two i32 values and
4745 /// take a 2 x i32 value to shift plus a shift amount.
4746 SDValue X86TargetLowering::LowerShift(SDValue Op, SelectionDAG &DAG) {
4747   assert(Op.getNumOperands() == 3 && "Not a double-shift!");
4748   MVT VT = Op.getValueType();
4749   unsigned VTBits = VT.getSizeInBits();
4750   DebugLoc dl = Op.getDebugLoc();
4751   bool isSRA = Op.getOpcode() == ISD::SRA_PARTS;
4752   SDValue ShOpLo = Op.getOperand(0);
4753   SDValue ShOpHi = Op.getOperand(1);
4754   SDValue ShAmt  = Op.getOperand(2);
4755   SDValue Tmp1 = isSRA ?
4756     DAG.getNode(ISD::SRA, dl, VT, ShOpHi,
4757                 DAG.getConstant(VTBits - 1, MVT::i8)) :
4758     DAG.getConstant(0, VT);
4759
4760   SDValue Tmp2, Tmp3;
4761   if (Op.getOpcode() == ISD::SHL_PARTS) {
4762     Tmp2 = DAG.getNode(X86ISD::SHLD, dl, VT, ShOpHi, ShOpLo, ShAmt);
4763     Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ShAmt);
4764   } else {
4765     Tmp2 = DAG.getNode(X86ISD::SHRD, dl, VT, ShOpLo, ShOpHi, ShAmt);
4766     Tmp3 = DAG.getNode(isSRA ? ISD::SRA : ISD::SRL, dl, VT, ShOpHi, ShAmt);
4767   }
4768
4769   SDValue AndNode = DAG.getNode(ISD::AND, dl, MVT::i8, ShAmt,
4770                                   DAG.getConstant(VTBits, MVT::i8));
4771   SDValue Cond = DAG.getNode(X86ISD::CMP, dl, VT,
4772                                AndNode, DAG.getConstant(0, MVT::i8));
4773
4774   SDValue Hi, Lo;
4775   SDValue CC = DAG.getConstant(X86::COND_NE, MVT::i8);
4776   SDValue Ops0[4] = { Tmp2, Tmp3, CC, Cond };
4777   SDValue Ops1[4] = { Tmp3, Tmp1, CC, Cond };
4778
4779   if (Op.getOpcode() == ISD::SHL_PARTS) {
4780     Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0, 4);
4781     Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1, 4);
4782   } else {
4783     Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0, 4);
4784     Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1, 4);
4785   }
4786
4787   SDValue Ops[2] = { Lo, Hi };
4788   return DAG.getMergeValues(Ops, 2, dl);
4789 }
4790
4791 SDValue X86TargetLowering::LowerSINT_TO_FP(SDValue Op, SelectionDAG &DAG) {
4792   MVT SrcVT = Op.getOperand(0).getValueType();
4793
4794   if (SrcVT.isVector()) {
4795     if (SrcVT == MVT::v2i32 && Op.getValueType() == MVT::v2f64) {
4796       return Op;
4797     }
4798     return SDValue();
4799   }
4800
4801   assert(SrcVT.getSimpleVT() <= MVT::i64 && SrcVT.getSimpleVT() >= MVT::i16 &&
4802          "Unknown SINT_TO_FP to lower!");
4803
4804   // These are really Legal; return the operand so the caller accepts it as
4805   // Legal.
4806   if (SrcVT == MVT::i32 && isScalarFPTypeInSSEReg(Op.getValueType()))
4807     return Op;
4808   if (SrcVT == MVT::i64 && isScalarFPTypeInSSEReg(Op.getValueType()) &&
4809       Subtarget->is64Bit()) {
4810     return Op;
4811   }
4812
4813   DebugLoc dl = Op.getDebugLoc();
4814   unsigned Size = SrcVT.getSizeInBits()/8;
4815   MachineFunction &MF = DAG.getMachineFunction();
4816   int SSFI = MF.getFrameInfo()->CreateStackObject(Size, Size);
4817   SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
4818   SDValue Chain = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
4819                                StackSlot,
4820                                PseudoSourceValue::getFixedStack(SSFI), 0);
4821   return BuildFILD(Op, SrcVT, Chain, StackSlot, DAG);
4822 }
4823
4824 SDValue X86TargetLowering::BuildFILD(SDValue Op, MVT SrcVT, SDValue Chain,
4825                                      SDValue StackSlot,
4826                                      SelectionDAG &DAG) {
4827   // Build the FILD
4828   DebugLoc dl = Op.getDebugLoc();
4829   SDVTList Tys;
4830   bool useSSE = isScalarFPTypeInSSEReg(Op.getValueType());
4831   if (useSSE)
4832     Tys = DAG.getVTList(MVT::f64, MVT::Other, MVT::Flag);
4833   else
4834     Tys = DAG.getVTList(Op.getValueType(), MVT::Other);
4835   SmallVector<SDValue, 8> Ops;
4836   Ops.push_back(Chain);
4837   Ops.push_back(StackSlot);
4838   Ops.push_back(DAG.getValueType(SrcVT));
4839   SDValue Result = DAG.getNode(useSSE ? X86ISD::FILD_FLAG : X86ISD::FILD, dl,
4840                                  Tys, &Ops[0], Ops.size());
4841
4842   if (useSSE) {
4843     Chain = Result.getValue(1);
4844     SDValue InFlag = Result.getValue(2);
4845
4846     // FIXME: Currently the FST is flagged to the FILD_FLAG. This
4847     // shouldn't be necessary except that RFP cannot be live across
4848     // multiple blocks. When stackifier is fixed, they can be uncoupled.
4849     MachineFunction &MF = DAG.getMachineFunction();
4850     int SSFI = MF.getFrameInfo()->CreateStackObject(8, 8);
4851     SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
4852     Tys = DAG.getVTList(MVT::Other);
4853     SmallVector<SDValue, 8> Ops;
4854     Ops.push_back(Chain);
4855     Ops.push_back(Result);
4856     Ops.push_back(StackSlot);
4857     Ops.push_back(DAG.getValueType(Op.getValueType()));
4858     Ops.push_back(InFlag);
4859     Chain = DAG.getNode(X86ISD::FST, dl, Tys, &Ops[0], Ops.size());
4860     Result = DAG.getLoad(Op.getValueType(), dl, Chain, StackSlot,
4861                          PseudoSourceValue::getFixedStack(SSFI), 0);
4862   }
4863
4864   return Result;
4865 }
4866
4867 // LowerUINT_TO_FP_i64 - 64-bit unsigned integer to double expansion.
4868 SDValue X86TargetLowering::LowerUINT_TO_FP_i64(SDValue Op, SelectionDAG &DAG) {
4869   // This algorithm is not obvious. Here it is in C code, more or less:
4870   /*
4871     double uint64_to_double( uint32_t hi, uint32_t lo ) {
4872       static const __m128i exp = { 0x4330000045300000ULL, 0 };
4873       static const __m128d bias = { 0x1.0p84, 0x1.0p52 };
4874
4875       // Copy ints to xmm registers.
4876       __m128i xh = _mm_cvtsi32_si128( hi );
4877       __m128i xl = _mm_cvtsi32_si128( lo );
4878
4879       // Combine into low half of a single xmm register.
4880       __m128i x = _mm_unpacklo_epi32( xh, xl );
4881       __m128d d;
4882       double sd;
4883
4884       // Merge in appropriate exponents to give the integer bits the right
4885       // magnitude.
4886       x = _mm_unpacklo_epi32( x, exp );
4887
4888       // Subtract away the biases to deal with the IEEE-754 double precision
4889       // implicit 1.
4890       d = _mm_sub_pd( (__m128d) x, bias );
4891
4892       // All conversions up to here are exact. The correctly rounded result is
4893       // calculated using the current rounding mode using the following
4894       // horizontal add.
4895       d = _mm_add_sd( d, _mm_unpackhi_pd( d, d ) );
4896       _mm_store_sd( &sd, d );   // Because we are returning doubles in XMM, this
4897                                 // store doesn't really need to be here (except
4898                                 // maybe to zero the other double)
4899       return sd;
4900     }
4901   */
4902
4903   DebugLoc dl = Op.getDebugLoc();
4904   LLVMContext *Context = DAG.getContext();
4905
4906   // Build some magic constants.
4907   std::vector<Constant*> CV0;
4908   CV0.push_back(ConstantInt::get(*Context, APInt(32, 0x45300000)));
4909   CV0.push_back(ConstantInt::get(*Context, APInt(32, 0x43300000)));
4910   CV0.push_back(ConstantInt::get(*Context, APInt(32, 0)));
4911   CV0.push_back(ConstantInt::get(*Context, APInt(32, 0)));
4912   Constant *C0 = ConstantVector::get(CV0);
4913   SDValue CPIdx0 = DAG.getConstantPool(C0, getPointerTy(), 16);
4914
4915   std::vector<Constant*> CV1;
4916   CV1.push_back(
4917     ConstantFP::get(*Context, APFloat(APInt(64, 0x4530000000000000ULL))));
4918   CV1.push_back(
4919     ConstantFP::get(*Context, APFloat(APInt(64, 0x4330000000000000ULL))));
4920   Constant *C1 = ConstantVector::get(CV1);
4921   SDValue CPIdx1 = DAG.getConstantPool(C1, getPointerTy(), 16);
4922
4923   SDValue XR1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
4924                             DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
4925                                         Op.getOperand(0),
4926                                         DAG.getIntPtrConstant(1)));
4927   SDValue XR2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
4928                             DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
4929                                         Op.getOperand(0),
4930                                         DAG.getIntPtrConstant(0)));
4931   SDValue Unpck1 = getUnpackl(DAG, dl, MVT::v4i32, XR1, XR2);
4932   SDValue CLod0 = DAG.getLoad(MVT::v4i32, dl, DAG.getEntryNode(), CPIdx0,
4933                               PseudoSourceValue::getConstantPool(), 0,
4934                               false, 16);
4935   SDValue Unpck2 = getUnpackl(DAG, dl, MVT::v4i32, Unpck1, CLod0);
4936   SDValue XR2F = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v2f64, Unpck2);
4937   SDValue CLod1 = DAG.getLoad(MVT::v2f64, dl, CLod0.getValue(1), CPIdx1,
4938                               PseudoSourceValue::getConstantPool(), 0,
4939                               false, 16);
4940   SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, XR2F, CLod1);
4941
4942   // Add the halves; easiest way is to swap them into another reg first.
4943   int ShufMask[2] = { 1, -1 };
4944   SDValue Shuf = DAG.getVectorShuffle(MVT::v2f64, dl, Sub,
4945                                       DAG.getUNDEF(MVT::v2f64), ShufMask);
4946   SDValue Add = DAG.getNode(ISD::FADD, dl, MVT::v2f64, Shuf, Sub);
4947   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Add,
4948                      DAG.getIntPtrConstant(0));
4949 }
4950
4951 // LowerUINT_TO_FP_i32 - 32-bit unsigned integer to float expansion.
4952 SDValue X86TargetLowering::LowerUINT_TO_FP_i32(SDValue Op, SelectionDAG &DAG) {
4953   DebugLoc dl = Op.getDebugLoc();
4954   // FP constant to bias correct the final result.
4955   SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL),
4956                                    MVT::f64);
4957
4958   // Load the 32-bit value into an XMM register.
4959   SDValue Load = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
4960                              DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
4961                                          Op.getOperand(0),
4962                                          DAG.getIntPtrConstant(0)));
4963
4964   Load = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
4965                      DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v2f64, Load),
4966                      DAG.getIntPtrConstant(0));
4967
4968   // Or the load with the bias.
4969   SDValue Or = DAG.getNode(ISD::OR, dl, MVT::v2i64,
4970                            DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v2i64,
4971                                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
4972                                                    MVT::v2f64, Load)),
4973                            DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v2i64,
4974                                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
4975                                                    MVT::v2f64, Bias)));
4976   Or = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
4977                    DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v2f64, Or),
4978                    DAG.getIntPtrConstant(0));
4979
4980   // Subtract the bias.
4981   SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::f64, Or, Bias);
4982
4983   // Handle final rounding.
4984   MVT DestVT = Op.getValueType();
4985
4986   if (DestVT.bitsLT(MVT::f64)) {
4987     return DAG.getNode(ISD::FP_ROUND, dl, DestVT, Sub,
4988                        DAG.getIntPtrConstant(0));
4989   } else if (DestVT.bitsGT(MVT::f64)) {
4990     return DAG.getNode(ISD::FP_EXTEND, dl, DestVT, Sub);
4991   }
4992
4993   // Handle final rounding.
4994   return Sub;
4995 }
4996
4997 SDValue X86TargetLowering::LowerUINT_TO_FP(SDValue Op, SelectionDAG &DAG) {
4998   SDValue N0 = Op.getOperand(0);
4999   DebugLoc dl = Op.getDebugLoc();
5000
5001   // Now not UINT_TO_FP is legal (it's marked custom), dag combiner won't
5002   // optimize it to a SINT_TO_FP when the sign bit is known zero. Perform
5003   // the optimization here.
5004   if (DAG.SignBitIsZero(N0))
5005     return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(), N0);
5006
5007   MVT SrcVT = N0.getValueType();
5008   if (SrcVT == MVT::i64) {
5009     // We only handle SSE2 f64 target here; caller can expand the rest.
5010     if (Op.getValueType() != MVT::f64 || !X86ScalarSSEf64)
5011       return SDValue();
5012
5013     return LowerUINT_TO_FP_i64(Op, DAG);
5014   } else if (SrcVT == MVT::i32 && X86ScalarSSEf64) {
5015     return LowerUINT_TO_FP_i32(Op, DAG);
5016   }
5017
5018   assert(SrcVT == MVT::i32 && "Unknown UINT_TO_FP to lower!");
5019
5020   // Make a 64-bit buffer, and use it to build an FILD.
5021   SDValue StackSlot = DAG.CreateStackTemporary(MVT::i64);
5022   SDValue WordOff = DAG.getConstant(4, getPointerTy());
5023   SDValue OffsetSlot = DAG.getNode(ISD::ADD, dl,
5024                                    getPointerTy(), StackSlot, WordOff);
5025   SDValue Store1 = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
5026                                 StackSlot, NULL, 0);
5027   SDValue Store2 = DAG.getStore(Store1, dl, DAG.getConstant(0, MVT::i32),
5028                                 OffsetSlot, NULL, 0);
5029   return BuildFILD(Op, MVT::i64, Store2, StackSlot, DAG);
5030 }
5031
5032 std::pair<SDValue,SDValue> X86TargetLowering::
5033 FP_TO_INTHelper(SDValue Op, SelectionDAG &DAG, bool IsSigned) {
5034   DebugLoc dl = Op.getDebugLoc();
5035
5036   MVT DstTy = Op.getValueType();
5037
5038   if (!IsSigned) {
5039     assert(DstTy == MVT::i32 && "Unexpected FP_TO_UINT");
5040     DstTy = MVT::i64;
5041   }
5042
5043   assert(DstTy.getSimpleVT() <= MVT::i64 &&
5044          DstTy.getSimpleVT() >= MVT::i16 &&
5045          "Unknown FP_TO_SINT to lower!");
5046
5047   // These are really Legal.
5048   if (DstTy == MVT::i32 &&
5049       isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
5050     return std::make_pair(SDValue(), SDValue());
5051   if (Subtarget->is64Bit() &&
5052       DstTy == MVT::i64 &&
5053       isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
5054     return std::make_pair(SDValue(), SDValue());
5055
5056   // We lower FP->sint64 into FISTP64, followed by a load, all to a temporary
5057   // stack slot.
5058   MachineFunction &MF = DAG.getMachineFunction();
5059   unsigned MemSize = DstTy.getSizeInBits()/8;
5060   int SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize);
5061   SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
5062   
5063   unsigned Opc;
5064   switch (DstTy.getSimpleVT()) {
5065   default: llvm_unreachable("Invalid FP_TO_SINT to lower!");
5066   case MVT::i16: Opc = X86ISD::FP_TO_INT16_IN_MEM; break;
5067   case MVT::i32: Opc = X86ISD::FP_TO_INT32_IN_MEM; break;
5068   case MVT::i64: Opc = X86ISD::FP_TO_INT64_IN_MEM; break;
5069   }
5070
5071   SDValue Chain = DAG.getEntryNode();
5072   SDValue Value = Op.getOperand(0);
5073   if (isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType())) {
5074     assert(DstTy == MVT::i64 && "Invalid FP_TO_SINT to lower!");
5075     Chain = DAG.getStore(Chain, dl, Value, StackSlot,
5076                          PseudoSourceValue::getFixedStack(SSFI), 0);
5077     SDVTList Tys = DAG.getVTList(Op.getOperand(0).getValueType(), MVT::Other);
5078     SDValue Ops[] = {
5079       Chain, StackSlot, DAG.getValueType(Op.getOperand(0).getValueType())
5080     };
5081     Value = DAG.getNode(X86ISD::FLD, dl, Tys, Ops, 3);
5082     Chain = Value.getValue(1);
5083     SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize);
5084     StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
5085   }
5086
5087   // Build the FP_TO_INT*_IN_MEM
5088   SDValue Ops[] = { Chain, Value, StackSlot };
5089   SDValue FIST = DAG.getNode(Opc, dl, MVT::Other, Ops, 3);
5090
5091   return std::make_pair(FIST, StackSlot);
5092 }
5093
5094 SDValue X86TargetLowering::LowerFP_TO_SINT(SDValue Op, SelectionDAG &DAG) {
5095   if (Op.getValueType().isVector()) {
5096     if (Op.getValueType() == MVT::v2i32 &&
5097         Op.getOperand(0).getValueType() == MVT::v2f64) {
5098       return Op;
5099     }
5100     return SDValue();
5101   }
5102
5103   std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG, true);
5104   SDValue FIST = Vals.first, StackSlot = Vals.second;
5105   // If FP_TO_INTHelper failed, the node is actually supposed to be Legal.
5106   if (FIST.getNode() == 0) return Op;
5107
5108   // Load the result.
5109   return DAG.getLoad(Op.getValueType(), Op.getDebugLoc(),
5110                      FIST, StackSlot, NULL, 0);
5111 }
5112
5113 SDValue X86TargetLowering::LowerFP_TO_UINT(SDValue Op, SelectionDAG &DAG) {
5114   std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG, false);
5115   SDValue FIST = Vals.first, StackSlot = Vals.second;
5116   assert(FIST.getNode() && "Unexpected failure");
5117
5118   // Load the result.
5119   return DAG.getLoad(Op.getValueType(), Op.getDebugLoc(),
5120                      FIST, StackSlot, NULL, 0);
5121 }
5122
5123 SDValue X86TargetLowering::LowerFABS(SDValue Op, SelectionDAG &DAG) {
5124   LLVMContext *Context = DAG.getContext();
5125   DebugLoc dl = Op.getDebugLoc();
5126   MVT VT = Op.getValueType();
5127   MVT EltVT = VT;
5128   if (VT.isVector())
5129     EltVT = VT.getVectorElementType();
5130   std::vector<Constant*> CV;
5131   if (EltVT == MVT::f64) {
5132     Constant *C = ConstantFP::get(*Context, APFloat(APInt(64, ~(1ULL << 63))));
5133     CV.push_back(C);
5134     CV.push_back(C);
5135   } else {
5136     Constant *C = ConstantFP::get(*Context, APFloat(APInt(32, ~(1U << 31))));
5137     CV.push_back(C);
5138     CV.push_back(C);
5139     CV.push_back(C);
5140     CV.push_back(C);
5141   }
5142   Constant *C = ConstantVector::get(CV);
5143   SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
5144   SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
5145                                PseudoSourceValue::getConstantPool(), 0,
5146                                false, 16);
5147   return DAG.getNode(X86ISD::FAND, dl, VT, Op.getOperand(0), Mask);
5148 }
5149
5150 SDValue X86TargetLowering::LowerFNEG(SDValue Op, SelectionDAG &DAG) {
5151   LLVMContext *Context = DAG.getContext();
5152   DebugLoc dl = Op.getDebugLoc();
5153   MVT VT = Op.getValueType();
5154   MVT EltVT = VT;
5155   unsigned EltNum = 1;
5156   if (VT.isVector()) {
5157     EltVT = VT.getVectorElementType();
5158     EltNum = VT.getVectorNumElements();
5159   }
5160   std::vector<Constant*> CV;
5161   if (EltVT == MVT::f64) {
5162     Constant *C = ConstantFP::get(*Context, APFloat(APInt(64, 1ULL << 63)));
5163     CV.push_back(C);
5164     CV.push_back(C);
5165   } else {
5166     Constant *C = ConstantFP::get(*Context, APFloat(APInt(32, 1U << 31)));
5167     CV.push_back(C);
5168     CV.push_back(C);
5169     CV.push_back(C);
5170     CV.push_back(C);
5171   }
5172   Constant *C = ConstantVector::get(CV);
5173   SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
5174   SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
5175                                PseudoSourceValue::getConstantPool(), 0,
5176                                false, 16);
5177   if (VT.isVector()) {
5178     return DAG.getNode(ISD::BIT_CONVERT, dl, VT,
5179                        DAG.getNode(ISD::XOR, dl, MVT::v2i64,
5180                     DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v2i64,
5181                                 Op.getOperand(0)),
5182                     DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v2i64, Mask)));
5183   } else {
5184     return DAG.getNode(X86ISD::FXOR, dl, VT, Op.getOperand(0), Mask);
5185   }
5186 }
5187
5188 SDValue X86TargetLowering::LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) {
5189   LLVMContext *Context = DAG.getContext();
5190   SDValue Op0 = Op.getOperand(0);
5191   SDValue Op1 = Op.getOperand(1);
5192   DebugLoc dl = Op.getDebugLoc();
5193   MVT VT = Op.getValueType();
5194   MVT SrcVT = Op1.getValueType();
5195
5196   // If second operand is smaller, extend it first.
5197   if (SrcVT.bitsLT(VT)) {
5198     Op1 = DAG.getNode(ISD::FP_EXTEND, dl, VT, Op1);
5199     SrcVT = VT;
5200   }
5201   // And if it is bigger, shrink it first.
5202   if (SrcVT.bitsGT(VT)) {
5203     Op1 = DAG.getNode(ISD::FP_ROUND, dl, VT, Op1, DAG.getIntPtrConstant(1));
5204     SrcVT = VT;
5205   }
5206
5207   // At this point the operands and the result should have the same
5208   // type, and that won't be f80 since that is not custom lowered.
5209
5210   // First get the sign bit of second operand.
5211   std::vector<Constant*> CV;
5212   if (SrcVT == MVT::f64) {
5213     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, 1ULL << 63))));
5214     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, 0))));
5215   } else {
5216     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 1U << 31))));
5217     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
5218     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
5219     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
5220   }
5221   Constant *C = ConstantVector::get(CV);
5222   SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
5223   SDValue Mask1 = DAG.getLoad(SrcVT, dl, DAG.getEntryNode(), CPIdx,
5224                                 PseudoSourceValue::getConstantPool(), 0,
5225                                 false, 16);
5226   SDValue SignBit = DAG.getNode(X86ISD::FAND, dl, SrcVT, Op1, Mask1);
5227
5228   // Shift sign bit right or left if the two operands have different types.
5229   if (SrcVT.bitsGT(VT)) {
5230     // Op0 is MVT::f32, Op1 is MVT::f64.
5231     SignBit = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f64, SignBit);
5232     SignBit = DAG.getNode(X86ISD::FSRL, dl, MVT::v2f64, SignBit,
5233                           DAG.getConstant(32, MVT::i32));
5234     SignBit = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v4f32, SignBit);
5235     SignBit = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f32, SignBit,
5236                           DAG.getIntPtrConstant(0));
5237   }
5238
5239   // Clear first operand sign bit.
5240   CV.clear();
5241   if (VT == MVT::f64) {
5242     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, ~(1ULL << 63)))));
5243     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, 0))));
5244   } else {
5245     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, ~(1U << 31)))));
5246     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
5247     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
5248     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
5249   }
5250   C = ConstantVector::get(CV);
5251   CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
5252   SDValue Mask2 = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
5253                                 PseudoSourceValue::getConstantPool(), 0,
5254                                 false, 16);
5255   SDValue Val = DAG.getNode(X86ISD::FAND, dl, VT, Op0, Mask2);
5256
5257   // Or the value with the sign bit.
5258   return DAG.getNode(X86ISD::FOR, dl, VT, Val, SignBit);
5259 }
5260
5261 /// Emit nodes that will be selected as "test Op0,Op0", or something
5262 /// equivalent.
5263 SDValue X86TargetLowering::EmitTest(SDValue Op, unsigned X86CC,
5264                                     SelectionDAG &DAG) {
5265   DebugLoc dl = Op.getDebugLoc();
5266
5267   // CF and OF aren't always set the way we want. Determine which
5268   // of these we need.
5269   bool NeedCF = false;
5270   bool NeedOF = false;
5271   switch (X86CC) {
5272   case X86::COND_A: case X86::COND_AE:
5273   case X86::COND_B: case X86::COND_BE:
5274     NeedCF = true;
5275     break;
5276   case X86::COND_G: case X86::COND_GE:
5277   case X86::COND_L: case X86::COND_LE:
5278   case X86::COND_O: case X86::COND_NO:
5279     NeedOF = true;
5280     break;
5281   default: break;
5282   }
5283
5284   // See if we can use the EFLAGS value from the operand instead of
5285   // doing a separate TEST. TEST always sets OF and CF to 0, so unless
5286   // we prove that the arithmetic won't overflow, we can't use OF or CF.
5287   if (Op.getResNo() == 0 && !NeedOF && !NeedCF) {
5288     unsigned Opcode = 0;
5289     unsigned NumOperands = 0;
5290     switch (Op.getNode()->getOpcode()) {
5291     case ISD::ADD:
5292       // Due to an isel shortcoming, be conservative if this add is likely to
5293       // be selected as part of a load-modify-store instruction. When the root
5294       // node in a match is a store, isel doesn't know how to remap non-chain
5295       // non-flag uses of other nodes in the match, such as the ADD in this
5296       // case. This leads to the ADD being left around and reselected, with
5297       // the result being two adds in the output.
5298       for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
5299            UE = Op.getNode()->use_end(); UI != UE; ++UI)
5300         if (UI->getOpcode() == ISD::STORE)
5301           goto default_case;
5302       if (ConstantSDNode *C =
5303             dyn_cast<ConstantSDNode>(Op.getNode()->getOperand(1))) {
5304         // An add of one will be selected as an INC.
5305         if (C->getAPIntValue() == 1) {
5306           Opcode = X86ISD::INC;
5307           NumOperands = 1;
5308           break;
5309         }
5310         // An add of negative one (subtract of one) will be selected as a DEC.
5311         if (C->getAPIntValue().isAllOnesValue()) {
5312           Opcode = X86ISD::DEC;
5313           NumOperands = 1;
5314           break;
5315         }
5316       }
5317       // Otherwise use a regular EFLAGS-setting add.
5318       Opcode = X86ISD::ADD;
5319       NumOperands = 2;
5320       break;
5321     case ISD::SUB:
5322       // Due to the ISEL shortcoming noted above, be conservative if this sub is
5323       // likely to be selected as part of a load-modify-store instruction.
5324       for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
5325            UE = Op.getNode()->use_end(); UI != UE; ++UI)
5326         if (UI->getOpcode() == ISD::STORE)
5327           goto default_case;
5328       // Otherwise use a regular EFLAGS-setting sub.
5329       Opcode = X86ISD::SUB;
5330       NumOperands = 2;
5331       break;
5332     case X86ISD::ADD:
5333     case X86ISD::SUB:
5334     case X86ISD::INC:
5335     case X86ISD::DEC:
5336       return SDValue(Op.getNode(), 1);
5337     default:
5338     default_case:
5339       break;
5340     }
5341     if (Opcode != 0) {
5342       SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
5343       SmallVector<SDValue, 4> Ops;
5344       for (unsigned i = 0; i != NumOperands; ++i)
5345         Ops.push_back(Op.getOperand(i));
5346       SDValue New = DAG.getNode(Opcode, dl, VTs, &Ops[0], NumOperands);
5347       DAG.ReplaceAllUsesWith(Op, New);
5348       return SDValue(New.getNode(), 1);
5349     }
5350   }
5351
5352   // Otherwise just emit a CMP with 0, which is the TEST pattern.
5353   return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
5354                      DAG.getConstant(0, Op.getValueType()));
5355 }
5356
5357 /// Emit nodes that will be selected as "cmp Op0,Op1", or something
5358 /// equivalent.
5359 SDValue X86TargetLowering::EmitCmp(SDValue Op0, SDValue Op1, unsigned X86CC,
5360                                    SelectionDAG &DAG) {
5361   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op1))
5362     if (C->getAPIntValue() == 0)
5363       return EmitTest(Op0, X86CC, DAG);
5364
5365   DebugLoc dl = Op0.getDebugLoc();
5366   return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op0, Op1);
5367 }
5368
5369 SDValue X86TargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) {
5370   assert(Op.getValueType() == MVT::i8 && "SetCC type must be 8-bit integer");
5371   SDValue Op0 = Op.getOperand(0);
5372   SDValue Op1 = Op.getOperand(1);
5373   DebugLoc dl = Op.getDebugLoc();
5374   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
5375
5376   // Lower (X & (1 << N)) == 0 to BT(X, N).
5377   // Lower ((X >>u N) & 1) != 0 to BT(X, N).
5378   // Lower ((X >>s N) & 1) != 0 to BT(X, N).
5379   if (Op0.getOpcode() == ISD::AND &&
5380       Op0.hasOneUse() &&
5381       Op1.getOpcode() == ISD::Constant &&
5382       cast<ConstantSDNode>(Op1)->getZExtValue() == 0 &&
5383       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
5384     SDValue LHS, RHS;
5385     if (Op0.getOperand(1).getOpcode() == ISD::SHL) {
5386       if (ConstantSDNode *Op010C =
5387             dyn_cast<ConstantSDNode>(Op0.getOperand(1).getOperand(0)))
5388         if (Op010C->getZExtValue() == 1) {
5389           LHS = Op0.getOperand(0);
5390           RHS = Op0.getOperand(1).getOperand(1);
5391         }
5392     } else if (Op0.getOperand(0).getOpcode() == ISD::SHL) {
5393       if (ConstantSDNode *Op000C =
5394             dyn_cast<ConstantSDNode>(Op0.getOperand(0).getOperand(0)))
5395         if (Op000C->getZExtValue() == 1) {
5396           LHS = Op0.getOperand(1);
5397           RHS = Op0.getOperand(0).getOperand(1);
5398         }
5399     } else if (Op0.getOperand(1).getOpcode() == ISD::Constant) {
5400       ConstantSDNode *AndRHS = cast<ConstantSDNode>(Op0.getOperand(1));
5401       SDValue AndLHS = Op0.getOperand(0);
5402       if (AndRHS->getZExtValue() == 1 && AndLHS.getOpcode() == ISD::SRL) {
5403         LHS = AndLHS.getOperand(0);
5404         RHS = AndLHS.getOperand(1);
5405       }
5406     }
5407
5408     if (LHS.getNode()) {
5409       // If LHS is i8, promote it to i16 with any_extend.  There is no i8 BT
5410       // instruction.  Since the shift amount is in-range-or-undefined, we know
5411       // that doing a bittest on the i16 value is ok.  We extend to i32 because
5412       // the encoding for the i16 version is larger than the i32 version.
5413       if (LHS.getValueType() == MVT::i8)
5414         LHS = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, LHS);
5415
5416       // If the operand types disagree, extend the shift amount to match.  Since
5417       // BT ignores high bits (like shifts) we can use anyextend.
5418       if (LHS.getValueType() != RHS.getValueType())
5419         RHS = DAG.getNode(ISD::ANY_EXTEND, dl, LHS.getValueType(), RHS);
5420
5421       SDValue BT = DAG.getNode(X86ISD::BT, dl, MVT::i32, LHS, RHS);
5422       unsigned Cond = CC == ISD::SETEQ ? X86::COND_AE : X86::COND_B;
5423       return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
5424                          DAG.getConstant(Cond, MVT::i8), BT);
5425     }
5426   }
5427
5428   bool isFP = Op.getOperand(1).getValueType().isFloatingPoint();
5429   unsigned X86CC = TranslateX86CC(CC, isFP, Op0, Op1, DAG);
5430
5431   SDValue Cond = EmitCmp(Op0, Op1, X86CC, DAG);
5432   return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
5433                      DAG.getConstant(X86CC, MVT::i8), Cond);
5434 }
5435
5436 SDValue X86TargetLowering::LowerVSETCC(SDValue Op, SelectionDAG &DAG) {
5437   SDValue Cond;
5438   SDValue Op0 = Op.getOperand(0);
5439   SDValue Op1 = Op.getOperand(1);
5440   SDValue CC = Op.getOperand(2);
5441   MVT VT = Op.getValueType();
5442   ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
5443   bool isFP = Op.getOperand(1).getValueType().isFloatingPoint();
5444   DebugLoc dl = Op.getDebugLoc();
5445
5446   if (isFP) {
5447     unsigned SSECC = 8;
5448     MVT VT0 = Op0.getValueType();
5449     assert(VT0 == MVT::v4f32 || VT0 == MVT::v2f64);
5450     unsigned Opc = VT0 == MVT::v4f32 ? X86ISD::CMPPS : X86ISD::CMPPD;
5451     bool Swap = false;
5452
5453     switch (SetCCOpcode) {
5454     default: break;
5455     case ISD::SETOEQ:
5456     case ISD::SETEQ:  SSECC = 0; break;
5457     case ISD::SETOGT:
5458     case ISD::SETGT: Swap = true; // Fallthrough
5459     case ISD::SETLT:
5460     case ISD::SETOLT: SSECC = 1; break;
5461     case ISD::SETOGE:
5462     case ISD::SETGE: Swap = true; // Fallthrough
5463     case ISD::SETLE:
5464     case ISD::SETOLE: SSECC = 2; break;
5465     case ISD::SETUO:  SSECC = 3; break;
5466     case ISD::SETUNE:
5467     case ISD::SETNE:  SSECC = 4; break;
5468     case ISD::SETULE: Swap = true;
5469     case ISD::SETUGE: SSECC = 5; break;
5470     case ISD::SETULT: Swap = true;
5471     case ISD::SETUGT: SSECC = 6; break;
5472     case ISD::SETO:   SSECC = 7; break;
5473     }
5474     if (Swap)
5475       std::swap(Op0, Op1);
5476
5477     // In the two special cases we can't handle, emit two comparisons.
5478     if (SSECC == 8) {
5479       if (SetCCOpcode == ISD::SETUEQ) {
5480         SDValue UNORD, EQ;
5481         UNORD = DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(3, MVT::i8));
5482         EQ = DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(0, MVT::i8));
5483         return DAG.getNode(ISD::OR, dl, VT, UNORD, EQ);
5484       }
5485       else if (SetCCOpcode == ISD::SETONE) {
5486         SDValue ORD, NEQ;
5487         ORD = DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(7, MVT::i8));
5488         NEQ = DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(4, MVT::i8));
5489         return DAG.getNode(ISD::AND, dl, VT, ORD, NEQ);
5490       }
5491       llvm_unreachable("Illegal FP comparison");
5492     }
5493     // Handle all other FP comparisons here.
5494     return DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(SSECC, MVT::i8));
5495   }
5496
5497   // We are handling one of the integer comparisons here.  Since SSE only has
5498   // GT and EQ comparisons for integer, swapping operands and multiple
5499   // operations may be required for some comparisons.
5500   unsigned Opc = 0, EQOpc = 0, GTOpc = 0;
5501   bool Swap = false, Invert = false, FlipSigns = false;
5502
5503   switch (VT.getSimpleVT()) {
5504   default: break;
5505   case MVT::v8i8:
5506   case MVT::v16i8: EQOpc = X86ISD::PCMPEQB; GTOpc = X86ISD::PCMPGTB; break;
5507   case MVT::v4i16:
5508   case MVT::v8i16: EQOpc = X86ISD::PCMPEQW; GTOpc = X86ISD::PCMPGTW; break;
5509   case MVT::v2i32:
5510   case MVT::v4i32: EQOpc = X86ISD::PCMPEQD; GTOpc = X86ISD::PCMPGTD; break;
5511   case MVT::v2i64: EQOpc = X86ISD::PCMPEQQ; GTOpc = X86ISD::PCMPGTQ; break;
5512   }
5513
5514   switch (SetCCOpcode) {
5515   default: break;
5516   case ISD::SETNE:  Invert = true;
5517   case ISD::SETEQ:  Opc = EQOpc; break;
5518   case ISD::SETLT:  Swap = true;
5519   case ISD::SETGT:  Opc = GTOpc; break;
5520   case ISD::SETGE:  Swap = true;
5521   case ISD::SETLE:  Opc = GTOpc; Invert = true; break;
5522   case ISD::SETULT: Swap = true;
5523   case ISD::SETUGT: Opc = GTOpc; FlipSigns = true; break;
5524   case ISD::SETUGE: Swap = true;
5525   case ISD::SETULE: Opc = GTOpc; FlipSigns = true; Invert = true; break;
5526   }
5527   if (Swap)
5528     std::swap(Op0, Op1);
5529
5530   // Since SSE has no unsigned integer comparisons, we need to flip  the sign
5531   // bits of the inputs before performing those operations.
5532   if (FlipSigns) {
5533     MVT EltVT = VT.getVectorElementType();
5534     SDValue SignBit = DAG.getConstant(APInt::getSignBit(EltVT.getSizeInBits()),
5535                                       EltVT);
5536     std::vector<SDValue> SignBits(VT.getVectorNumElements(), SignBit);
5537     SDValue SignVec = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &SignBits[0],
5538                                     SignBits.size());
5539     Op0 = DAG.getNode(ISD::XOR, dl, VT, Op0, SignVec);
5540     Op1 = DAG.getNode(ISD::XOR, dl, VT, Op1, SignVec);
5541   }
5542
5543   SDValue Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
5544
5545   // If the logical-not of the result is required, perform that now.
5546   if (Invert)
5547     Result = DAG.getNOT(dl, Result, VT);
5548
5549   return Result;
5550 }
5551
5552 // isX86LogicalCmp - Return true if opcode is a X86 logical comparison.
5553 static bool isX86LogicalCmp(SDValue Op) {
5554   unsigned Opc = Op.getNode()->getOpcode();
5555   if (Opc == X86ISD::CMP || Opc == X86ISD::COMI || Opc == X86ISD::UCOMI)
5556     return true;
5557   if (Op.getResNo() == 1 &&
5558       (Opc == X86ISD::ADD ||
5559        Opc == X86ISD::SUB ||
5560        Opc == X86ISD::SMUL ||
5561        Opc == X86ISD::UMUL ||
5562        Opc == X86ISD::INC ||
5563        Opc == X86ISD::DEC))
5564     return true;
5565
5566   return false;
5567 }
5568
5569 SDValue X86TargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) {
5570   bool addTest = true;
5571   SDValue Cond  = Op.getOperand(0);
5572   DebugLoc dl = Op.getDebugLoc();
5573   SDValue CC;
5574
5575   if (Cond.getOpcode() == ISD::SETCC)
5576     Cond = LowerSETCC(Cond, DAG);
5577
5578   // If condition flag is set by a X86ISD::CMP, then use it as the condition
5579   // setting operand in place of the X86ISD::SETCC.
5580   if (Cond.getOpcode() == X86ISD::SETCC) {
5581     CC = Cond.getOperand(0);
5582
5583     SDValue Cmp = Cond.getOperand(1);
5584     unsigned Opc = Cmp.getOpcode();
5585     MVT VT = Op.getValueType();
5586
5587     bool IllegalFPCMov = false;
5588     if (VT.isFloatingPoint() && !VT.isVector() &&
5589         !isScalarFPTypeInSSEReg(VT))  // FPStack?
5590       IllegalFPCMov = !hasFPCMov(cast<ConstantSDNode>(CC)->getSExtValue());
5591
5592     if ((isX86LogicalCmp(Cmp) && !IllegalFPCMov) ||
5593         Opc == X86ISD::BT) { // FIXME
5594       Cond = Cmp;
5595       addTest = false;
5596     }
5597   }
5598
5599   if (addTest) {
5600     CC = DAG.getConstant(X86::COND_NE, MVT::i8);
5601     Cond = EmitTest(Cond, X86::COND_NE, DAG);
5602   }
5603
5604   SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::Flag);
5605   SmallVector<SDValue, 4> Ops;
5606   // X86ISD::CMOV means set the result (which is operand 1) to the RHS if
5607   // condition is true.
5608   Ops.push_back(Op.getOperand(2));
5609   Ops.push_back(Op.getOperand(1));
5610   Ops.push_back(CC);
5611   Ops.push_back(Cond);
5612   return DAG.getNode(X86ISD::CMOV, dl, VTs, &Ops[0], Ops.size());
5613 }
5614
5615 // isAndOrOfSingleUseSetCCs - Return true if node is an ISD::AND or
5616 // ISD::OR of two X86ISD::SETCC nodes each of which has no other use apart
5617 // from the AND / OR.
5618 static bool isAndOrOfSetCCs(SDValue Op, unsigned &Opc) {
5619   Opc = Op.getOpcode();
5620   if (Opc != ISD::OR && Opc != ISD::AND)
5621     return false;
5622   return (Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
5623           Op.getOperand(0).hasOneUse() &&
5624           Op.getOperand(1).getOpcode() == X86ISD::SETCC &&
5625           Op.getOperand(1).hasOneUse());
5626 }
5627
5628 // isXor1OfSetCC - Return true if node is an ISD::XOR of a X86ISD::SETCC and
5629 // 1 and that the SETCC node has a single use.
5630 static bool isXor1OfSetCC(SDValue Op) {
5631   if (Op.getOpcode() != ISD::XOR)
5632     return false;
5633   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
5634   if (N1C && N1C->getAPIntValue() == 1) {
5635     return Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
5636       Op.getOperand(0).hasOneUse();
5637   }
5638   return false;
5639 }
5640
5641 SDValue X86TargetLowering::LowerBRCOND(SDValue Op, SelectionDAG &DAG) {
5642   bool addTest = true;
5643   SDValue Chain = Op.getOperand(0);
5644   SDValue Cond  = Op.getOperand(1);
5645   SDValue Dest  = Op.getOperand(2);
5646   DebugLoc dl = Op.getDebugLoc();
5647   SDValue CC;
5648
5649   if (Cond.getOpcode() == ISD::SETCC)
5650     Cond = LowerSETCC(Cond, DAG);
5651 #if 0
5652   // FIXME: LowerXALUO doesn't handle these!!
5653   else if (Cond.getOpcode() == X86ISD::ADD  ||
5654            Cond.getOpcode() == X86ISD::SUB  ||
5655            Cond.getOpcode() == X86ISD::SMUL ||
5656            Cond.getOpcode() == X86ISD::UMUL)
5657     Cond = LowerXALUO(Cond, DAG);
5658 #endif
5659
5660   // If condition flag is set by a X86ISD::CMP, then use it as the condition
5661   // setting operand in place of the X86ISD::SETCC.
5662   if (Cond.getOpcode() == X86ISD::SETCC) {
5663     CC = Cond.getOperand(0);
5664
5665     SDValue Cmp = Cond.getOperand(1);
5666     unsigned Opc = Cmp.getOpcode();
5667     // FIXME: WHY THE SPECIAL CASING OF LogicalCmp??
5668     if (isX86LogicalCmp(Cmp) || Opc == X86ISD::BT) {
5669       Cond = Cmp;
5670       addTest = false;
5671     } else {
5672       switch (cast<ConstantSDNode>(CC)->getZExtValue()) {
5673       default: break;
5674       case X86::COND_O:
5675       case X86::COND_B:
5676         // These can only come from an arithmetic instruction with overflow,
5677         // e.g. SADDO, UADDO.
5678         Cond = Cond.getNode()->getOperand(1);
5679         addTest = false;
5680         break;
5681       }
5682     }
5683   } else {
5684     unsigned CondOpc;
5685     if (Cond.hasOneUse() && isAndOrOfSetCCs(Cond, CondOpc)) {
5686       SDValue Cmp = Cond.getOperand(0).getOperand(1);
5687       if (CondOpc == ISD::OR) {
5688         // Also, recognize the pattern generated by an FCMP_UNE. We can emit
5689         // two branches instead of an explicit OR instruction with a
5690         // separate test.
5691         if (Cmp == Cond.getOperand(1).getOperand(1) &&
5692             isX86LogicalCmp(Cmp)) {
5693           CC = Cond.getOperand(0).getOperand(0);
5694           Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
5695                               Chain, Dest, CC, Cmp);
5696           CC = Cond.getOperand(1).getOperand(0);
5697           Cond = Cmp;
5698           addTest = false;
5699         }
5700       } else { // ISD::AND
5701         // Also, recognize the pattern generated by an FCMP_OEQ. We can emit
5702         // two branches instead of an explicit AND instruction with a
5703         // separate test. However, we only do this if this block doesn't
5704         // have a fall-through edge, because this requires an explicit
5705         // jmp when the condition is false.
5706         if (Cmp == Cond.getOperand(1).getOperand(1) &&
5707             isX86LogicalCmp(Cmp) &&
5708             Op.getNode()->hasOneUse()) {
5709           X86::CondCode CCode =
5710             (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
5711           CCode = X86::GetOppositeBranchCondition(CCode);
5712           CC = DAG.getConstant(CCode, MVT::i8);
5713           SDValue User = SDValue(*Op.getNode()->use_begin(), 0);
5714           // Look for an unconditional branch following this conditional branch.
5715           // We need this because we need to reverse the successors in order
5716           // to implement FCMP_OEQ.
5717           if (User.getOpcode() == ISD::BR) {
5718             SDValue FalseBB = User.getOperand(1);
5719             SDValue NewBR =
5720               DAG.UpdateNodeOperands(User, User.getOperand(0), Dest);
5721             assert(NewBR == User);
5722             Dest = FalseBB;
5723
5724             Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
5725                                 Chain, Dest, CC, Cmp);
5726             X86::CondCode CCode =
5727               (X86::CondCode)Cond.getOperand(1).getConstantOperandVal(0);
5728             CCode = X86::GetOppositeBranchCondition(CCode);
5729             CC = DAG.getConstant(CCode, MVT::i8);
5730             Cond = Cmp;
5731             addTest = false;
5732           }
5733         }
5734       }
5735     } else if (Cond.hasOneUse() && isXor1OfSetCC(Cond)) {
5736       // Recognize for xorb (setcc), 1 patterns. The xor inverts the condition.
5737       // It should be transformed during dag combiner except when the condition
5738       // is set by a arithmetics with overflow node.
5739       X86::CondCode CCode =
5740         (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
5741       CCode = X86::GetOppositeBranchCondition(CCode);
5742       CC = DAG.getConstant(CCode, MVT::i8);
5743       Cond = Cond.getOperand(0).getOperand(1);
5744       addTest = false;
5745     }
5746   }
5747
5748   if (addTest) {
5749     CC = DAG.getConstant(X86::COND_NE, MVT::i8);
5750     Cond = EmitTest(Cond, X86::COND_NE, DAG);
5751   }
5752   return DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
5753                      Chain, Dest, CC, Cond);
5754 }
5755
5756
5757 // Lower dynamic stack allocation to _alloca call for Cygwin/Mingw targets.
5758 // Calls to _alloca is needed to probe the stack when allocating more than 4k
5759 // bytes in one go. Touching the stack at 4K increments is necessary to ensure
5760 // that the guard pages used by the OS virtual memory manager are allocated in
5761 // correct sequence.
5762 SDValue
5763 X86TargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
5764                                            SelectionDAG &DAG) {
5765   assert(Subtarget->isTargetCygMing() &&
5766          "This should be used only on Cygwin/Mingw targets");
5767   DebugLoc dl = Op.getDebugLoc();
5768
5769   // Get the inputs.
5770   SDValue Chain = Op.getOperand(0);
5771   SDValue Size  = Op.getOperand(1);
5772   // FIXME: Ensure alignment here
5773
5774   SDValue Flag;
5775
5776   MVT IntPtr = getPointerTy();
5777   MVT SPTy = Subtarget->is64Bit() ? MVT::i64 : MVT::i32;
5778
5779   Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(0, true));
5780
5781   Chain = DAG.getCopyToReg(Chain, dl, X86::EAX, Size, Flag);
5782   Flag = Chain.getValue(1);
5783
5784   SDVTList  NodeTys = DAG.getVTList(MVT::Other, MVT::Flag);
5785   SDValue Ops[] = { Chain,
5786                       DAG.getTargetExternalSymbol("_alloca", IntPtr),
5787                       DAG.getRegister(X86::EAX, IntPtr),
5788                       DAG.getRegister(X86StackPtr, SPTy),
5789                       Flag };
5790   Chain = DAG.getNode(X86ISD::CALL, dl, NodeTys, Ops, 5);
5791   Flag = Chain.getValue(1);
5792
5793   Chain = DAG.getCALLSEQ_END(Chain,
5794                              DAG.getIntPtrConstant(0, true),
5795                              DAG.getIntPtrConstant(0, true),
5796                              Flag);
5797
5798   Chain = DAG.getCopyFromReg(Chain, dl, X86StackPtr, SPTy).getValue(1);
5799
5800   SDValue Ops1[2] = { Chain.getValue(0), Chain };
5801   return DAG.getMergeValues(Ops1, 2, dl);
5802 }
5803
5804 SDValue
5805 X86TargetLowering::EmitTargetCodeForMemset(SelectionDAG &DAG, DebugLoc dl,
5806                                            SDValue Chain,
5807                                            SDValue Dst, SDValue Src,
5808                                            SDValue Size, unsigned Align,
5809                                            const Value *DstSV,
5810                                            uint64_t DstSVOff) {
5811   ConstantSDNode *ConstantSize = dyn_cast<ConstantSDNode>(Size);
5812
5813   // If not DWORD aligned or size is more than the threshold, call the library.
5814   // The libc version is likely to be faster for these cases. It can use the
5815   // address value and run time information about the CPU.
5816   if ((Align & 3) != 0 ||
5817       !ConstantSize ||
5818       ConstantSize->getZExtValue() >
5819         getSubtarget()->getMaxInlineSizeThreshold()) {
5820     SDValue InFlag(0, 0);
5821
5822     // Check to see if there is a specialized entry-point for memory zeroing.
5823     ConstantSDNode *V = dyn_cast<ConstantSDNode>(Src);
5824
5825     if (const char *bzeroEntry =  V &&
5826         V->isNullValue() ? Subtarget->getBZeroEntry() : 0) {
5827       MVT IntPtr = getPointerTy();
5828       const Type *IntPtrTy = TD->getIntPtrType();
5829       TargetLowering::ArgListTy Args;
5830       TargetLowering::ArgListEntry Entry;
5831       Entry.Node = Dst;
5832       Entry.Ty = IntPtrTy;
5833       Args.push_back(Entry);
5834       Entry.Node = Size;
5835       Args.push_back(Entry);
5836       std::pair<SDValue,SDValue> CallResult =
5837         LowerCallTo(Chain, Type::VoidTy, false, false, false, false,
5838                     0, CallingConv::C, false,
5839                     DAG.getExternalSymbol(bzeroEntry, IntPtr), Args, DAG, dl);
5840       return CallResult.second;
5841     }
5842
5843     // Otherwise have the target-independent code call memset.
5844     return SDValue();
5845   }
5846
5847   uint64_t SizeVal = ConstantSize->getZExtValue();
5848   SDValue InFlag(0, 0);
5849   MVT AVT;
5850   SDValue Count;
5851   ConstantSDNode *ValC = dyn_cast<ConstantSDNode>(Src);
5852   unsigned BytesLeft = 0;
5853   bool TwoRepStos = false;
5854   if (ValC) {
5855     unsigned ValReg;
5856     uint64_t Val = ValC->getZExtValue() & 255;
5857
5858     // If the value is a constant, then we can potentially use larger sets.
5859     switch (Align & 3) {
5860     case 2:   // WORD aligned
5861       AVT = MVT::i16;
5862       ValReg = X86::AX;
5863       Val = (Val << 8) | Val;
5864       break;
5865     case 0:  // DWORD aligned
5866       AVT = MVT::i32;
5867       ValReg = X86::EAX;
5868       Val = (Val << 8)  | Val;
5869       Val = (Val << 16) | Val;
5870       if (Subtarget->is64Bit() && ((Align & 0x7) == 0)) {  // QWORD aligned
5871         AVT = MVT::i64;
5872         ValReg = X86::RAX;
5873         Val = (Val << 32) | Val;
5874       }
5875       break;
5876     default:  // Byte aligned
5877       AVT = MVT::i8;
5878       ValReg = X86::AL;
5879       Count = DAG.getIntPtrConstant(SizeVal);
5880       break;
5881     }
5882
5883     if (AVT.bitsGT(MVT::i8)) {
5884       unsigned UBytes = AVT.getSizeInBits() / 8;
5885       Count = DAG.getIntPtrConstant(SizeVal / UBytes);
5886       BytesLeft = SizeVal % UBytes;
5887     }
5888
5889     Chain  = DAG.getCopyToReg(Chain, dl, ValReg, DAG.getConstant(Val, AVT),
5890                               InFlag);
5891     InFlag = Chain.getValue(1);
5892   } else {
5893     AVT = MVT::i8;
5894     Count  = DAG.getIntPtrConstant(SizeVal);
5895     Chain  = DAG.getCopyToReg(Chain, dl, X86::AL, Src, InFlag);
5896     InFlag = Chain.getValue(1);
5897   }
5898
5899   Chain  = DAG.getCopyToReg(Chain, dl, Subtarget->is64Bit() ? X86::RCX :
5900                                                               X86::ECX,
5901                             Count, InFlag);
5902   InFlag = Chain.getValue(1);
5903   Chain  = DAG.getCopyToReg(Chain, dl, Subtarget->is64Bit() ? X86::RDI :
5904                                                               X86::EDI,
5905                             Dst, InFlag);
5906   InFlag = Chain.getValue(1);
5907
5908   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Flag);
5909   SmallVector<SDValue, 8> Ops;
5910   Ops.push_back(Chain);
5911   Ops.push_back(DAG.getValueType(AVT));
5912   Ops.push_back(InFlag);
5913   Chain  = DAG.getNode(X86ISD::REP_STOS, dl, Tys, &Ops[0], Ops.size());
5914
5915   if (TwoRepStos) {
5916     InFlag = Chain.getValue(1);
5917     Count  = Size;
5918     MVT CVT = Count.getValueType();
5919     SDValue Left = DAG.getNode(ISD::AND, dl, CVT, Count,
5920                                DAG.getConstant((AVT == MVT::i64) ? 7 : 3, CVT));
5921     Chain  = DAG.getCopyToReg(Chain, dl, (CVT == MVT::i64) ? X86::RCX :
5922                                                              X86::ECX,
5923                               Left, InFlag);
5924     InFlag = Chain.getValue(1);
5925     Tys = DAG.getVTList(MVT::Other, MVT::Flag);
5926     Ops.clear();
5927     Ops.push_back(Chain);
5928     Ops.push_back(DAG.getValueType(MVT::i8));
5929     Ops.push_back(InFlag);
5930     Chain  = DAG.getNode(X86ISD::REP_STOS, dl, Tys, &Ops[0], Ops.size());
5931   } else if (BytesLeft) {
5932     // Handle the last 1 - 7 bytes.
5933     unsigned Offset = SizeVal - BytesLeft;
5934     MVT AddrVT = Dst.getValueType();
5935     MVT SizeVT = Size.getValueType();
5936
5937     Chain = DAG.getMemset(Chain, dl,
5938                           DAG.getNode(ISD::ADD, dl, AddrVT, Dst,
5939                                       DAG.getConstant(Offset, AddrVT)),
5940                           Src,
5941                           DAG.getConstant(BytesLeft, SizeVT),
5942                           Align, DstSV, DstSVOff + Offset);
5943   }
5944
5945   // TODO: Use a Tokenfactor, as in memcpy, instead of a single chain.
5946   return Chain;
5947 }
5948
5949 SDValue
5950 X86TargetLowering::EmitTargetCodeForMemcpy(SelectionDAG &DAG, DebugLoc dl,
5951                                       SDValue Chain, SDValue Dst, SDValue Src,
5952                                       SDValue Size, unsigned Align,
5953                                       bool AlwaysInline,
5954                                       const Value *DstSV, uint64_t DstSVOff,
5955                                       const Value *SrcSV, uint64_t SrcSVOff) {
5956   // This requires the copy size to be a constant, preferrably
5957   // within a subtarget-specific limit.
5958   ConstantSDNode *ConstantSize = dyn_cast<ConstantSDNode>(Size);
5959   if (!ConstantSize)
5960     return SDValue();
5961   uint64_t SizeVal = ConstantSize->getZExtValue();
5962   if (!AlwaysInline && SizeVal > getSubtarget()->getMaxInlineSizeThreshold())
5963     return SDValue();
5964
5965   /// If not DWORD aligned, call the library.
5966   if ((Align & 3) != 0)
5967     return SDValue();
5968
5969   // DWORD aligned
5970   MVT AVT = MVT::i32;
5971   if (Subtarget->is64Bit() && ((Align & 0x7) == 0))  // QWORD aligned
5972     AVT = MVT::i64;
5973
5974   unsigned UBytes = AVT.getSizeInBits() / 8;
5975   unsigned CountVal = SizeVal / UBytes;
5976   SDValue Count = DAG.getIntPtrConstant(CountVal);
5977   unsigned BytesLeft = SizeVal % UBytes;
5978
5979   SDValue InFlag(0, 0);
5980   Chain  = DAG.getCopyToReg(Chain, dl, Subtarget->is64Bit() ? X86::RCX :
5981                                                               X86::ECX,
5982                             Count, InFlag);
5983   InFlag = Chain.getValue(1);
5984   Chain  = DAG.getCopyToReg(Chain, dl, Subtarget->is64Bit() ? X86::RDI :
5985                                                              X86::EDI,
5986                             Dst, InFlag);
5987   InFlag = Chain.getValue(1);
5988   Chain  = DAG.getCopyToReg(Chain, dl, Subtarget->is64Bit() ? X86::RSI :
5989                                                               X86::ESI,
5990                             Src, InFlag);
5991   InFlag = Chain.getValue(1);
5992
5993   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Flag);
5994   SmallVector<SDValue, 8> Ops;
5995   Ops.push_back(Chain);
5996   Ops.push_back(DAG.getValueType(AVT));
5997   Ops.push_back(InFlag);
5998   SDValue RepMovs = DAG.getNode(X86ISD::REP_MOVS, dl, Tys, &Ops[0], Ops.size());
5999
6000   SmallVector<SDValue, 4> Results;
6001   Results.push_back(RepMovs);
6002   if (BytesLeft) {
6003     // Handle the last 1 - 7 bytes.
6004     unsigned Offset = SizeVal - BytesLeft;
6005     MVT DstVT = Dst.getValueType();
6006     MVT SrcVT = Src.getValueType();
6007     MVT SizeVT = Size.getValueType();
6008     Results.push_back(DAG.getMemcpy(Chain, dl,
6009                                     DAG.getNode(ISD::ADD, dl, DstVT, Dst,
6010                                                 DAG.getConstant(Offset, DstVT)),
6011                                     DAG.getNode(ISD::ADD, dl, SrcVT, Src,
6012                                                 DAG.getConstant(Offset, SrcVT)),
6013                                     DAG.getConstant(BytesLeft, SizeVT),
6014                                     Align, AlwaysInline,
6015                                     DstSV, DstSVOff + Offset,
6016                                     SrcSV, SrcSVOff + Offset));
6017   }
6018
6019   return DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
6020                      &Results[0], Results.size());
6021 }
6022
6023 SDValue X86TargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) {
6024   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
6025   DebugLoc dl = Op.getDebugLoc();
6026
6027   if (!Subtarget->is64Bit()) {
6028     // vastart just stores the address of the VarArgsFrameIndex slot into the
6029     // memory location argument.
6030     SDValue FR = DAG.getFrameIndex(VarArgsFrameIndex, getPointerTy());
6031     return DAG.getStore(Op.getOperand(0), dl, FR, Op.getOperand(1), SV, 0);
6032   }
6033
6034   // __va_list_tag:
6035   //   gp_offset         (0 - 6 * 8)
6036   //   fp_offset         (48 - 48 + 8 * 16)
6037   //   overflow_arg_area (point to parameters coming in memory).
6038   //   reg_save_area
6039   SmallVector<SDValue, 8> MemOps;
6040   SDValue FIN = Op.getOperand(1);
6041   // Store gp_offset
6042   SDValue Store = DAG.getStore(Op.getOperand(0), dl,
6043                                  DAG.getConstant(VarArgsGPOffset, MVT::i32),
6044                                  FIN, SV, 0);
6045   MemOps.push_back(Store);
6046
6047   // Store fp_offset
6048   FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(),
6049                     FIN, DAG.getIntPtrConstant(4));
6050   Store = DAG.getStore(Op.getOperand(0), dl,
6051                        DAG.getConstant(VarArgsFPOffset, MVT::i32),
6052                        FIN, SV, 0);
6053   MemOps.push_back(Store);
6054
6055   // Store ptr to overflow_arg_area
6056   FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(),
6057                     FIN, DAG.getIntPtrConstant(4));
6058   SDValue OVFIN = DAG.getFrameIndex(VarArgsFrameIndex, getPointerTy());
6059   Store = DAG.getStore(Op.getOperand(0), dl, OVFIN, FIN, SV, 0);
6060   MemOps.push_back(Store);
6061
6062   // Store ptr to reg_save_area.
6063   FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(),
6064                     FIN, DAG.getIntPtrConstant(8));
6065   SDValue RSFIN = DAG.getFrameIndex(RegSaveFrameIndex, getPointerTy());
6066   Store = DAG.getStore(Op.getOperand(0), dl, RSFIN, FIN, SV, 0);
6067   MemOps.push_back(Store);
6068   return DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
6069                      &MemOps[0], MemOps.size());
6070 }
6071
6072 SDValue X86TargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) {
6073   // X86-64 va_list is a struct { i32, i32, i8*, i8* }.
6074   assert(Subtarget->is64Bit() && "This code only handles 64-bit va_arg!");
6075   SDValue Chain = Op.getOperand(0);
6076   SDValue SrcPtr = Op.getOperand(1);
6077   SDValue SrcSV = Op.getOperand(2);
6078
6079   llvm_report_error("VAArgInst is not yet implemented for x86-64!");
6080   return SDValue();
6081 }
6082
6083 SDValue X86TargetLowering::LowerVACOPY(SDValue Op, SelectionDAG &DAG) {
6084   // X86-64 va_list is a struct { i32, i32, i8*, i8* }.
6085   assert(Subtarget->is64Bit() && "This code only handles 64-bit va_copy!");
6086   SDValue Chain = Op.getOperand(0);
6087   SDValue DstPtr = Op.getOperand(1);
6088   SDValue SrcPtr = Op.getOperand(2);
6089   const Value *DstSV = cast<SrcValueSDNode>(Op.getOperand(3))->getValue();
6090   const Value *SrcSV = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
6091   DebugLoc dl = Op.getDebugLoc();
6092
6093   return DAG.getMemcpy(Chain, dl, DstPtr, SrcPtr,
6094                        DAG.getIntPtrConstant(24), 8, false,
6095                        DstSV, 0, SrcSV, 0);
6096 }
6097
6098 SDValue
6099 X86TargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op, SelectionDAG &DAG) {
6100   DebugLoc dl = Op.getDebugLoc();
6101   unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
6102   switch (IntNo) {
6103   default: return SDValue();    // Don't custom lower most intrinsics.
6104   // Comparison intrinsics.
6105   case Intrinsic::x86_sse_comieq_ss:
6106   case Intrinsic::x86_sse_comilt_ss:
6107   case Intrinsic::x86_sse_comile_ss:
6108   case Intrinsic::x86_sse_comigt_ss:
6109   case Intrinsic::x86_sse_comige_ss:
6110   case Intrinsic::x86_sse_comineq_ss:
6111   case Intrinsic::x86_sse_ucomieq_ss:
6112   case Intrinsic::x86_sse_ucomilt_ss:
6113   case Intrinsic::x86_sse_ucomile_ss:
6114   case Intrinsic::x86_sse_ucomigt_ss:
6115   case Intrinsic::x86_sse_ucomige_ss:
6116   case Intrinsic::x86_sse_ucomineq_ss:
6117   case Intrinsic::x86_sse2_comieq_sd:
6118   case Intrinsic::x86_sse2_comilt_sd:
6119   case Intrinsic::x86_sse2_comile_sd:
6120   case Intrinsic::x86_sse2_comigt_sd:
6121   case Intrinsic::x86_sse2_comige_sd:
6122   case Intrinsic::x86_sse2_comineq_sd:
6123   case Intrinsic::x86_sse2_ucomieq_sd:
6124   case Intrinsic::x86_sse2_ucomilt_sd:
6125   case Intrinsic::x86_sse2_ucomile_sd:
6126   case Intrinsic::x86_sse2_ucomigt_sd:
6127   case Intrinsic::x86_sse2_ucomige_sd:
6128   case Intrinsic::x86_sse2_ucomineq_sd: {
6129     unsigned Opc = 0;
6130     ISD::CondCode CC = ISD::SETCC_INVALID;
6131     switch (IntNo) {
6132     default: break;
6133     case Intrinsic::x86_sse_comieq_ss:
6134     case Intrinsic::x86_sse2_comieq_sd:
6135       Opc = X86ISD::COMI;
6136       CC = ISD::SETEQ;
6137       break;
6138     case Intrinsic::x86_sse_comilt_ss:
6139     case Intrinsic::x86_sse2_comilt_sd:
6140       Opc = X86ISD::COMI;
6141       CC = ISD::SETLT;
6142       break;
6143     case Intrinsic::x86_sse_comile_ss:
6144     case Intrinsic::x86_sse2_comile_sd:
6145       Opc = X86ISD::COMI;
6146       CC = ISD::SETLE;
6147       break;
6148     case Intrinsic::x86_sse_comigt_ss:
6149     case Intrinsic::x86_sse2_comigt_sd:
6150       Opc = X86ISD::COMI;
6151       CC = ISD::SETGT;
6152       break;
6153     case Intrinsic::x86_sse_comige_ss:
6154     case Intrinsic::x86_sse2_comige_sd:
6155       Opc = X86ISD::COMI;
6156       CC = ISD::SETGE;
6157       break;
6158     case Intrinsic::x86_sse_comineq_ss:
6159     case Intrinsic::x86_sse2_comineq_sd:
6160       Opc = X86ISD::COMI;
6161       CC = ISD::SETNE;
6162       break;
6163     case Intrinsic::x86_sse_ucomieq_ss:
6164     case Intrinsic::x86_sse2_ucomieq_sd:
6165       Opc = X86ISD::UCOMI;
6166       CC = ISD::SETEQ;
6167       break;
6168     case Intrinsic::x86_sse_ucomilt_ss:
6169     case Intrinsic::x86_sse2_ucomilt_sd:
6170       Opc = X86ISD::UCOMI;
6171       CC = ISD::SETLT;
6172       break;
6173     case Intrinsic::x86_sse_ucomile_ss:
6174     case Intrinsic::x86_sse2_ucomile_sd:
6175       Opc = X86ISD::UCOMI;
6176       CC = ISD::SETLE;
6177       break;
6178     case Intrinsic::x86_sse_ucomigt_ss:
6179     case Intrinsic::x86_sse2_ucomigt_sd:
6180       Opc = X86ISD::UCOMI;
6181       CC = ISD::SETGT;
6182       break;
6183     case Intrinsic::x86_sse_ucomige_ss:
6184     case Intrinsic::x86_sse2_ucomige_sd:
6185       Opc = X86ISD::UCOMI;
6186       CC = ISD::SETGE;
6187       break;
6188     case Intrinsic::x86_sse_ucomineq_ss:
6189     case Intrinsic::x86_sse2_ucomineq_sd:
6190       Opc = X86ISD::UCOMI;
6191       CC = ISD::SETNE;
6192       break;
6193     }
6194
6195     SDValue LHS = Op.getOperand(1);
6196     SDValue RHS = Op.getOperand(2);
6197     unsigned X86CC = TranslateX86CC(CC, true, LHS, RHS, DAG);
6198     SDValue Cond = DAG.getNode(Opc, dl, MVT::i32, LHS, RHS);
6199     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
6200                                 DAG.getConstant(X86CC, MVT::i8), Cond);
6201     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
6202   }
6203
6204   // Fix vector shift instructions where the last operand is a non-immediate
6205   // i32 value.
6206   case Intrinsic::x86_sse2_pslli_w:
6207   case Intrinsic::x86_sse2_pslli_d:
6208   case Intrinsic::x86_sse2_pslli_q:
6209   case Intrinsic::x86_sse2_psrli_w:
6210   case Intrinsic::x86_sse2_psrli_d:
6211   case Intrinsic::x86_sse2_psrli_q:
6212   case Intrinsic::x86_sse2_psrai_w:
6213   case Intrinsic::x86_sse2_psrai_d:
6214   case Intrinsic::x86_mmx_pslli_w:
6215   case Intrinsic::x86_mmx_pslli_d:
6216   case Intrinsic::x86_mmx_pslli_q:
6217   case Intrinsic::x86_mmx_psrli_w:
6218   case Intrinsic::x86_mmx_psrli_d:
6219   case Intrinsic::x86_mmx_psrli_q:
6220   case Intrinsic::x86_mmx_psrai_w:
6221   case Intrinsic::x86_mmx_psrai_d: {
6222     SDValue ShAmt = Op.getOperand(2);
6223     if (isa<ConstantSDNode>(ShAmt))
6224       return SDValue();
6225
6226     unsigned NewIntNo = 0;
6227     MVT ShAmtVT = MVT::v4i32;
6228     switch (IntNo) {
6229     case Intrinsic::x86_sse2_pslli_w:
6230       NewIntNo = Intrinsic::x86_sse2_psll_w;
6231       break;
6232     case Intrinsic::x86_sse2_pslli_d:
6233       NewIntNo = Intrinsic::x86_sse2_psll_d;
6234       break;
6235     case Intrinsic::x86_sse2_pslli_q:
6236       NewIntNo = Intrinsic::x86_sse2_psll_q;
6237       break;
6238     case Intrinsic::x86_sse2_psrli_w:
6239       NewIntNo = Intrinsic::x86_sse2_psrl_w;
6240       break;
6241     case Intrinsic::x86_sse2_psrli_d:
6242       NewIntNo = Intrinsic::x86_sse2_psrl_d;
6243       break;
6244     case Intrinsic::x86_sse2_psrli_q:
6245       NewIntNo = Intrinsic::x86_sse2_psrl_q;
6246       break;
6247     case Intrinsic::x86_sse2_psrai_w:
6248       NewIntNo = Intrinsic::x86_sse2_psra_w;
6249       break;
6250     case Intrinsic::x86_sse2_psrai_d:
6251       NewIntNo = Intrinsic::x86_sse2_psra_d;
6252       break;
6253     default: {
6254       ShAmtVT = MVT::v2i32;
6255       switch (IntNo) {
6256       case Intrinsic::x86_mmx_pslli_w:
6257         NewIntNo = Intrinsic::x86_mmx_psll_w;
6258         break;
6259       case Intrinsic::x86_mmx_pslli_d:
6260         NewIntNo = Intrinsic::x86_mmx_psll_d;
6261         break;
6262       case Intrinsic::x86_mmx_pslli_q:
6263         NewIntNo = Intrinsic::x86_mmx_psll_q;
6264         break;
6265       case Intrinsic::x86_mmx_psrli_w:
6266         NewIntNo = Intrinsic::x86_mmx_psrl_w;
6267         break;
6268       case Intrinsic::x86_mmx_psrli_d:
6269         NewIntNo = Intrinsic::x86_mmx_psrl_d;
6270         break;
6271       case Intrinsic::x86_mmx_psrli_q:
6272         NewIntNo = Intrinsic::x86_mmx_psrl_q;
6273         break;
6274       case Intrinsic::x86_mmx_psrai_w:
6275         NewIntNo = Intrinsic::x86_mmx_psra_w;
6276         break;
6277       case Intrinsic::x86_mmx_psrai_d:
6278         NewIntNo = Intrinsic::x86_mmx_psra_d;
6279         break;
6280       default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
6281       }
6282       break;
6283     }
6284     }
6285     MVT VT = Op.getValueType();
6286     ShAmt = DAG.getNode(ISD::BIT_CONVERT, dl, VT,
6287                         DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, ShAmtVT, ShAmt));
6288     return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
6289                        DAG.getConstant(NewIntNo, MVT::i32),
6290                        Op.getOperand(1), ShAmt);
6291   }
6292   }
6293 }
6294
6295 SDValue X86TargetLowering::LowerRETURNADDR(SDValue Op, SelectionDAG &DAG) {
6296   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
6297   DebugLoc dl = Op.getDebugLoc();
6298
6299   if (Depth > 0) {
6300     SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
6301     SDValue Offset =
6302       DAG.getConstant(TD->getPointerSize(),
6303                       Subtarget->is64Bit() ? MVT::i64 : MVT::i32);
6304     return DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(),
6305                        DAG.getNode(ISD::ADD, dl, getPointerTy(),
6306                                    FrameAddr, Offset),
6307                        NULL, 0);
6308   }
6309
6310   // Just load the return address.
6311   SDValue RetAddrFI = getReturnAddressFrameIndex(DAG);
6312   return DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(),
6313                      RetAddrFI, NULL, 0);
6314 }
6315
6316 SDValue X86TargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) {
6317   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
6318   MFI->setFrameAddressIsTaken(true);
6319   MVT VT = Op.getValueType();
6320   DebugLoc dl = Op.getDebugLoc();  // FIXME probably not meaningful
6321   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
6322   unsigned FrameReg = Subtarget->is64Bit() ? X86::RBP : X86::EBP;
6323   SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
6324   while (Depth--)
6325     FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr, NULL, 0);
6326   return FrameAddr;
6327 }
6328
6329 SDValue X86TargetLowering::LowerFRAME_TO_ARGS_OFFSET(SDValue Op,
6330                                                      SelectionDAG &DAG) {
6331   return DAG.getIntPtrConstant(2*TD->getPointerSize());
6332 }
6333
6334 SDValue X86TargetLowering::LowerEH_RETURN(SDValue Op, SelectionDAG &DAG)
6335 {
6336   MachineFunction &MF = DAG.getMachineFunction();
6337   SDValue Chain     = Op.getOperand(0);
6338   SDValue Offset    = Op.getOperand(1);
6339   SDValue Handler   = Op.getOperand(2);
6340   DebugLoc dl       = Op.getDebugLoc();
6341
6342   SDValue Frame = DAG.getRegister(Subtarget->is64Bit() ? X86::RBP : X86::EBP,
6343                                   getPointerTy());
6344   unsigned StoreAddrReg = (Subtarget->is64Bit() ? X86::RCX : X86::ECX);
6345
6346   SDValue StoreAddr = DAG.getNode(ISD::SUB, dl, getPointerTy(), Frame,
6347                                   DAG.getIntPtrConstant(-TD->getPointerSize()));
6348   StoreAddr = DAG.getNode(ISD::ADD, dl, getPointerTy(), StoreAddr, Offset);
6349   Chain = DAG.getStore(Chain, dl, Handler, StoreAddr, NULL, 0);
6350   Chain = DAG.getCopyToReg(Chain, dl, StoreAddrReg, StoreAddr);
6351   MF.getRegInfo().addLiveOut(StoreAddrReg);
6352
6353   return DAG.getNode(X86ISD::EH_RETURN, dl,
6354                      MVT::Other,
6355                      Chain, DAG.getRegister(StoreAddrReg, getPointerTy()));
6356 }
6357
6358 SDValue X86TargetLowering::LowerTRAMPOLINE(SDValue Op,
6359                                              SelectionDAG &DAG) {
6360   SDValue Root = Op.getOperand(0);
6361   SDValue Trmp = Op.getOperand(1); // trampoline
6362   SDValue FPtr = Op.getOperand(2); // nested function
6363   SDValue Nest = Op.getOperand(3); // 'nest' parameter value
6364   DebugLoc dl  = Op.getDebugLoc();
6365
6366   const Value *TrmpAddr = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
6367
6368   const X86InstrInfo *TII =
6369     ((X86TargetMachine&)getTargetMachine()).getInstrInfo();
6370
6371   if (Subtarget->is64Bit()) {
6372     SDValue OutChains[6];
6373
6374     // Large code-model.
6375
6376     const unsigned char JMP64r  = TII->getBaseOpcodeFor(X86::JMP64r);
6377     const unsigned char MOV64ri = TII->getBaseOpcodeFor(X86::MOV64ri);
6378
6379     const unsigned char N86R10 = RegInfo->getX86RegNum(X86::R10);
6380     const unsigned char N86R11 = RegInfo->getX86RegNum(X86::R11);
6381
6382     const unsigned char REX_WB = 0x40 | 0x08 | 0x01; // REX prefix
6383
6384     // Load the pointer to the nested function into R11.
6385     unsigned OpCode = ((MOV64ri | N86R11) << 8) | REX_WB; // movabsq r11
6386     SDValue Addr = Trmp;
6387     OutChains[0] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
6388                                 Addr, TrmpAddr, 0);
6389
6390     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
6391                        DAG.getConstant(2, MVT::i64));
6392     OutChains[1] = DAG.getStore(Root, dl, FPtr, Addr, TrmpAddr, 2, false, 2);
6393
6394     // Load the 'nest' parameter value into R10.
6395     // R10 is specified in X86CallingConv.td
6396     OpCode = ((MOV64ri | N86R10) << 8) | REX_WB; // movabsq r10
6397     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
6398                        DAG.getConstant(10, MVT::i64));
6399     OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
6400                                 Addr, TrmpAddr, 10);
6401
6402     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
6403                        DAG.getConstant(12, MVT::i64));
6404     OutChains[3] = DAG.getStore(Root, dl, Nest, Addr, TrmpAddr, 12, false, 2);
6405
6406     // Jump to the nested function.
6407     OpCode = (JMP64r << 8) | REX_WB; // jmpq *...
6408     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
6409                        DAG.getConstant(20, MVT::i64));
6410     OutChains[4] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
6411                                 Addr, TrmpAddr, 20);
6412
6413     unsigned char ModRM = N86R11 | (4 << 3) | (3 << 6); // ...r11
6414     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
6415                        DAG.getConstant(22, MVT::i64));
6416     OutChains[5] = DAG.getStore(Root, dl, DAG.getConstant(ModRM, MVT::i8), Addr,
6417                                 TrmpAddr, 22);
6418
6419     SDValue Ops[] =
6420       { Trmp, DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains, 6) };
6421     return DAG.getMergeValues(Ops, 2, dl);
6422   } else {
6423     const Function *Func =
6424       cast<Function>(cast<SrcValueSDNode>(Op.getOperand(5))->getValue());
6425     unsigned CC = Func->getCallingConv();
6426     unsigned NestReg;
6427
6428     switch (CC) {
6429     default:
6430       llvm_unreachable("Unsupported calling convention");
6431     case CallingConv::C:
6432     case CallingConv::X86_StdCall: {
6433       // Pass 'nest' parameter in ECX.
6434       // Must be kept in sync with X86CallingConv.td
6435       NestReg = X86::ECX;
6436
6437       // Check that ECX wasn't needed by an 'inreg' parameter.
6438       const FunctionType *FTy = Func->getFunctionType();
6439       const AttrListPtr &Attrs = Func->getAttributes();
6440
6441       if (!Attrs.isEmpty() && !Func->isVarArg()) {
6442         unsigned InRegCount = 0;
6443         unsigned Idx = 1;
6444
6445         for (FunctionType::param_iterator I = FTy->param_begin(),
6446              E = FTy->param_end(); I != E; ++I, ++Idx)
6447           if (Attrs.paramHasAttr(Idx, Attribute::InReg))
6448             // FIXME: should only count parameters that are lowered to integers.
6449             InRegCount += (TD->getTypeSizeInBits(*I) + 31) / 32;
6450
6451         if (InRegCount > 2) {
6452           llvm_report_error("Nest register in use - reduce number of inreg parameters!");
6453         }
6454       }
6455       break;
6456     }
6457     case CallingConv::X86_FastCall:
6458     case CallingConv::Fast:
6459       // Pass 'nest' parameter in EAX.
6460       // Must be kept in sync with X86CallingConv.td
6461       NestReg = X86::EAX;
6462       break;
6463     }
6464
6465     SDValue OutChains[4];
6466     SDValue Addr, Disp;
6467
6468     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
6469                        DAG.getConstant(10, MVT::i32));
6470     Disp = DAG.getNode(ISD::SUB, dl, MVT::i32, FPtr, Addr);
6471
6472     const unsigned char MOV32ri = TII->getBaseOpcodeFor(X86::MOV32ri);
6473     const unsigned char N86Reg = RegInfo->getX86RegNum(NestReg);
6474     OutChains[0] = DAG.getStore(Root, dl,
6475                                 DAG.getConstant(MOV32ri|N86Reg, MVT::i8),
6476                                 Trmp, TrmpAddr, 0);
6477
6478     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
6479                        DAG.getConstant(1, MVT::i32));
6480     OutChains[1] = DAG.getStore(Root, dl, Nest, Addr, TrmpAddr, 1, false, 1);
6481
6482     const unsigned char JMP = TII->getBaseOpcodeFor(X86::JMP);
6483     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
6484                        DAG.getConstant(5, MVT::i32));
6485     OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(JMP, MVT::i8), Addr,
6486                                 TrmpAddr, 5, false, 1);
6487
6488     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
6489                        DAG.getConstant(6, MVT::i32));
6490     OutChains[3] = DAG.getStore(Root, dl, Disp, Addr, TrmpAddr, 6, false, 1);
6491
6492     SDValue Ops[] =
6493       { Trmp, DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains, 4) };
6494     return DAG.getMergeValues(Ops, 2, dl);
6495   }
6496 }
6497
6498 SDValue X86TargetLowering::LowerFLT_ROUNDS_(SDValue Op, SelectionDAG &DAG) {
6499   /*
6500    The rounding mode is in bits 11:10 of FPSR, and has the following
6501    settings:
6502      00 Round to nearest
6503      01 Round to -inf
6504      10 Round to +inf
6505      11 Round to 0
6506
6507   FLT_ROUNDS, on the other hand, expects the following:
6508     -1 Undefined
6509      0 Round to 0
6510      1 Round to nearest
6511      2 Round to +inf
6512      3 Round to -inf
6513
6514   To perform the conversion, we do:
6515     (((((FPSR & 0x800) >> 11) | ((FPSR & 0x400) >> 9)) + 1) & 3)
6516   */
6517
6518   MachineFunction &MF = DAG.getMachineFunction();
6519   const TargetMachine &TM = MF.getTarget();
6520   const TargetFrameInfo &TFI = *TM.getFrameInfo();
6521   unsigned StackAlignment = TFI.getStackAlignment();
6522   MVT VT = Op.getValueType();
6523   DebugLoc dl = Op.getDebugLoc();
6524
6525   // Save FP Control Word to stack slot
6526   int SSFI = MF.getFrameInfo()->CreateStackObject(2, StackAlignment);
6527   SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
6528
6529   SDValue Chain = DAG.getNode(X86ISD::FNSTCW16m, dl, MVT::Other,
6530                               DAG.getEntryNode(), StackSlot);
6531
6532   // Load FP Control Word from stack slot
6533   SDValue CWD = DAG.getLoad(MVT::i16, dl, Chain, StackSlot, NULL, 0);
6534
6535   // Transform as necessary
6536   SDValue CWD1 =
6537     DAG.getNode(ISD::SRL, dl, MVT::i16,
6538                 DAG.getNode(ISD::AND, dl, MVT::i16,
6539                             CWD, DAG.getConstant(0x800, MVT::i16)),
6540                 DAG.getConstant(11, MVT::i8));
6541   SDValue CWD2 =
6542     DAG.getNode(ISD::SRL, dl, MVT::i16,
6543                 DAG.getNode(ISD::AND, dl, MVT::i16,
6544                             CWD, DAG.getConstant(0x400, MVT::i16)),
6545                 DAG.getConstant(9, MVT::i8));
6546
6547   SDValue RetVal =
6548     DAG.getNode(ISD::AND, dl, MVT::i16,
6549                 DAG.getNode(ISD::ADD, dl, MVT::i16,
6550                             DAG.getNode(ISD::OR, dl, MVT::i16, CWD1, CWD2),
6551                             DAG.getConstant(1, MVT::i16)),
6552                 DAG.getConstant(3, MVT::i16));
6553
6554
6555   return DAG.getNode((VT.getSizeInBits() < 16 ?
6556                       ISD::TRUNCATE : ISD::ZERO_EXTEND), dl, VT, RetVal);
6557 }
6558
6559 SDValue X86TargetLowering::LowerCTLZ(SDValue Op, SelectionDAG &DAG) {
6560   MVT VT = Op.getValueType();
6561   MVT OpVT = VT;
6562   unsigned NumBits = VT.getSizeInBits();
6563   DebugLoc dl = Op.getDebugLoc();
6564
6565   Op = Op.getOperand(0);
6566   if (VT == MVT::i8) {
6567     // Zero extend to i32 since there is not an i8 bsr.
6568     OpVT = MVT::i32;
6569     Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
6570   }
6571
6572   // Issue a bsr (scan bits in reverse) which also sets EFLAGS.
6573   SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
6574   Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
6575
6576   // If src is zero (i.e. bsr sets ZF), returns NumBits.
6577   SmallVector<SDValue, 4> Ops;
6578   Ops.push_back(Op);
6579   Ops.push_back(DAG.getConstant(NumBits+NumBits-1, OpVT));
6580   Ops.push_back(DAG.getConstant(X86::COND_E, MVT::i8));
6581   Ops.push_back(Op.getValue(1));
6582   Op = DAG.getNode(X86ISD::CMOV, dl, OpVT, &Ops[0], 4);
6583
6584   // Finally xor with NumBits-1.
6585   Op = DAG.getNode(ISD::XOR, dl, OpVT, Op, DAG.getConstant(NumBits-1, OpVT));
6586
6587   if (VT == MVT::i8)
6588     Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
6589   return Op;
6590 }
6591
6592 SDValue X86TargetLowering::LowerCTTZ(SDValue Op, SelectionDAG &DAG) {
6593   MVT VT = Op.getValueType();
6594   MVT OpVT = VT;
6595   unsigned NumBits = VT.getSizeInBits();
6596   DebugLoc dl = Op.getDebugLoc();
6597
6598   Op = Op.getOperand(0);
6599   if (VT == MVT::i8) {
6600     OpVT = MVT::i32;
6601     Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
6602   }
6603
6604   // Issue a bsf (scan bits forward) which also sets EFLAGS.
6605   SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
6606   Op = DAG.getNode(X86ISD::BSF, dl, VTs, Op);
6607
6608   // If src is zero (i.e. bsf sets ZF), returns NumBits.
6609   SmallVector<SDValue, 4> Ops;
6610   Ops.push_back(Op);
6611   Ops.push_back(DAG.getConstant(NumBits, OpVT));
6612   Ops.push_back(DAG.getConstant(X86::COND_E, MVT::i8));
6613   Ops.push_back(Op.getValue(1));
6614   Op = DAG.getNode(X86ISD::CMOV, dl, OpVT, &Ops[0], 4);
6615
6616   if (VT == MVT::i8)
6617     Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
6618   return Op;
6619 }
6620
6621 SDValue X86TargetLowering::LowerMUL_V2I64(SDValue Op, SelectionDAG &DAG) {
6622   MVT VT = Op.getValueType();
6623   assert(VT == MVT::v2i64 && "Only know how to lower V2I64 multiply");
6624   DebugLoc dl = Op.getDebugLoc();
6625
6626   //  ulong2 Ahi = __builtin_ia32_psrlqi128( a, 32);
6627   //  ulong2 Bhi = __builtin_ia32_psrlqi128( b, 32);
6628   //  ulong2 AloBlo = __builtin_ia32_pmuludq128( a, b );
6629   //  ulong2 AloBhi = __builtin_ia32_pmuludq128( a, Bhi );
6630   //  ulong2 AhiBlo = __builtin_ia32_pmuludq128( Ahi, b );
6631   //
6632   //  AloBhi = __builtin_ia32_psllqi128( AloBhi, 32 );
6633   //  AhiBlo = __builtin_ia32_psllqi128( AhiBlo, 32 );
6634   //  return AloBlo + AloBhi + AhiBlo;
6635
6636   SDValue A = Op.getOperand(0);
6637   SDValue B = Op.getOperand(1);
6638
6639   SDValue Ahi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
6640                        DAG.getConstant(Intrinsic::x86_sse2_psrli_q, MVT::i32),
6641                        A, DAG.getConstant(32, MVT::i32));
6642   SDValue Bhi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
6643                        DAG.getConstant(Intrinsic::x86_sse2_psrli_q, MVT::i32),
6644                        B, DAG.getConstant(32, MVT::i32));
6645   SDValue AloBlo = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
6646                        DAG.getConstant(Intrinsic::x86_sse2_pmulu_dq, MVT::i32),
6647                        A, B);
6648   SDValue AloBhi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
6649                        DAG.getConstant(Intrinsic::x86_sse2_pmulu_dq, MVT::i32),
6650                        A, Bhi);
6651   SDValue AhiBlo = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
6652                        DAG.getConstant(Intrinsic::x86_sse2_pmulu_dq, MVT::i32),
6653                        Ahi, B);
6654   AloBhi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
6655                        DAG.getConstant(Intrinsic::x86_sse2_pslli_q, MVT::i32),
6656                        AloBhi, DAG.getConstant(32, MVT::i32));
6657   AhiBlo = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
6658                        DAG.getConstant(Intrinsic::x86_sse2_pslli_q, MVT::i32),
6659                        AhiBlo, DAG.getConstant(32, MVT::i32));
6660   SDValue Res = DAG.getNode(ISD::ADD, dl, VT, AloBlo, AloBhi);
6661   Res = DAG.getNode(ISD::ADD, dl, VT, Res, AhiBlo);
6662   return Res;
6663 }
6664
6665
6666 SDValue X86TargetLowering::LowerXALUO(SDValue Op, SelectionDAG &DAG) {
6667   // Lower the "add/sub/mul with overflow" instruction into a regular ins plus
6668   // a "setcc" instruction that checks the overflow flag. The "brcond" lowering
6669   // looks for this combo and may remove the "setcc" instruction if the "setcc"
6670   // has only one use.
6671   SDNode *N = Op.getNode();
6672   SDValue LHS = N->getOperand(0);
6673   SDValue RHS = N->getOperand(1);
6674   unsigned BaseOp = 0;
6675   unsigned Cond = 0;
6676   DebugLoc dl = Op.getDebugLoc();
6677
6678   switch (Op.getOpcode()) {
6679   default: llvm_unreachable("Unknown ovf instruction!");
6680   case ISD::SADDO:
6681     // A subtract of one will be selected as a INC. Note that INC doesn't
6682     // set CF, so we can't do this for UADDO.
6683     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op))
6684       if (C->getAPIntValue() == 1) {
6685         BaseOp = X86ISD::INC;
6686         Cond = X86::COND_O;
6687         break;
6688       }
6689     BaseOp = X86ISD::ADD;
6690     Cond = X86::COND_O;
6691     break;
6692   case ISD::UADDO:
6693     BaseOp = X86ISD::ADD;
6694     Cond = X86::COND_B;
6695     break;
6696   case ISD::SSUBO:
6697     // A subtract of one will be selected as a DEC. Note that DEC doesn't
6698     // set CF, so we can't do this for USUBO.
6699     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op))
6700       if (C->getAPIntValue() == 1) {
6701         BaseOp = X86ISD::DEC;
6702         Cond = X86::COND_O;
6703         break;
6704       }
6705     BaseOp = X86ISD::SUB;
6706     Cond = X86::COND_O;
6707     break;
6708   case ISD::USUBO:
6709     BaseOp = X86ISD::SUB;
6710     Cond = X86::COND_B;
6711     break;
6712   case ISD::SMULO:
6713     BaseOp = X86ISD::SMUL;
6714     Cond = X86::COND_O;
6715     break;
6716   case ISD::UMULO:
6717     BaseOp = X86ISD::UMUL;
6718     Cond = X86::COND_B;
6719     break;
6720   }
6721
6722   // Also sets EFLAGS.
6723   SDVTList VTs = DAG.getVTList(N->getValueType(0), MVT::i32);
6724   SDValue Sum = DAG.getNode(BaseOp, dl, VTs, LHS, RHS);
6725
6726   SDValue SetCC =
6727     DAG.getNode(X86ISD::SETCC, dl, N->getValueType(1),
6728                 DAG.getConstant(Cond, MVT::i32), SDValue(Sum.getNode(), 1));
6729
6730   DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), SetCC);
6731   return Sum;
6732 }
6733
6734 SDValue X86TargetLowering::LowerCMP_SWAP(SDValue Op, SelectionDAG &DAG) {
6735   MVT T = Op.getValueType();
6736   DebugLoc dl = Op.getDebugLoc();
6737   unsigned Reg = 0;
6738   unsigned size = 0;
6739   switch(T.getSimpleVT()) {
6740   default:
6741     assert(false && "Invalid value type!");
6742   case MVT::i8:  Reg = X86::AL;  size = 1; break;
6743   case MVT::i16: Reg = X86::AX;  size = 2; break;
6744   case MVT::i32: Reg = X86::EAX; size = 4; break;
6745   case MVT::i64:
6746     assert(Subtarget->is64Bit() && "Node not type legal!");
6747     Reg = X86::RAX; size = 8;
6748     break;
6749   }
6750   SDValue cpIn = DAG.getCopyToReg(Op.getOperand(0), dl, Reg,
6751                                     Op.getOperand(2), SDValue());
6752   SDValue Ops[] = { cpIn.getValue(0),
6753                     Op.getOperand(1),
6754                     Op.getOperand(3),
6755                     DAG.getTargetConstant(size, MVT::i8),
6756                     cpIn.getValue(1) };
6757   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Flag);
6758   SDValue Result = DAG.getNode(X86ISD::LCMPXCHG_DAG, dl, Tys, Ops, 5);
6759   SDValue cpOut =
6760     DAG.getCopyFromReg(Result.getValue(0), dl, Reg, T, Result.getValue(1));
6761   return cpOut;
6762 }
6763
6764 SDValue X86TargetLowering::LowerREADCYCLECOUNTER(SDValue Op,
6765                                                  SelectionDAG &DAG) {
6766   assert(Subtarget->is64Bit() && "Result not type legalized?");
6767   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Flag);
6768   SDValue TheChain = Op.getOperand(0);
6769   DebugLoc dl = Op.getDebugLoc();
6770   SDValue rd = DAG.getNode(X86ISD::RDTSC_DAG, dl, Tys, &TheChain, 1);
6771   SDValue rax = DAG.getCopyFromReg(rd, dl, X86::RAX, MVT::i64, rd.getValue(1));
6772   SDValue rdx = DAG.getCopyFromReg(rax.getValue(1), dl, X86::RDX, MVT::i64,
6773                                    rax.getValue(2));
6774   SDValue Tmp = DAG.getNode(ISD::SHL, dl, MVT::i64, rdx,
6775                             DAG.getConstant(32, MVT::i8));
6776   SDValue Ops[] = {
6777     DAG.getNode(ISD::OR, dl, MVT::i64, rax, Tmp),
6778     rdx.getValue(1)
6779   };
6780   return DAG.getMergeValues(Ops, 2, dl);
6781 }
6782
6783 SDValue X86TargetLowering::LowerLOAD_SUB(SDValue Op, SelectionDAG &DAG) {
6784   SDNode *Node = Op.getNode();
6785   DebugLoc dl = Node->getDebugLoc();
6786   MVT T = Node->getValueType(0);
6787   SDValue negOp = DAG.getNode(ISD::SUB, dl, T,
6788                               DAG.getConstant(0, T), Node->getOperand(2));
6789   return DAG.getAtomic(ISD::ATOMIC_LOAD_ADD, dl,
6790                        cast<AtomicSDNode>(Node)->getMemoryVT(),
6791                        Node->getOperand(0),
6792                        Node->getOperand(1), negOp,
6793                        cast<AtomicSDNode>(Node)->getSrcValue(),
6794                        cast<AtomicSDNode>(Node)->getAlignment());
6795 }
6796
6797 /// LowerOperation - Provide custom lowering hooks for some operations.
6798 ///
6799 SDValue X86TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) {
6800   switch (Op.getOpcode()) {
6801   default: llvm_unreachable("Should not custom lower this!");
6802   case ISD::ATOMIC_CMP_SWAP:    return LowerCMP_SWAP(Op,DAG);
6803   case ISD::ATOMIC_LOAD_SUB:    return LowerLOAD_SUB(Op,DAG);
6804   case ISD::BUILD_VECTOR:       return LowerBUILD_VECTOR(Op, DAG);
6805   case ISD::VECTOR_SHUFFLE:     return LowerVECTOR_SHUFFLE(Op, DAG);
6806   case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
6807   case ISD::INSERT_VECTOR_ELT:  return LowerINSERT_VECTOR_ELT(Op, DAG);
6808   case ISD::SCALAR_TO_VECTOR:   return LowerSCALAR_TO_VECTOR(Op, DAG);
6809   case ISD::ConstantPool:       return LowerConstantPool(Op, DAG);
6810   case ISD::GlobalAddress:      return LowerGlobalAddress(Op, DAG);
6811   case ISD::GlobalTLSAddress:   return LowerGlobalTLSAddress(Op, DAG);
6812   case ISD::ExternalSymbol:     return LowerExternalSymbol(Op, DAG);
6813   case ISD::SHL_PARTS:
6814   case ISD::SRA_PARTS:
6815   case ISD::SRL_PARTS:          return LowerShift(Op, DAG);
6816   case ISD::SINT_TO_FP:         return LowerSINT_TO_FP(Op, DAG);
6817   case ISD::UINT_TO_FP:         return LowerUINT_TO_FP(Op, DAG);
6818   case ISD::FP_TO_SINT:         return LowerFP_TO_SINT(Op, DAG);
6819   case ISD::FP_TO_UINT:         return LowerFP_TO_UINT(Op, DAG);
6820   case ISD::FABS:               return LowerFABS(Op, DAG);
6821   case ISD::FNEG:               return LowerFNEG(Op, DAG);
6822   case ISD::FCOPYSIGN:          return LowerFCOPYSIGN(Op, DAG);
6823   case ISD::SETCC:              return LowerSETCC(Op, DAG);
6824   case ISD::VSETCC:             return LowerVSETCC(Op, DAG);
6825   case ISD::SELECT:             return LowerSELECT(Op, DAG);
6826   case ISD::BRCOND:             return LowerBRCOND(Op, DAG);
6827   case ISD::JumpTable:          return LowerJumpTable(Op, DAG);
6828   case ISD::CALL:               return LowerCALL(Op, DAG);
6829   case ISD::RET:                return LowerRET(Op, DAG);
6830   case ISD::FORMAL_ARGUMENTS:   return LowerFORMAL_ARGUMENTS(Op, DAG);
6831   case ISD::VASTART:            return LowerVASTART(Op, DAG);
6832   case ISD::VAARG:              return LowerVAARG(Op, DAG);
6833   case ISD::VACOPY:             return LowerVACOPY(Op, DAG);
6834   case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
6835   case ISD::RETURNADDR:         return LowerRETURNADDR(Op, DAG);
6836   case ISD::FRAMEADDR:          return LowerFRAMEADDR(Op, DAG);
6837   case ISD::FRAME_TO_ARGS_OFFSET:
6838                                 return LowerFRAME_TO_ARGS_OFFSET(Op, DAG);
6839   case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG);
6840   case ISD::EH_RETURN:          return LowerEH_RETURN(Op, DAG);
6841   case ISD::TRAMPOLINE:         return LowerTRAMPOLINE(Op, DAG);
6842   case ISD::FLT_ROUNDS_:        return LowerFLT_ROUNDS_(Op, DAG);
6843   case ISD::CTLZ:               return LowerCTLZ(Op, DAG);
6844   case ISD::CTTZ:               return LowerCTTZ(Op, DAG);
6845   case ISD::MUL:                return LowerMUL_V2I64(Op, DAG);
6846   case ISD::SADDO:
6847   case ISD::UADDO:
6848   case ISD::SSUBO:
6849   case ISD::USUBO:
6850   case ISD::SMULO:
6851   case ISD::UMULO:              return LowerXALUO(Op, DAG);
6852   case ISD::READCYCLECOUNTER:   return LowerREADCYCLECOUNTER(Op, DAG);
6853   }
6854 }
6855
6856 void X86TargetLowering::
6857 ReplaceATOMIC_BINARY_64(SDNode *Node, SmallVectorImpl<SDValue>&Results,
6858                         SelectionDAG &DAG, unsigned NewOp) {
6859   MVT T = Node->getValueType(0);
6860   DebugLoc dl = Node->getDebugLoc();
6861   assert (T == MVT::i64 && "Only know how to expand i64 atomics");
6862
6863   SDValue Chain = Node->getOperand(0);
6864   SDValue In1 = Node->getOperand(1);
6865   SDValue In2L = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
6866                              Node->getOperand(2), DAG.getIntPtrConstant(0));
6867   SDValue In2H = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
6868                              Node->getOperand(2), DAG.getIntPtrConstant(1));
6869   // This is a generalized SDNode, not an AtomicSDNode, so it doesn't
6870   // have a MemOperand.  Pass the info through as a normal operand.
6871   SDValue LSI = DAG.getMemOperand(cast<MemSDNode>(Node)->getMemOperand());
6872   SDValue Ops[] = { Chain, In1, In2L, In2H, LSI };
6873   SDVTList Tys = DAG.getVTList(MVT::i32, MVT::i32, MVT::Other);
6874   SDValue Result = DAG.getNode(NewOp, dl, Tys, Ops, 5);
6875   SDValue OpsF[] = { Result.getValue(0), Result.getValue(1)};
6876   Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, OpsF, 2));
6877   Results.push_back(Result.getValue(2));
6878 }
6879
6880 /// ReplaceNodeResults - Replace a node with an illegal result type
6881 /// with a new node built out of custom code.
6882 void X86TargetLowering::ReplaceNodeResults(SDNode *N,
6883                                            SmallVectorImpl<SDValue>&Results,
6884                                            SelectionDAG &DAG) {
6885   DebugLoc dl = N->getDebugLoc();
6886   switch (N->getOpcode()) {
6887   default:
6888     assert(false && "Do not know how to custom type legalize this operation!");
6889     return;
6890   case ISD::FP_TO_SINT: {
6891     std::pair<SDValue,SDValue> Vals =
6892         FP_TO_INTHelper(SDValue(N, 0), DAG, true);
6893     SDValue FIST = Vals.first, StackSlot = Vals.second;
6894     if (FIST.getNode() != 0) {
6895       MVT VT = N->getValueType(0);
6896       // Return a load from the stack slot.
6897       Results.push_back(DAG.getLoad(VT, dl, FIST, StackSlot, NULL, 0));
6898     }
6899     return;
6900   }
6901   case ISD::READCYCLECOUNTER: {
6902     SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Flag);
6903     SDValue TheChain = N->getOperand(0);
6904     SDValue rd = DAG.getNode(X86ISD::RDTSC_DAG, dl, Tys, &TheChain, 1);
6905     SDValue eax = DAG.getCopyFromReg(rd, dl, X86::EAX, MVT::i32,
6906                                      rd.getValue(1));
6907     SDValue edx = DAG.getCopyFromReg(eax.getValue(1), dl, X86::EDX, MVT::i32,
6908                                      eax.getValue(2));
6909     // Use a buildpair to merge the two 32-bit values into a 64-bit one.
6910     SDValue Ops[] = { eax, edx };
6911     Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Ops, 2));
6912     Results.push_back(edx.getValue(1));
6913     return;
6914   }
6915   case ISD::ATOMIC_CMP_SWAP: {
6916     MVT T = N->getValueType(0);
6917     assert (T == MVT::i64 && "Only know how to expand i64 Cmp and Swap");
6918     SDValue cpInL, cpInH;
6919     cpInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(2),
6920                         DAG.getConstant(0, MVT::i32));
6921     cpInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(2),
6922                         DAG.getConstant(1, MVT::i32));
6923     cpInL = DAG.getCopyToReg(N->getOperand(0), dl, X86::EAX, cpInL, SDValue());
6924     cpInH = DAG.getCopyToReg(cpInL.getValue(0), dl, X86::EDX, cpInH,
6925                              cpInL.getValue(1));
6926     SDValue swapInL, swapInH;
6927     swapInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(3),
6928                           DAG.getConstant(0, MVT::i32));
6929     swapInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(3),
6930                           DAG.getConstant(1, MVT::i32));
6931     swapInL = DAG.getCopyToReg(cpInH.getValue(0), dl, X86::EBX, swapInL,
6932                                cpInH.getValue(1));
6933     swapInH = DAG.getCopyToReg(swapInL.getValue(0), dl, X86::ECX, swapInH,
6934                                swapInL.getValue(1));
6935     SDValue Ops[] = { swapInH.getValue(0),
6936                       N->getOperand(1),
6937                       swapInH.getValue(1) };
6938     SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Flag);
6939     SDValue Result = DAG.getNode(X86ISD::LCMPXCHG8_DAG, dl, Tys, Ops, 3);
6940     SDValue cpOutL = DAG.getCopyFromReg(Result.getValue(0), dl, X86::EAX,
6941                                         MVT::i32, Result.getValue(1));
6942     SDValue cpOutH = DAG.getCopyFromReg(cpOutL.getValue(1), dl, X86::EDX,
6943                                         MVT::i32, cpOutL.getValue(2));
6944     SDValue OpsF[] = { cpOutL.getValue(0), cpOutH.getValue(0)};
6945     Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, OpsF, 2));
6946     Results.push_back(cpOutH.getValue(1));
6947     return;
6948   }
6949   case ISD::ATOMIC_LOAD_ADD:
6950     ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMADD64_DAG);
6951     return;
6952   case ISD::ATOMIC_LOAD_AND:
6953     ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMAND64_DAG);
6954     return;
6955   case ISD::ATOMIC_LOAD_NAND:
6956     ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMNAND64_DAG);
6957     return;
6958   case ISD::ATOMIC_LOAD_OR:
6959     ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMOR64_DAG);
6960     return;
6961   case ISD::ATOMIC_LOAD_SUB:
6962     ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMSUB64_DAG);
6963     return;
6964   case ISD::ATOMIC_LOAD_XOR:
6965     ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMXOR64_DAG);
6966     return;
6967   case ISD::ATOMIC_SWAP:
6968     ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMSWAP64_DAG);
6969     return;
6970   }
6971 }
6972
6973 const char *X86TargetLowering::getTargetNodeName(unsigned Opcode) const {
6974   switch (Opcode) {
6975   default: return NULL;
6976   case X86ISD::BSF:                return "X86ISD::BSF";
6977   case X86ISD::BSR:                return "X86ISD::BSR";
6978   case X86ISD::SHLD:               return "X86ISD::SHLD";
6979   case X86ISD::SHRD:               return "X86ISD::SHRD";
6980   case X86ISD::FAND:               return "X86ISD::FAND";
6981   case X86ISD::FOR:                return "X86ISD::FOR";
6982   case X86ISD::FXOR:               return "X86ISD::FXOR";
6983   case X86ISD::FSRL:               return "X86ISD::FSRL";
6984   case X86ISD::FILD:               return "X86ISD::FILD";
6985   case X86ISD::FILD_FLAG:          return "X86ISD::FILD_FLAG";
6986   case X86ISD::FP_TO_INT16_IN_MEM: return "X86ISD::FP_TO_INT16_IN_MEM";
6987   case X86ISD::FP_TO_INT32_IN_MEM: return "X86ISD::FP_TO_INT32_IN_MEM";
6988   case X86ISD::FP_TO_INT64_IN_MEM: return "X86ISD::FP_TO_INT64_IN_MEM";
6989   case X86ISD::FLD:                return "X86ISD::FLD";
6990   case X86ISD::FST:                return "X86ISD::FST";
6991   case X86ISD::CALL:               return "X86ISD::CALL";
6992   case X86ISD::TAILCALL:           return "X86ISD::TAILCALL";
6993   case X86ISD::RDTSC_DAG:          return "X86ISD::RDTSC_DAG";
6994   case X86ISD::BT:                 return "X86ISD::BT";
6995   case X86ISD::CMP:                return "X86ISD::CMP";
6996   case X86ISD::COMI:               return "X86ISD::COMI";
6997   case X86ISD::UCOMI:              return "X86ISD::UCOMI";
6998   case X86ISD::SETCC:              return "X86ISD::SETCC";
6999   case X86ISD::CMOV:               return "X86ISD::CMOV";
7000   case X86ISD::BRCOND:             return "X86ISD::BRCOND";
7001   case X86ISD::RET_FLAG:           return "X86ISD::RET_FLAG";
7002   case X86ISD::REP_STOS:           return "X86ISD::REP_STOS";
7003   case X86ISD::REP_MOVS:           return "X86ISD::REP_MOVS";
7004   case X86ISD::GlobalBaseReg:      return "X86ISD::GlobalBaseReg";
7005   case X86ISD::Wrapper:            return "X86ISD::Wrapper";
7006   case X86ISD::WrapperRIP:         return "X86ISD::WrapperRIP";
7007   case X86ISD::PEXTRB:             return "X86ISD::PEXTRB";
7008   case X86ISD::PEXTRW:             return "X86ISD::PEXTRW";
7009   case X86ISD::INSERTPS:           return "X86ISD::INSERTPS";
7010   case X86ISD::PINSRB:             return "X86ISD::PINSRB";
7011   case X86ISD::PINSRW:             return "X86ISD::PINSRW";
7012   case X86ISD::PSHUFB:             return "X86ISD::PSHUFB";
7013   case X86ISD::FMAX:               return "X86ISD::FMAX";
7014   case X86ISD::FMIN:               return "X86ISD::FMIN";
7015   case X86ISD::FRSQRT:             return "X86ISD::FRSQRT";
7016   case X86ISD::FRCP:               return "X86ISD::FRCP";
7017   case X86ISD::TLSADDR:            return "X86ISD::TLSADDR";
7018   case X86ISD::SegmentBaseAddress: return "X86ISD::SegmentBaseAddress";
7019   case X86ISD::EH_RETURN:          return "X86ISD::EH_RETURN";
7020   case X86ISD::TC_RETURN:          return "X86ISD::TC_RETURN";
7021   case X86ISD::FNSTCW16m:          return "X86ISD::FNSTCW16m";
7022   case X86ISD::LCMPXCHG_DAG:       return "X86ISD::LCMPXCHG_DAG";
7023   case X86ISD::LCMPXCHG8_DAG:      return "X86ISD::LCMPXCHG8_DAG";
7024   case X86ISD::ATOMADD64_DAG:      return "X86ISD::ATOMADD64_DAG";
7025   case X86ISD::ATOMSUB64_DAG:      return "X86ISD::ATOMSUB64_DAG";
7026   case X86ISD::ATOMOR64_DAG:       return "X86ISD::ATOMOR64_DAG";
7027   case X86ISD::ATOMXOR64_DAG:      return "X86ISD::ATOMXOR64_DAG";
7028   case X86ISD::ATOMAND64_DAG:      return "X86ISD::ATOMAND64_DAG";
7029   case X86ISD::ATOMNAND64_DAG:     return "X86ISD::ATOMNAND64_DAG";
7030   case X86ISD::VZEXT_MOVL:         return "X86ISD::VZEXT_MOVL";
7031   case X86ISD::VZEXT_LOAD:         return "X86ISD::VZEXT_LOAD";
7032   case X86ISD::VSHL:               return "X86ISD::VSHL";
7033   case X86ISD::VSRL:               return "X86ISD::VSRL";
7034   case X86ISD::CMPPD:              return "X86ISD::CMPPD";
7035   case X86ISD::CMPPS:              return "X86ISD::CMPPS";
7036   case X86ISD::PCMPEQB:            return "X86ISD::PCMPEQB";
7037   case X86ISD::PCMPEQW:            return "X86ISD::PCMPEQW";
7038   case X86ISD::PCMPEQD:            return "X86ISD::PCMPEQD";
7039   case X86ISD::PCMPEQQ:            return "X86ISD::PCMPEQQ";
7040   case X86ISD::PCMPGTB:            return "X86ISD::PCMPGTB";
7041   case X86ISD::PCMPGTW:            return "X86ISD::PCMPGTW";
7042   case X86ISD::PCMPGTD:            return "X86ISD::PCMPGTD";
7043   case X86ISD::PCMPGTQ:            return "X86ISD::PCMPGTQ";
7044   case X86ISD::ADD:                return "X86ISD::ADD";
7045   case X86ISD::SUB:                return "X86ISD::SUB";
7046   case X86ISD::SMUL:               return "X86ISD::SMUL";
7047   case X86ISD::UMUL:               return "X86ISD::UMUL";
7048   case X86ISD::INC:                return "X86ISD::INC";
7049   case X86ISD::DEC:                return "X86ISD::DEC";
7050   case X86ISD::MUL_IMM:            return "X86ISD::MUL_IMM";
7051   }
7052 }
7053
7054 // isLegalAddressingMode - Return true if the addressing mode represented
7055 // by AM is legal for this target, for a load/store of the specified type.
7056 bool X86TargetLowering::isLegalAddressingMode(const AddrMode &AM,
7057                                               const Type *Ty) const {
7058   // X86 supports extremely general addressing modes.
7059
7060   // X86 allows a sign-extended 32-bit immediate field as a displacement.
7061   if (AM.BaseOffs <= -(1LL << 32) || AM.BaseOffs >= (1LL << 32)-1)
7062     return false;
7063
7064   if (AM.BaseGV) {
7065     unsigned GVFlags =
7066       Subtarget->ClassifyGlobalReference(AM.BaseGV, getTargetMachine());
7067     
7068     // If a reference to this global requires an extra load, we can't fold it.
7069     if (isGlobalStubReference(GVFlags))
7070       return false;
7071     
7072     // If BaseGV requires a register for the PIC base, we cannot also have a
7073     // BaseReg specified.
7074     if (AM.HasBaseReg && isGlobalRelativeToPICBase(GVFlags))
7075       return false;
7076
7077     // X86-64 only supports addr of globals in small code model.
7078     if (Subtarget->is64Bit()) {
7079       if (getTargetMachine().getCodeModel() != CodeModel::Small)
7080         return false;
7081       // If lower 4G is not available, then we must use rip-relative addressing.
7082       if (AM.BaseOffs || AM.Scale > 1)
7083         return false;
7084     }
7085   }
7086
7087   switch (AM.Scale) {
7088   case 0:
7089   case 1:
7090   case 2:
7091   case 4:
7092   case 8:
7093     // These scales always work.
7094     break;
7095   case 3:
7096   case 5:
7097   case 9:
7098     // These scales are formed with basereg+scalereg.  Only accept if there is
7099     // no basereg yet.
7100     if (AM.HasBaseReg)
7101       return false;
7102     break;
7103   default:  // Other stuff never works.
7104     return false;
7105   }
7106
7107   return true;
7108 }
7109
7110
7111 bool X86TargetLowering::isTruncateFree(const Type *Ty1, const Type *Ty2) const {
7112   if (!Ty1->isInteger() || !Ty2->isInteger())
7113     return false;
7114   unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
7115   unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
7116   if (NumBits1 <= NumBits2)
7117     return false;
7118   return Subtarget->is64Bit() || NumBits1 < 64;
7119 }
7120
7121 bool X86TargetLowering::isTruncateFree(MVT VT1, MVT VT2) const {
7122   if (!VT1.isInteger() || !VT2.isInteger())
7123     return false;
7124   unsigned NumBits1 = VT1.getSizeInBits();
7125   unsigned NumBits2 = VT2.getSizeInBits();
7126   if (NumBits1 <= NumBits2)
7127     return false;
7128   return Subtarget->is64Bit() || NumBits1 < 64;
7129 }
7130
7131 bool X86TargetLowering::isZExtFree(const Type *Ty1, const Type *Ty2) const {
7132   // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
7133   return Ty1 == Type::Int32Ty && Ty2 == Type::Int64Ty && Subtarget->is64Bit();
7134 }
7135
7136 bool X86TargetLowering::isZExtFree(MVT VT1, MVT VT2) const {
7137   // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
7138   return VT1 == MVT::i32 && VT2 == MVT::i64 && Subtarget->is64Bit();
7139 }
7140
7141 bool X86TargetLowering::isNarrowingProfitable(MVT VT1, MVT VT2) const {
7142   // i16 instructions are longer (0x66 prefix) and potentially slower.
7143   return !(VT1 == MVT::i32 && VT2 == MVT::i16);
7144 }
7145
7146 /// isShuffleMaskLegal - Targets can use this to indicate that they only
7147 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
7148 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
7149 /// are assumed to be legal.
7150 bool
7151 X86TargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M, 
7152                                       MVT VT) const {
7153   // Only do shuffles on 128-bit vector types for now.
7154   if (VT.getSizeInBits() == 64)
7155     return false;
7156
7157   // FIXME: pshufb, blends, palignr, shifts.
7158   return (VT.getVectorNumElements() == 2 ||
7159           ShuffleVectorSDNode::isSplatMask(&M[0], VT) ||
7160           isMOVLMask(M, VT) ||
7161           isSHUFPMask(M, VT) ||
7162           isPSHUFDMask(M, VT) ||
7163           isPSHUFHWMask(M, VT) ||
7164           isPSHUFLWMask(M, VT) ||
7165           isUNPCKLMask(M, VT) ||
7166           isUNPCKHMask(M, VT) ||
7167           isUNPCKL_v_undef_Mask(M, VT) ||
7168           isUNPCKH_v_undef_Mask(M, VT));
7169 }
7170
7171 bool
7172 X86TargetLowering::isVectorClearMaskLegal(const SmallVectorImpl<int> &Mask,
7173                                           MVT VT) const {
7174   unsigned NumElts = VT.getVectorNumElements();
7175   // FIXME: This collection of masks seems suspect.
7176   if (NumElts == 2)
7177     return true;
7178   if (NumElts == 4 && VT.getSizeInBits() == 128) {
7179     return (isMOVLMask(Mask, VT)  ||
7180             isCommutedMOVLMask(Mask, VT, true) ||
7181             isSHUFPMask(Mask, VT) ||
7182             isCommutedSHUFPMask(Mask, VT));
7183   }
7184   return false;
7185 }
7186
7187 //===----------------------------------------------------------------------===//
7188 //                           X86 Scheduler Hooks
7189 //===----------------------------------------------------------------------===//
7190
7191 // private utility function
7192 MachineBasicBlock *
7193 X86TargetLowering::EmitAtomicBitwiseWithCustomInserter(MachineInstr *bInstr,
7194                                                        MachineBasicBlock *MBB,
7195                                                        unsigned regOpc,
7196                                                        unsigned immOpc,
7197                                                        unsigned LoadOpc,
7198                                                        unsigned CXchgOpc,
7199                                                        unsigned copyOpc,
7200                                                        unsigned notOpc,
7201                                                        unsigned EAXreg,
7202                                                        TargetRegisterClass *RC,
7203                                                        bool invSrc) const {
7204   // For the atomic bitwise operator, we generate
7205   //   thisMBB:
7206   //   newMBB:
7207   //     ld  t1 = [bitinstr.addr]
7208   //     op  t2 = t1, [bitinstr.val]
7209   //     mov EAX = t1
7210   //     lcs dest = [bitinstr.addr], t2  [EAX is implicit]
7211   //     bz  newMBB
7212   //     fallthrough -->nextMBB
7213   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
7214   const BasicBlock *LLVM_BB = MBB->getBasicBlock();
7215   MachineFunction::iterator MBBIter = MBB;
7216   ++MBBIter;
7217
7218   /// First build the CFG
7219   MachineFunction *F = MBB->getParent();
7220   MachineBasicBlock *thisMBB = MBB;
7221   MachineBasicBlock *newMBB = F->CreateMachineBasicBlock(LLVM_BB);
7222   MachineBasicBlock *nextMBB = F->CreateMachineBasicBlock(LLVM_BB);
7223   F->insert(MBBIter, newMBB);
7224   F->insert(MBBIter, nextMBB);
7225
7226   // Move all successors to thisMBB to nextMBB
7227   nextMBB->transferSuccessors(thisMBB);
7228
7229   // Update thisMBB to fall through to newMBB
7230   thisMBB->addSuccessor(newMBB);
7231
7232   // newMBB jumps to itself and fall through to nextMBB
7233   newMBB->addSuccessor(nextMBB);
7234   newMBB->addSuccessor(newMBB);
7235
7236   // Insert instructions into newMBB based on incoming instruction
7237   assert(bInstr->getNumOperands() < X86AddrNumOperands + 4 &&
7238          "unexpected number of operands");
7239   DebugLoc dl = bInstr->getDebugLoc();
7240   MachineOperand& destOper = bInstr->getOperand(0);
7241   MachineOperand* argOpers[2 + X86AddrNumOperands];
7242   int numArgs = bInstr->getNumOperands() - 1;
7243   for (int i=0; i < numArgs; ++i)
7244     argOpers[i] = &bInstr->getOperand(i+1);
7245
7246   // x86 address has 4 operands: base, index, scale, and displacement
7247   int lastAddrIndx = X86AddrNumOperands - 1; // [0,3]
7248   int valArgIndx = lastAddrIndx + 1;
7249
7250   unsigned t1 = F->getRegInfo().createVirtualRegister(RC);
7251   MachineInstrBuilder MIB = BuildMI(newMBB, dl, TII->get(LoadOpc), t1);
7252   for (int i=0; i <= lastAddrIndx; ++i)
7253     (*MIB).addOperand(*argOpers[i]);
7254
7255   unsigned tt = F->getRegInfo().createVirtualRegister(RC);
7256   if (invSrc) {
7257     MIB = BuildMI(newMBB, dl, TII->get(notOpc), tt).addReg(t1);
7258   }
7259   else
7260     tt = t1;
7261
7262   unsigned t2 = F->getRegInfo().createVirtualRegister(RC);
7263   assert((argOpers[valArgIndx]->isReg() ||
7264           argOpers[valArgIndx]->isImm()) &&
7265          "invalid operand");
7266   if (argOpers[valArgIndx]->isReg())
7267     MIB = BuildMI(newMBB, dl, TII->get(regOpc), t2);
7268   else
7269     MIB = BuildMI(newMBB, dl, TII->get(immOpc), t2);
7270   MIB.addReg(tt);
7271   (*MIB).addOperand(*argOpers[valArgIndx]);
7272
7273   MIB = BuildMI(newMBB, dl, TII->get(copyOpc), EAXreg);
7274   MIB.addReg(t1);
7275
7276   MIB = BuildMI(newMBB, dl, TII->get(CXchgOpc));
7277   for (int i=0; i <= lastAddrIndx; ++i)
7278     (*MIB).addOperand(*argOpers[i]);
7279   MIB.addReg(t2);
7280   assert(bInstr->hasOneMemOperand() && "Unexpected number of memoperand");
7281   (*MIB).addMemOperand(*F, *bInstr->memoperands_begin());
7282
7283   MIB = BuildMI(newMBB, dl, TII->get(copyOpc), destOper.getReg());
7284   MIB.addReg(EAXreg);
7285
7286   // insert branch
7287   BuildMI(newMBB, dl, TII->get(X86::JNE)).addMBB(newMBB);
7288
7289   F->DeleteMachineInstr(bInstr);   // The pseudo instruction is gone now.
7290   return nextMBB;
7291 }
7292
7293 // private utility function:  64 bit atomics on 32 bit host.
7294 MachineBasicBlock *
7295 X86TargetLowering::EmitAtomicBit6432WithCustomInserter(MachineInstr *bInstr,
7296                                                        MachineBasicBlock *MBB,
7297                                                        unsigned regOpcL,
7298                                                        unsigned regOpcH,
7299                                                        unsigned immOpcL,
7300                                                        unsigned immOpcH,
7301                                                        bool invSrc) const {
7302   // For the atomic bitwise operator, we generate
7303   //   thisMBB (instructions are in pairs, except cmpxchg8b)
7304   //     ld t1,t2 = [bitinstr.addr]
7305   //   newMBB:
7306   //     out1, out2 = phi (thisMBB, t1/t2) (newMBB, t3/t4)
7307   //     op  t5, t6 <- out1, out2, [bitinstr.val]
7308   //      (for SWAP, substitute:  mov t5, t6 <- [bitinstr.val])
7309   //     mov ECX, EBX <- t5, t6
7310   //     mov EAX, EDX <- t1, t2
7311   //     cmpxchg8b [bitinstr.addr]  [EAX, EDX, EBX, ECX implicit]
7312   //     mov t3, t4 <- EAX, EDX
7313   //     bz  newMBB
7314   //     result in out1, out2
7315   //     fallthrough -->nextMBB
7316
7317   const TargetRegisterClass *RC = X86::GR32RegisterClass;
7318   const unsigned LoadOpc = X86::MOV32rm;
7319   const unsigned copyOpc = X86::MOV32rr;
7320   const unsigned NotOpc = X86::NOT32r;
7321   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
7322   const BasicBlock *LLVM_BB = MBB->getBasicBlock();
7323   MachineFunction::iterator MBBIter = MBB;
7324   ++MBBIter;
7325
7326   /// First build the CFG
7327   MachineFunction *F = MBB->getParent();
7328   MachineBasicBlock *thisMBB = MBB;
7329   MachineBasicBlock *newMBB = F->CreateMachineBasicBlock(LLVM_BB);
7330   MachineBasicBlock *nextMBB = F->CreateMachineBasicBlock(LLVM_BB);
7331   F->insert(MBBIter, newMBB);
7332   F->insert(MBBIter, nextMBB);
7333
7334   // Move all successors to thisMBB to nextMBB
7335   nextMBB->transferSuccessors(thisMBB);
7336
7337   // Update thisMBB to fall through to newMBB
7338   thisMBB->addSuccessor(newMBB);
7339
7340   // newMBB jumps to itself and fall through to nextMBB
7341   newMBB->addSuccessor(nextMBB);
7342   newMBB->addSuccessor(newMBB);
7343
7344   DebugLoc dl = bInstr->getDebugLoc();
7345   // Insert instructions into newMBB based on incoming instruction
7346   // There are 8 "real" operands plus 9 implicit def/uses, ignored here.
7347   assert(bInstr->getNumOperands() < X86AddrNumOperands + 14 &&
7348          "unexpected number of operands");
7349   MachineOperand& dest1Oper = bInstr->getOperand(0);
7350   MachineOperand& dest2Oper = bInstr->getOperand(1);
7351   MachineOperand* argOpers[2 + X86AddrNumOperands];
7352   for (int i=0; i < 2 + X86AddrNumOperands; ++i)
7353     argOpers[i] = &bInstr->getOperand(i+2);
7354
7355   // x86 address has 4 operands: base, index, scale, and displacement
7356   int lastAddrIndx = X86AddrNumOperands - 1; // [0,3]
7357
7358   unsigned t1 = F->getRegInfo().createVirtualRegister(RC);
7359   MachineInstrBuilder MIB = BuildMI(thisMBB, dl, TII->get(LoadOpc), t1);
7360   for (int i=0; i <= lastAddrIndx; ++i)
7361     (*MIB).addOperand(*argOpers[i]);
7362   unsigned t2 = F->getRegInfo().createVirtualRegister(RC);
7363   MIB = BuildMI(thisMBB, dl, TII->get(LoadOpc), t2);
7364   // add 4 to displacement.
7365   for (int i=0; i <= lastAddrIndx-2; ++i)
7366     (*MIB).addOperand(*argOpers[i]);
7367   MachineOperand newOp3 = *(argOpers[3]);
7368   if (newOp3.isImm())
7369     newOp3.setImm(newOp3.getImm()+4);
7370   else
7371     newOp3.setOffset(newOp3.getOffset()+4);
7372   (*MIB).addOperand(newOp3);
7373   (*MIB).addOperand(*argOpers[lastAddrIndx]);
7374
7375   // t3/4 are defined later, at the bottom of the loop
7376   unsigned t3 = F->getRegInfo().createVirtualRegister(RC);
7377   unsigned t4 = F->getRegInfo().createVirtualRegister(RC);
7378   BuildMI(newMBB, dl, TII->get(X86::PHI), dest1Oper.getReg())
7379     .addReg(t1).addMBB(thisMBB).addReg(t3).addMBB(newMBB);
7380   BuildMI(newMBB, dl, TII->get(X86::PHI), dest2Oper.getReg())
7381     .addReg(t2).addMBB(thisMBB).addReg(t4).addMBB(newMBB);
7382
7383   unsigned tt1 = F->getRegInfo().createVirtualRegister(RC);
7384   unsigned tt2 = F->getRegInfo().createVirtualRegister(RC);
7385   if (invSrc) {
7386     MIB = BuildMI(newMBB, dl, TII->get(NotOpc), tt1).addReg(t1);
7387     MIB = BuildMI(newMBB, dl, TII->get(NotOpc), tt2).addReg(t2);
7388   } else {
7389     tt1 = t1;
7390     tt2 = t2;
7391   }
7392
7393   int valArgIndx = lastAddrIndx + 1;
7394   assert((argOpers[valArgIndx]->isReg() ||
7395           argOpers[valArgIndx]->isImm()) &&
7396          "invalid operand");
7397   unsigned t5 = F->getRegInfo().createVirtualRegister(RC);
7398   unsigned t6 = F->getRegInfo().createVirtualRegister(RC);
7399   if (argOpers[valArgIndx]->isReg())
7400     MIB = BuildMI(newMBB, dl, TII->get(regOpcL), t5);
7401   else
7402     MIB = BuildMI(newMBB, dl, TII->get(immOpcL), t5);
7403   if (regOpcL != X86::MOV32rr)
7404     MIB.addReg(tt1);
7405   (*MIB).addOperand(*argOpers[valArgIndx]);
7406   assert(argOpers[valArgIndx + 1]->isReg() ==
7407          argOpers[valArgIndx]->isReg());
7408   assert(argOpers[valArgIndx + 1]->isImm() ==
7409          argOpers[valArgIndx]->isImm());
7410   if (argOpers[valArgIndx + 1]->isReg())
7411     MIB = BuildMI(newMBB, dl, TII->get(regOpcH), t6);
7412   else
7413     MIB = BuildMI(newMBB, dl, TII->get(immOpcH), t6);
7414   if (regOpcH != X86::MOV32rr)
7415     MIB.addReg(tt2);
7416   (*MIB).addOperand(*argOpers[valArgIndx + 1]);
7417
7418   MIB = BuildMI(newMBB, dl, TII->get(copyOpc), X86::EAX);
7419   MIB.addReg(t1);
7420   MIB = BuildMI(newMBB, dl, TII->get(copyOpc), X86::EDX);
7421   MIB.addReg(t2);
7422
7423   MIB = BuildMI(newMBB, dl, TII->get(copyOpc), X86::EBX);
7424   MIB.addReg(t5);
7425   MIB = BuildMI(newMBB, dl, TII->get(copyOpc), X86::ECX);
7426   MIB.addReg(t6);
7427
7428   MIB = BuildMI(newMBB, dl, TII->get(X86::LCMPXCHG8B));
7429   for (int i=0; i <= lastAddrIndx; ++i)
7430     (*MIB).addOperand(*argOpers[i]);
7431
7432   assert(bInstr->hasOneMemOperand() && "Unexpected number of memoperand");
7433   (*MIB).addMemOperand(*F, *bInstr->memoperands_begin());
7434
7435   MIB = BuildMI(newMBB, dl, TII->get(copyOpc), t3);
7436   MIB.addReg(X86::EAX);
7437   MIB = BuildMI(newMBB, dl, TII->get(copyOpc), t4);
7438   MIB.addReg(X86::EDX);
7439
7440   // insert branch
7441   BuildMI(newMBB, dl, TII->get(X86::JNE)).addMBB(newMBB);
7442
7443   F->DeleteMachineInstr(bInstr);   // The pseudo instruction is gone now.
7444   return nextMBB;
7445 }
7446
7447 // private utility function
7448 MachineBasicBlock *
7449 X86TargetLowering::EmitAtomicMinMaxWithCustomInserter(MachineInstr *mInstr,
7450                                                       MachineBasicBlock *MBB,
7451                                                       unsigned cmovOpc) const {
7452   // For the atomic min/max operator, we generate
7453   //   thisMBB:
7454   //   newMBB:
7455   //     ld t1 = [min/max.addr]
7456   //     mov t2 = [min/max.val]
7457   //     cmp  t1, t2
7458   //     cmov[cond] t2 = t1
7459   //     mov EAX = t1
7460   //     lcs dest = [bitinstr.addr], t2  [EAX is implicit]
7461   //     bz   newMBB
7462   //     fallthrough -->nextMBB
7463   //
7464   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
7465   const BasicBlock *LLVM_BB = MBB->getBasicBlock();
7466   MachineFunction::iterator MBBIter = MBB;
7467   ++MBBIter;
7468
7469   /// First build the CFG
7470   MachineFunction *F = MBB->getParent();
7471   MachineBasicBlock *thisMBB = MBB;
7472   MachineBasicBlock *newMBB = F->CreateMachineBasicBlock(LLVM_BB);
7473   MachineBasicBlock *nextMBB = F->CreateMachineBasicBlock(LLVM_BB);
7474   F->insert(MBBIter, newMBB);
7475   F->insert(MBBIter, nextMBB);
7476
7477   // Move all successors to thisMBB to nextMBB
7478   nextMBB->transferSuccessors(thisMBB);
7479
7480   // Update thisMBB to fall through to newMBB
7481   thisMBB->addSuccessor(newMBB);
7482
7483   // newMBB jumps to newMBB and fall through to nextMBB
7484   newMBB->addSuccessor(nextMBB);
7485   newMBB->addSuccessor(newMBB);
7486
7487   DebugLoc dl = mInstr->getDebugLoc();
7488   // Insert instructions into newMBB based on incoming instruction
7489   assert(mInstr->getNumOperands() < X86AddrNumOperands + 4 &&
7490          "unexpected number of operands");
7491   MachineOperand& destOper = mInstr->getOperand(0);
7492   MachineOperand* argOpers[2 + X86AddrNumOperands];
7493   int numArgs = mInstr->getNumOperands() - 1;
7494   for (int i=0; i < numArgs; ++i)
7495     argOpers[i] = &mInstr->getOperand(i+1);
7496
7497   // x86 address has 4 operands: base, index, scale, and displacement
7498   int lastAddrIndx = X86AddrNumOperands - 1; // [0,3]
7499   int valArgIndx = lastAddrIndx + 1;
7500
7501   unsigned t1 = F->getRegInfo().createVirtualRegister(X86::GR32RegisterClass);
7502   MachineInstrBuilder MIB = BuildMI(newMBB, dl, TII->get(X86::MOV32rm), t1);
7503   for (int i=0; i <= lastAddrIndx; ++i)
7504     (*MIB).addOperand(*argOpers[i]);
7505
7506   // We only support register and immediate values
7507   assert((argOpers[valArgIndx]->isReg() ||
7508           argOpers[valArgIndx]->isImm()) &&
7509          "invalid operand");
7510
7511   unsigned t2 = F->getRegInfo().createVirtualRegister(X86::GR32RegisterClass);
7512   if (argOpers[valArgIndx]->isReg())
7513     MIB = BuildMI(newMBB, dl, TII->get(X86::MOV32rr), t2);
7514   else
7515     MIB = BuildMI(newMBB, dl, TII->get(X86::MOV32rr), t2);
7516   (*MIB).addOperand(*argOpers[valArgIndx]);
7517
7518   MIB = BuildMI(newMBB, dl, TII->get(X86::MOV32rr), X86::EAX);
7519   MIB.addReg(t1);
7520
7521   MIB = BuildMI(newMBB, dl, TII->get(X86::CMP32rr));
7522   MIB.addReg(t1);
7523   MIB.addReg(t2);
7524
7525   // Generate movc
7526   unsigned t3 = F->getRegInfo().createVirtualRegister(X86::GR32RegisterClass);
7527   MIB = BuildMI(newMBB, dl, TII->get(cmovOpc),t3);
7528   MIB.addReg(t2);
7529   MIB.addReg(t1);
7530
7531   // Cmp and exchange if none has modified the memory location
7532   MIB = BuildMI(newMBB, dl, TII->get(X86::LCMPXCHG32));
7533   for (int i=0; i <= lastAddrIndx; ++i)
7534     (*MIB).addOperand(*argOpers[i]);
7535   MIB.addReg(t3);
7536   assert(mInstr->hasOneMemOperand() && "Unexpected number of memoperand");
7537   (*MIB).addMemOperand(*F, *mInstr->memoperands_begin());
7538
7539   MIB = BuildMI(newMBB, dl, TII->get(X86::MOV32rr), destOper.getReg());
7540   MIB.addReg(X86::EAX);
7541
7542   // insert branch
7543   BuildMI(newMBB, dl, TII->get(X86::JNE)).addMBB(newMBB);
7544
7545   F->DeleteMachineInstr(mInstr);   // The pseudo instruction is gone now.
7546   return nextMBB;
7547 }
7548
7549
7550 MachineBasicBlock *
7551 X86TargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
7552                                                MachineBasicBlock *BB) const {
7553   DebugLoc dl = MI->getDebugLoc();
7554   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
7555   switch (MI->getOpcode()) {
7556   default: assert(false && "Unexpected instr type to insert");
7557   case X86::CMOV_V1I64:
7558   case X86::CMOV_FR32:
7559   case X86::CMOV_FR64:
7560   case X86::CMOV_V4F32:
7561   case X86::CMOV_V2F64:
7562   case X86::CMOV_V2I64: {
7563     // To "insert" a SELECT_CC instruction, we actually have to insert the
7564     // diamond control-flow pattern.  The incoming instruction knows the
7565     // destination vreg to set, the condition code register to branch on, the
7566     // true/false values to select between, and a branch opcode to use.
7567     const BasicBlock *LLVM_BB = BB->getBasicBlock();
7568     MachineFunction::iterator It = BB;
7569     ++It;
7570
7571     //  thisMBB:
7572     //  ...
7573     //   TrueVal = ...
7574     //   cmpTY ccX, r1, r2
7575     //   bCC copy1MBB
7576     //   fallthrough --> copy0MBB
7577     MachineBasicBlock *thisMBB = BB;
7578     MachineFunction *F = BB->getParent();
7579     MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
7580     MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
7581     unsigned Opc =
7582       X86::GetCondBranchFromCond((X86::CondCode)MI->getOperand(3).getImm());
7583     BuildMI(BB, dl, TII->get(Opc)).addMBB(sinkMBB);
7584     F->insert(It, copy0MBB);
7585     F->insert(It, sinkMBB);
7586     // Update machine-CFG edges by transferring all successors of the current
7587     // block to the new block which will contain the Phi node for the select.
7588     sinkMBB->transferSuccessors(BB);
7589
7590     // Add the true and fallthrough blocks as its successors.
7591     BB->addSuccessor(copy0MBB);
7592     BB->addSuccessor(sinkMBB);
7593
7594     //  copy0MBB:
7595     //   %FalseValue = ...
7596     //   # fallthrough to sinkMBB
7597     BB = copy0MBB;
7598
7599     // Update machine-CFG edges
7600     BB->addSuccessor(sinkMBB);
7601
7602     //  sinkMBB:
7603     //   %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
7604     //  ...
7605     BB = sinkMBB;
7606     BuildMI(BB, dl, TII->get(X86::PHI), MI->getOperand(0).getReg())
7607       .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB)
7608       .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
7609
7610     F->DeleteMachineInstr(MI);   // The pseudo instruction is gone now.
7611     return BB;
7612   }
7613
7614   case X86::FP32_TO_INT16_IN_MEM:
7615   case X86::FP32_TO_INT32_IN_MEM:
7616   case X86::FP32_TO_INT64_IN_MEM:
7617   case X86::FP64_TO_INT16_IN_MEM:
7618   case X86::FP64_TO_INT32_IN_MEM:
7619   case X86::FP64_TO_INT64_IN_MEM:
7620   case X86::FP80_TO_INT16_IN_MEM:
7621   case X86::FP80_TO_INT32_IN_MEM:
7622   case X86::FP80_TO_INT64_IN_MEM: {
7623     // Change the floating point control register to use "round towards zero"
7624     // mode when truncating to an integer value.
7625     MachineFunction *F = BB->getParent();
7626     int CWFrameIdx = F->getFrameInfo()->CreateStackObject(2, 2);
7627     addFrameReference(BuildMI(BB, dl, TII->get(X86::FNSTCW16m)), CWFrameIdx);
7628
7629     // Load the old value of the high byte of the control word...
7630     unsigned OldCW =
7631       F->getRegInfo().createVirtualRegister(X86::GR16RegisterClass);
7632     addFrameReference(BuildMI(BB, dl, TII->get(X86::MOV16rm), OldCW),
7633                       CWFrameIdx);
7634
7635     // Set the high part to be round to zero...
7636     addFrameReference(BuildMI(BB, dl, TII->get(X86::MOV16mi)), CWFrameIdx)
7637       .addImm(0xC7F);
7638
7639     // Reload the modified control word now...
7640     addFrameReference(BuildMI(BB, dl, TII->get(X86::FLDCW16m)), CWFrameIdx);
7641
7642     // Restore the memory image of control word to original value
7643     addFrameReference(BuildMI(BB, dl, TII->get(X86::MOV16mr)), CWFrameIdx)
7644       .addReg(OldCW);
7645
7646     // Get the X86 opcode to use.
7647     unsigned Opc;
7648     switch (MI->getOpcode()) {
7649     default: llvm_unreachable("illegal opcode!");
7650     case X86::FP32_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m32; break;
7651     case X86::FP32_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m32; break;
7652     case X86::FP32_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m32; break;
7653     case X86::FP64_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m64; break;
7654     case X86::FP64_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m64; break;
7655     case X86::FP64_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m64; break;
7656     case X86::FP80_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m80; break;
7657     case X86::FP80_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m80; break;
7658     case X86::FP80_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m80; break;
7659     }
7660
7661     X86AddressMode AM;
7662     MachineOperand &Op = MI->getOperand(0);
7663     if (Op.isReg()) {
7664       AM.BaseType = X86AddressMode::RegBase;
7665       AM.Base.Reg = Op.getReg();
7666     } else {
7667       AM.BaseType = X86AddressMode::FrameIndexBase;
7668       AM.Base.FrameIndex = Op.getIndex();
7669     }
7670     Op = MI->getOperand(1);
7671     if (Op.isImm())
7672       AM.Scale = Op.getImm();
7673     Op = MI->getOperand(2);
7674     if (Op.isImm())
7675       AM.IndexReg = Op.getImm();
7676     Op = MI->getOperand(3);
7677     if (Op.isGlobal()) {
7678       AM.GV = Op.getGlobal();
7679     } else {
7680       AM.Disp = Op.getImm();
7681     }
7682     addFullAddress(BuildMI(BB, dl, TII->get(Opc)), AM)
7683                       .addReg(MI->getOperand(X86AddrNumOperands).getReg());
7684
7685     // Reload the original control word now.
7686     addFrameReference(BuildMI(BB, dl, TII->get(X86::FLDCW16m)), CWFrameIdx);
7687
7688     F->DeleteMachineInstr(MI);   // The pseudo instruction is gone now.
7689     return BB;
7690   }
7691   case X86::ATOMAND32:
7692     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND32rr,
7693                                                X86::AND32ri, X86::MOV32rm,
7694                                                X86::LCMPXCHG32, X86::MOV32rr,
7695                                                X86::NOT32r, X86::EAX,
7696                                                X86::GR32RegisterClass);
7697   case X86::ATOMOR32:
7698     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR32rr,
7699                                                X86::OR32ri, X86::MOV32rm,
7700                                                X86::LCMPXCHG32, X86::MOV32rr,
7701                                                X86::NOT32r, X86::EAX,
7702                                                X86::GR32RegisterClass);
7703   case X86::ATOMXOR32:
7704     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR32rr,
7705                                                X86::XOR32ri, X86::MOV32rm,
7706                                                X86::LCMPXCHG32, X86::MOV32rr,
7707                                                X86::NOT32r, X86::EAX,
7708                                                X86::GR32RegisterClass);
7709   case X86::ATOMNAND32:
7710     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND32rr,
7711                                                X86::AND32ri, X86::MOV32rm,
7712                                                X86::LCMPXCHG32, X86::MOV32rr,
7713                                                X86::NOT32r, X86::EAX,
7714                                                X86::GR32RegisterClass, true);
7715   case X86::ATOMMIN32:
7716     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVL32rr);
7717   case X86::ATOMMAX32:
7718     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVG32rr);
7719   case X86::ATOMUMIN32:
7720     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVB32rr);
7721   case X86::ATOMUMAX32:
7722     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVA32rr);
7723
7724   case X86::ATOMAND16:
7725     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND16rr,
7726                                                X86::AND16ri, X86::MOV16rm,
7727                                                X86::LCMPXCHG16, X86::MOV16rr,
7728                                                X86::NOT16r, X86::AX,
7729                                                X86::GR16RegisterClass);
7730   case X86::ATOMOR16:
7731     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR16rr,
7732                                                X86::OR16ri, X86::MOV16rm,
7733                                                X86::LCMPXCHG16, X86::MOV16rr,
7734                                                X86::NOT16r, X86::AX,
7735                                                X86::GR16RegisterClass);
7736   case X86::ATOMXOR16:
7737     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR16rr,
7738                                                X86::XOR16ri, X86::MOV16rm,
7739                                                X86::LCMPXCHG16, X86::MOV16rr,
7740                                                X86::NOT16r, X86::AX,
7741                                                X86::GR16RegisterClass);
7742   case X86::ATOMNAND16:
7743     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND16rr,
7744                                                X86::AND16ri, X86::MOV16rm,
7745                                                X86::LCMPXCHG16, X86::MOV16rr,
7746                                                X86::NOT16r, X86::AX,
7747                                                X86::GR16RegisterClass, true);
7748   case X86::ATOMMIN16:
7749     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVL16rr);
7750   case X86::ATOMMAX16:
7751     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVG16rr);
7752   case X86::ATOMUMIN16:
7753     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVB16rr);
7754   case X86::ATOMUMAX16:
7755     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVA16rr);
7756
7757   case X86::ATOMAND8:
7758     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND8rr,
7759                                                X86::AND8ri, X86::MOV8rm,
7760                                                X86::LCMPXCHG8, X86::MOV8rr,
7761                                                X86::NOT8r, X86::AL,
7762                                                X86::GR8RegisterClass);
7763   case X86::ATOMOR8:
7764     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR8rr,
7765                                                X86::OR8ri, X86::MOV8rm,
7766                                                X86::LCMPXCHG8, X86::MOV8rr,
7767                                                X86::NOT8r, X86::AL,
7768                                                X86::GR8RegisterClass);
7769   case X86::ATOMXOR8:
7770     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR8rr,
7771                                                X86::XOR8ri, X86::MOV8rm,
7772                                                X86::LCMPXCHG8, X86::MOV8rr,
7773                                                X86::NOT8r, X86::AL,
7774                                                X86::GR8RegisterClass);
7775   case X86::ATOMNAND8:
7776     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND8rr,
7777                                                X86::AND8ri, X86::MOV8rm,
7778                                                X86::LCMPXCHG8, X86::MOV8rr,
7779                                                X86::NOT8r, X86::AL,
7780                                                X86::GR8RegisterClass, true);
7781   // FIXME: There are no CMOV8 instructions; MIN/MAX need some other way.
7782   // This group is for 64-bit host.
7783   case X86::ATOMAND64:
7784     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND64rr,
7785                                                X86::AND64ri32, X86::MOV64rm,
7786                                                X86::LCMPXCHG64, X86::MOV64rr,
7787                                                X86::NOT64r, X86::RAX,
7788                                                X86::GR64RegisterClass);
7789   case X86::ATOMOR64:
7790     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR64rr,
7791                                                X86::OR64ri32, X86::MOV64rm,
7792                                                X86::LCMPXCHG64, X86::MOV64rr,
7793                                                X86::NOT64r, X86::RAX,
7794                                                X86::GR64RegisterClass);
7795   case X86::ATOMXOR64:
7796     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR64rr,
7797                                                X86::XOR64ri32, X86::MOV64rm,
7798                                                X86::LCMPXCHG64, X86::MOV64rr,
7799                                                X86::NOT64r, X86::RAX,
7800                                                X86::GR64RegisterClass);
7801   case X86::ATOMNAND64:
7802     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND64rr,
7803                                                X86::AND64ri32, X86::MOV64rm,
7804                                                X86::LCMPXCHG64, X86::MOV64rr,
7805                                                X86::NOT64r, X86::RAX,
7806                                                X86::GR64RegisterClass, true);
7807   case X86::ATOMMIN64:
7808     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVL64rr);
7809   case X86::ATOMMAX64:
7810     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVG64rr);
7811   case X86::ATOMUMIN64:
7812     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVB64rr);
7813   case X86::ATOMUMAX64:
7814     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVA64rr);
7815
7816   // This group does 64-bit operations on a 32-bit host.
7817   case X86::ATOMAND6432:
7818     return EmitAtomicBit6432WithCustomInserter(MI, BB,
7819                                                X86::AND32rr, X86::AND32rr,
7820                                                X86::AND32ri, X86::AND32ri,
7821                                                false);
7822   case X86::ATOMOR6432:
7823     return EmitAtomicBit6432WithCustomInserter(MI, BB,
7824                                                X86::OR32rr, X86::OR32rr,
7825                                                X86::OR32ri, X86::OR32ri,
7826                                                false);
7827   case X86::ATOMXOR6432:
7828     return EmitAtomicBit6432WithCustomInserter(MI, BB,
7829                                                X86::XOR32rr, X86::XOR32rr,
7830                                                X86::XOR32ri, X86::XOR32ri,
7831                                                false);
7832   case X86::ATOMNAND6432:
7833     return EmitAtomicBit6432WithCustomInserter(MI, BB,
7834                                                X86::AND32rr, X86::AND32rr,
7835                                                X86::AND32ri, X86::AND32ri,
7836                                                true);
7837   case X86::ATOMADD6432:
7838     return EmitAtomicBit6432WithCustomInserter(MI, BB,
7839                                                X86::ADD32rr, X86::ADC32rr,
7840                                                X86::ADD32ri, X86::ADC32ri,
7841                                                false);
7842   case X86::ATOMSUB6432:
7843     return EmitAtomicBit6432WithCustomInserter(MI, BB,
7844                                                X86::SUB32rr, X86::SBB32rr,
7845                                                X86::SUB32ri, X86::SBB32ri,
7846                                                false);
7847   case X86::ATOMSWAP6432:
7848     return EmitAtomicBit6432WithCustomInserter(MI, BB,
7849                                                X86::MOV32rr, X86::MOV32rr,
7850                                                X86::MOV32ri, X86::MOV32ri,
7851                                                false);
7852   }
7853 }
7854
7855 //===----------------------------------------------------------------------===//
7856 //                           X86 Optimization Hooks
7857 //===----------------------------------------------------------------------===//
7858
7859 void X86TargetLowering::computeMaskedBitsForTargetNode(const SDValue Op,
7860                                                        const APInt &Mask,
7861                                                        APInt &KnownZero,
7862                                                        APInt &KnownOne,
7863                                                        const SelectionDAG &DAG,
7864                                                        unsigned Depth) const {
7865   unsigned Opc = Op.getOpcode();
7866   assert((Opc >= ISD::BUILTIN_OP_END ||
7867           Opc == ISD::INTRINSIC_WO_CHAIN ||
7868           Opc == ISD::INTRINSIC_W_CHAIN ||
7869           Opc == ISD::INTRINSIC_VOID) &&
7870          "Should use MaskedValueIsZero if you don't know whether Op"
7871          " is a target node!");
7872
7873   KnownZero = KnownOne = APInt(Mask.getBitWidth(), 0);   // Don't know anything.
7874   switch (Opc) {
7875   default: break;
7876   case X86ISD::ADD:
7877   case X86ISD::SUB:
7878   case X86ISD::SMUL:
7879   case X86ISD::UMUL:
7880   case X86ISD::INC:
7881   case X86ISD::DEC:
7882     // These nodes' second result is a boolean.
7883     if (Op.getResNo() == 0)
7884       break;
7885     // Fallthrough
7886   case X86ISD::SETCC:
7887     KnownZero |= APInt::getHighBitsSet(Mask.getBitWidth(),
7888                                        Mask.getBitWidth() - 1);
7889     break;
7890   }
7891 }
7892
7893 /// isGAPlusOffset - Returns true (and the GlobalValue and the offset) if the
7894 /// node is a GlobalAddress + offset.
7895 bool X86TargetLowering::isGAPlusOffset(SDNode *N,
7896                                        GlobalValue* &GA, int64_t &Offset) const{
7897   if (N->getOpcode() == X86ISD::Wrapper) {
7898     if (isa<GlobalAddressSDNode>(N->getOperand(0))) {
7899       GA = cast<GlobalAddressSDNode>(N->getOperand(0))->getGlobal();
7900       Offset = cast<GlobalAddressSDNode>(N->getOperand(0))->getOffset();
7901       return true;
7902     }
7903   }
7904   return TargetLowering::isGAPlusOffset(N, GA, Offset);
7905 }
7906
7907 static bool isBaseAlignmentOfN(unsigned N, SDNode *Base,
7908                                const TargetLowering &TLI) {
7909   GlobalValue *GV;
7910   int64_t Offset = 0;
7911   if (TLI.isGAPlusOffset(Base, GV, Offset))
7912     return (GV->getAlignment() >= N && (Offset % N) == 0);
7913   // DAG combine handles the stack object case.
7914   return false;
7915 }
7916
7917 static bool EltsFromConsecutiveLoads(ShuffleVectorSDNode *N, unsigned NumElems,
7918                                      MVT EVT, LoadSDNode *&LDBase,
7919                                      unsigned &LastLoadedElt,
7920                                      SelectionDAG &DAG, MachineFrameInfo *MFI,
7921                                      const TargetLowering &TLI) {
7922   LDBase = NULL;
7923   LastLoadedElt = -1U;
7924   for (unsigned i = 0; i < NumElems; ++i) {
7925     if (N->getMaskElt(i) < 0) {
7926       if (!LDBase)
7927         return false;
7928       continue;
7929     }
7930
7931     SDValue Elt = DAG.getShuffleScalarElt(N, i);
7932     if (!Elt.getNode() ||
7933         (Elt.getOpcode() != ISD::UNDEF && !ISD::isNON_EXTLoad(Elt.getNode())))
7934       return false;
7935     if (!LDBase) {
7936       if (Elt.getNode()->getOpcode() == ISD::UNDEF)
7937         return false;
7938       LDBase = cast<LoadSDNode>(Elt.getNode());
7939       LastLoadedElt = i;
7940       continue;
7941     }
7942     if (Elt.getOpcode() == ISD::UNDEF)
7943       continue;
7944
7945     LoadSDNode *LD = cast<LoadSDNode>(Elt);
7946     if (!TLI.isConsecutiveLoad(LD, LDBase, EVT.getSizeInBits()/8, i, MFI))
7947       return false;
7948     LastLoadedElt = i;
7949   }
7950   return true;
7951 }
7952
7953 /// PerformShuffleCombine - Combine a vector_shuffle that is equal to
7954 /// build_vector load1, load2, load3, load4, <0, 1, 2, 3> into a 128-bit load
7955 /// if the load addresses are consecutive, non-overlapping, and in the right
7956 /// order.  In the case of v2i64, it will see if it can rewrite the
7957 /// shuffle to be an appropriate build vector so it can take advantage of
7958 // performBuildVectorCombine.
7959 static SDValue PerformShuffleCombine(SDNode *N, SelectionDAG &DAG,
7960                                      const TargetLowering &TLI) {
7961   DebugLoc dl = N->getDebugLoc();
7962   MVT VT = N->getValueType(0);
7963   MVT EVT = VT.getVectorElementType();
7964   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
7965   unsigned NumElems = VT.getVectorNumElements();
7966
7967   if (VT.getSizeInBits() != 128)
7968     return SDValue();
7969
7970   // Try to combine a vector_shuffle into a 128-bit load.
7971   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
7972   LoadSDNode *LD = NULL;
7973   unsigned LastLoadedElt;
7974   if (!EltsFromConsecutiveLoads(SVN, NumElems, EVT, LD, LastLoadedElt, DAG,
7975                                 MFI, TLI))
7976     return SDValue();
7977
7978   if (LastLoadedElt == NumElems - 1) {
7979     if (isBaseAlignmentOfN(16, LD->getBasePtr().getNode(), TLI))
7980       return DAG.getLoad(VT, dl, LD->getChain(), LD->getBasePtr(),
7981                          LD->getSrcValue(), LD->getSrcValueOffset(),
7982                          LD->isVolatile());
7983     return DAG.getLoad(VT, dl, LD->getChain(), LD->getBasePtr(),
7984                        LD->getSrcValue(), LD->getSrcValueOffset(),
7985                        LD->isVolatile(), LD->getAlignment());
7986   } else if (NumElems == 4 && LastLoadedElt == 1) {
7987     SDVTList Tys = DAG.getVTList(MVT::v2i64, MVT::Other);
7988     SDValue Ops[] = { LD->getChain(), LD->getBasePtr() };
7989     SDValue ResNode = DAG.getNode(X86ISD::VZEXT_LOAD, dl, Tys, Ops, 2);
7990     return DAG.getNode(ISD::BIT_CONVERT, dl, VT, ResNode);
7991   }
7992   return SDValue();
7993 }
7994
7995 /// PerformSELECTCombine - Do target-specific dag combines on SELECT nodes.
7996 static SDValue PerformSELECTCombine(SDNode *N, SelectionDAG &DAG,
7997                                     const X86Subtarget *Subtarget) {
7998   DebugLoc DL = N->getDebugLoc();
7999   SDValue Cond = N->getOperand(0);
8000   // Get the LHS/RHS of the select.
8001   SDValue LHS = N->getOperand(1);
8002   SDValue RHS = N->getOperand(2);
8003   
8004   // If we have SSE[12] support, try to form min/max nodes.
8005   if (Subtarget->hasSSE2() &&
8006       (LHS.getValueType() == MVT::f32 || LHS.getValueType() == MVT::f64) &&
8007       Cond.getOpcode() == ISD::SETCC) {
8008     ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
8009
8010     unsigned Opcode = 0;
8011     if (LHS == Cond.getOperand(0) && RHS == Cond.getOperand(1)) {
8012       switch (CC) {
8013       default: break;
8014       case ISD::SETOLE: // (X <= Y) ? X : Y -> min
8015       case ISD::SETULE:
8016       case ISD::SETLE:
8017         if (!UnsafeFPMath) break;
8018         // FALL THROUGH.
8019       case ISD::SETOLT:  // (X olt/lt Y) ? X : Y -> min
8020       case ISD::SETLT:
8021         Opcode = X86ISD::FMIN;
8022         break;
8023
8024       case ISD::SETOGT: // (X > Y) ? X : Y -> max
8025       case ISD::SETUGT:
8026       case ISD::SETGT:
8027         if (!UnsafeFPMath) break;
8028         // FALL THROUGH.
8029       case ISD::SETUGE:  // (X uge/ge Y) ? X : Y -> max
8030       case ISD::SETGE:
8031         Opcode = X86ISD::FMAX;
8032         break;
8033       }
8034     } else if (LHS == Cond.getOperand(1) && RHS == Cond.getOperand(0)) {
8035       switch (CC) {
8036       default: break;
8037       case ISD::SETOGT: // (X > Y) ? Y : X -> min
8038       case ISD::SETUGT:
8039       case ISD::SETGT:
8040         if (!UnsafeFPMath) break;
8041         // FALL THROUGH.
8042       case ISD::SETUGE:  // (X uge/ge Y) ? Y : X -> min
8043       case ISD::SETGE:
8044         Opcode = X86ISD::FMIN;
8045         break;
8046
8047       case ISD::SETOLE:   // (X <= Y) ? Y : X -> max
8048       case ISD::SETULE:
8049       case ISD::SETLE:
8050         if (!UnsafeFPMath) break;
8051         // FALL THROUGH.
8052       case ISD::SETOLT:   // (X olt/lt Y) ? Y : X -> max
8053       case ISD::SETLT:
8054         Opcode = X86ISD::FMAX;
8055         break;
8056       }
8057     }
8058
8059     if (Opcode)
8060       return DAG.getNode(Opcode, DL, N->getValueType(0), LHS, RHS);
8061   }
8062   
8063   // If this is a select between two integer constants, try to do some
8064   // optimizations.
8065   if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(LHS)) {
8066     if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(RHS))
8067       // Don't do this for crazy integer types.
8068       if (DAG.getTargetLoweringInfo().isTypeLegal(LHS.getValueType())) {
8069         // If this is efficiently invertible, canonicalize the LHSC/RHSC values
8070         // so that TrueC (the true value) is larger than FalseC.
8071         bool NeedsCondInvert = false;
8072         
8073         if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue()) &&
8074             // Efficiently invertible.
8075             (Cond.getOpcode() == ISD::SETCC ||  // setcc -> invertible.
8076              (Cond.getOpcode() == ISD::XOR &&   // xor(X, C) -> invertible.
8077               isa<ConstantSDNode>(Cond.getOperand(1))))) {
8078           NeedsCondInvert = true;
8079           std::swap(TrueC, FalseC);
8080         }
8081    
8082         // Optimize C ? 8 : 0 -> zext(C) << 3.  Likewise for any pow2/0.
8083         if (FalseC->getAPIntValue() == 0 &&
8084             TrueC->getAPIntValue().isPowerOf2()) {
8085           if (NeedsCondInvert) // Invert the condition if needed.
8086             Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
8087                                DAG.getConstant(1, Cond.getValueType()));
8088           
8089           // Zero extend the condition if needed.
8090           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, LHS.getValueType(), Cond);
8091           
8092           unsigned ShAmt = TrueC->getAPIntValue().logBase2();
8093           return DAG.getNode(ISD::SHL, DL, LHS.getValueType(), Cond,
8094                              DAG.getConstant(ShAmt, MVT::i8));
8095         }
8096         
8097         // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.
8098         if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
8099           if (NeedsCondInvert) // Invert the condition if needed.
8100             Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
8101                                DAG.getConstant(1, Cond.getValueType()));
8102           
8103           // Zero extend the condition if needed.
8104           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
8105                              FalseC->getValueType(0), Cond);
8106           return DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
8107                              SDValue(FalseC, 0));
8108         }
8109         
8110         // Optimize cases that will turn into an LEA instruction.  This requires
8111         // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
8112         if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
8113           uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
8114           if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
8115           
8116           bool isFastMultiplier = false;
8117           if (Diff < 10) {
8118             switch ((unsigned char)Diff) {
8119               default: break;
8120               case 1:  // result = add base, cond
8121               case 2:  // result = lea base(    , cond*2)
8122               case 3:  // result = lea base(cond, cond*2)
8123               case 4:  // result = lea base(    , cond*4)
8124               case 5:  // result = lea base(cond, cond*4)
8125               case 8:  // result = lea base(    , cond*8)
8126               case 9:  // result = lea base(cond, cond*8)
8127                 isFastMultiplier = true;
8128                 break;
8129             }
8130           }
8131           
8132           if (isFastMultiplier) {
8133             APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
8134             if (NeedsCondInvert) // Invert the condition if needed.
8135               Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
8136                                  DAG.getConstant(1, Cond.getValueType()));
8137             
8138             // Zero extend the condition if needed.
8139             Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
8140                                Cond);
8141             // Scale the condition by the difference.
8142             if (Diff != 1)
8143               Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
8144                                  DAG.getConstant(Diff, Cond.getValueType()));
8145             
8146             // Add the base if non-zero.
8147             if (FalseC->getAPIntValue() != 0)
8148               Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
8149                                  SDValue(FalseC, 0));
8150             return Cond;
8151           }
8152         }      
8153       }
8154   }
8155       
8156   return SDValue();
8157 }
8158
8159 /// Optimize X86ISD::CMOV [LHS, RHS, CONDCODE (e.g. X86::COND_NE), CONDVAL]
8160 static SDValue PerformCMOVCombine(SDNode *N, SelectionDAG &DAG,
8161                                   TargetLowering::DAGCombinerInfo &DCI) {
8162   DebugLoc DL = N->getDebugLoc();
8163   
8164   // If the flag operand isn't dead, don't touch this CMOV.
8165   if (N->getNumValues() == 2 && !SDValue(N, 1).use_empty())
8166     return SDValue();
8167   
8168   // If this is a select between two integer constants, try to do some
8169   // optimizations.  Note that the operands are ordered the opposite of SELECT
8170   // operands.
8171   if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(N->getOperand(1))) {
8172     if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(N->getOperand(0))) {
8173       // Canonicalize the TrueC/FalseC values so that TrueC (the true value) is
8174       // larger than FalseC (the false value).
8175       X86::CondCode CC = (X86::CondCode)N->getConstantOperandVal(2);
8176         
8177       if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue())) {
8178         CC = X86::GetOppositeBranchCondition(CC);
8179         std::swap(TrueC, FalseC);
8180       }
8181         
8182       // Optimize C ? 8 : 0 -> zext(setcc(C)) << 3.  Likewise for any pow2/0.
8183       // This is efficient for any integer data type (including i8/i16) and
8184       // shift amount.
8185       if (FalseC->getAPIntValue() == 0 && TrueC->getAPIntValue().isPowerOf2()) {
8186         SDValue Cond = N->getOperand(3);
8187         Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
8188                            DAG.getConstant(CC, MVT::i8), Cond);
8189       
8190         // Zero extend the condition if needed.
8191         Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, TrueC->getValueType(0), Cond);
8192         
8193         unsigned ShAmt = TrueC->getAPIntValue().logBase2();
8194         Cond = DAG.getNode(ISD::SHL, DL, Cond.getValueType(), Cond,
8195                            DAG.getConstant(ShAmt, MVT::i8));
8196         if (N->getNumValues() == 2)  // Dead flag value?
8197           return DCI.CombineTo(N, Cond, SDValue());
8198         return Cond;
8199       }
8200       
8201       // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.  This is efficient
8202       // for any integer data type, including i8/i16.
8203       if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
8204         SDValue Cond = N->getOperand(3);
8205         Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
8206                            DAG.getConstant(CC, MVT::i8), Cond);
8207         
8208         // Zero extend the condition if needed.
8209         Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
8210                            FalseC->getValueType(0), Cond);
8211         Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
8212                            SDValue(FalseC, 0));
8213         
8214         if (N->getNumValues() == 2)  // Dead flag value?
8215           return DCI.CombineTo(N, Cond, SDValue());
8216         return Cond;
8217       }
8218       
8219       // Optimize cases that will turn into an LEA instruction.  This requires
8220       // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
8221       if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
8222         uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
8223         if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
8224        
8225         bool isFastMultiplier = false;
8226         if (Diff < 10) {
8227           switch ((unsigned char)Diff) {
8228           default: break;
8229           case 1:  // result = add base, cond
8230           case 2:  // result = lea base(    , cond*2)
8231           case 3:  // result = lea base(cond, cond*2)
8232           case 4:  // result = lea base(    , cond*4)
8233           case 5:  // result = lea base(cond, cond*4)
8234           case 8:  // result = lea base(    , cond*8)
8235           case 9:  // result = lea base(cond, cond*8)
8236             isFastMultiplier = true;
8237             break;
8238           }
8239         }
8240         
8241         if (isFastMultiplier) {
8242           APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
8243           SDValue Cond = N->getOperand(3);
8244           Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
8245                              DAG.getConstant(CC, MVT::i8), Cond);
8246           // Zero extend the condition if needed.
8247           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
8248                              Cond);
8249           // Scale the condition by the difference.
8250           if (Diff != 1)
8251             Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
8252                                DAG.getConstant(Diff, Cond.getValueType()));
8253
8254           // Add the base if non-zero.
8255           if (FalseC->getAPIntValue() != 0)
8256             Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
8257                                SDValue(FalseC, 0));
8258           if (N->getNumValues() == 2)  // Dead flag value?
8259             return DCI.CombineTo(N, Cond, SDValue());
8260           return Cond;
8261         }
8262       }      
8263     }
8264   }
8265   return SDValue();
8266 }
8267
8268
8269 /// PerformMulCombine - Optimize a single multiply with constant into two
8270 /// in order to implement it with two cheaper instructions, e.g.
8271 /// LEA + SHL, LEA + LEA.
8272 static SDValue PerformMulCombine(SDNode *N, SelectionDAG &DAG,
8273                                  TargetLowering::DAGCombinerInfo &DCI) {
8274   if (DAG.getMachineFunction().
8275       getFunction()->hasFnAttr(Attribute::OptimizeForSize))
8276     return SDValue();
8277
8278   if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
8279     return SDValue();
8280
8281   MVT VT = N->getValueType(0);
8282   if (VT != MVT::i64)
8283     return SDValue();
8284
8285   ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
8286   if (!C)
8287     return SDValue();
8288   uint64_t MulAmt = C->getZExtValue();
8289   if (isPowerOf2_64(MulAmt) || MulAmt == 3 || MulAmt == 5 || MulAmt == 9)
8290     return SDValue();
8291
8292   uint64_t MulAmt1 = 0;
8293   uint64_t MulAmt2 = 0;
8294   if ((MulAmt % 9) == 0) {
8295     MulAmt1 = 9;
8296     MulAmt2 = MulAmt / 9;
8297   } else if ((MulAmt % 5) == 0) {
8298     MulAmt1 = 5;
8299     MulAmt2 = MulAmt / 5;
8300   } else if ((MulAmt % 3) == 0) {
8301     MulAmt1 = 3;
8302     MulAmt2 = MulAmt / 3;
8303   }
8304   if (MulAmt2 &&
8305       (isPowerOf2_64(MulAmt2) || MulAmt2 == 3 || MulAmt2 == 5 || MulAmt2 == 9)){
8306     DebugLoc DL = N->getDebugLoc();
8307
8308     if (isPowerOf2_64(MulAmt2) &&
8309         !(N->hasOneUse() && N->use_begin()->getOpcode() == ISD::ADD))
8310       // If second multiplifer is pow2, issue it first. We want the multiply by
8311       // 3, 5, or 9 to be folded into the addressing mode unless the lone use
8312       // is an add.
8313       std::swap(MulAmt1, MulAmt2);
8314
8315     SDValue NewMul;
8316     if (isPowerOf2_64(MulAmt1)) 
8317       NewMul = DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
8318                            DAG.getConstant(Log2_64(MulAmt1), MVT::i8));
8319     else
8320       NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, N->getOperand(0),
8321                            DAG.getConstant(MulAmt1, VT));
8322
8323     if (isPowerOf2_64(MulAmt2)) 
8324       NewMul = DAG.getNode(ISD::SHL, DL, VT, NewMul,
8325                            DAG.getConstant(Log2_64(MulAmt2), MVT::i8));
8326     else 
8327       NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, NewMul,
8328                            DAG.getConstant(MulAmt2, VT));
8329
8330     // Do not add new nodes to DAG combiner worklist.
8331     DCI.CombineTo(N, NewMul, false);
8332   }
8333   return SDValue();
8334 }
8335
8336
8337 /// PerformShiftCombine - Transforms vector shift nodes to use vector shifts
8338 ///                       when possible.
8339 static SDValue PerformShiftCombine(SDNode* N, SelectionDAG &DAG,
8340                                    const X86Subtarget *Subtarget) {
8341   // On X86 with SSE2 support, we can transform this to a vector shift if
8342   // all elements are shifted by the same amount.  We can't do this in legalize
8343   // because the a constant vector is typically transformed to a constant pool
8344   // so we have no knowledge of the shift amount.
8345   if (!Subtarget->hasSSE2())
8346     return SDValue();
8347
8348   MVT VT = N->getValueType(0);
8349   if (VT != MVT::v2i64 && VT != MVT::v4i32 && VT != MVT::v8i16)
8350     return SDValue();
8351
8352   SDValue ShAmtOp = N->getOperand(1);
8353   MVT EltVT = VT.getVectorElementType();
8354   DebugLoc DL = N->getDebugLoc();
8355   SDValue BaseShAmt;
8356   if (ShAmtOp.getOpcode() == ISD::BUILD_VECTOR) {
8357     unsigned NumElts = VT.getVectorNumElements();
8358     unsigned i = 0;
8359     for (; i != NumElts; ++i) {
8360       SDValue Arg = ShAmtOp.getOperand(i);
8361       if (Arg.getOpcode() == ISD::UNDEF) continue;
8362       BaseShAmt = Arg;
8363       break;
8364     }
8365     for (; i != NumElts; ++i) {
8366       SDValue Arg = ShAmtOp.getOperand(i);
8367       if (Arg.getOpcode() == ISD::UNDEF) continue;
8368       if (Arg != BaseShAmt) {
8369         return SDValue();
8370       }
8371     }
8372   } else if (ShAmtOp.getOpcode() == ISD::VECTOR_SHUFFLE &&
8373              cast<ShuffleVectorSDNode>(ShAmtOp)->isSplat()) {
8374     BaseShAmt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, EltVT, ShAmtOp,
8375                             DAG.getIntPtrConstant(0));
8376   } else
8377     return SDValue();
8378
8379   if (EltVT.bitsGT(MVT::i32))
8380     BaseShAmt = DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, BaseShAmt);
8381   else if (EltVT.bitsLT(MVT::i32))
8382     BaseShAmt = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, BaseShAmt);
8383
8384   // The shift amount is identical so we can do a vector shift.
8385   SDValue  ValOp = N->getOperand(0);
8386   switch (N->getOpcode()) {
8387   default:
8388     llvm_unreachable("Unknown shift opcode!");
8389     break;
8390   case ISD::SHL:
8391     if (VT == MVT::v2i64)
8392       return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
8393                          DAG.getConstant(Intrinsic::x86_sse2_pslli_q, MVT::i32),
8394                          ValOp, BaseShAmt);
8395     if (VT == MVT::v4i32)
8396       return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
8397                          DAG.getConstant(Intrinsic::x86_sse2_pslli_d, MVT::i32),
8398                          ValOp, BaseShAmt);
8399     if (VT == MVT::v8i16)
8400       return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
8401                          DAG.getConstant(Intrinsic::x86_sse2_pslli_w, MVT::i32),
8402                          ValOp, BaseShAmt);
8403     break;
8404   case ISD::SRA:
8405     if (VT == MVT::v4i32)
8406       return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
8407                          DAG.getConstant(Intrinsic::x86_sse2_psrai_d, MVT::i32),
8408                          ValOp, BaseShAmt);
8409     if (VT == MVT::v8i16)
8410       return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
8411                          DAG.getConstant(Intrinsic::x86_sse2_psrai_w, MVT::i32),
8412                          ValOp, BaseShAmt);
8413     break;
8414   case ISD::SRL:
8415     if (VT == MVT::v2i64)
8416       return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
8417                          DAG.getConstant(Intrinsic::x86_sse2_psrli_q, MVT::i32),
8418                          ValOp, BaseShAmt);
8419     if (VT == MVT::v4i32)
8420       return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
8421                          DAG.getConstant(Intrinsic::x86_sse2_psrli_d, MVT::i32),
8422                          ValOp, BaseShAmt);
8423     if (VT ==  MVT::v8i16)
8424       return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
8425                          DAG.getConstant(Intrinsic::x86_sse2_psrli_w, MVT::i32),
8426                          ValOp, BaseShAmt);
8427     break;
8428   }
8429   return SDValue();
8430 }
8431
8432 /// PerformSTORECombine - Do target-specific dag combines on STORE nodes.
8433 static SDValue PerformSTORECombine(SDNode *N, SelectionDAG &DAG,
8434                                    const X86Subtarget *Subtarget) {
8435   // Turn load->store of MMX types into GPR load/stores.  This avoids clobbering
8436   // the FP state in cases where an emms may be missing.
8437   // A preferable solution to the general problem is to figure out the right
8438   // places to insert EMMS.  This qualifies as a quick hack.
8439
8440   // Similarly, turn load->store of i64 into double load/stores in 32-bit mode.
8441   StoreSDNode *St = cast<StoreSDNode>(N);
8442   MVT VT = St->getValue().getValueType();
8443   if (VT.getSizeInBits() != 64)
8444     return SDValue();
8445
8446   const Function *F = DAG.getMachineFunction().getFunction();
8447   bool NoImplicitFloatOps = F->hasFnAttr(Attribute::NoImplicitFloat);
8448   bool F64IsLegal = !UseSoftFloat && !NoImplicitFloatOps 
8449     && Subtarget->hasSSE2();
8450   if ((VT.isVector() ||
8451        (VT == MVT::i64 && F64IsLegal && !Subtarget->is64Bit())) &&
8452       isa<LoadSDNode>(St->getValue()) &&
8453       !cast<LoadSDNode>(St->getValue())->isVolatile() &&
8454       St->getChain().hasOneUse() && !St->isVolatile()) {
8455     SDNode* LdVal = St->getValue().getNode();
8456     LoadSDNode *Ld = 0;
8457     int TokenFactorIndex = -1;
8458     SmallVector<SDValue, 8> Ops;
8459     SDNode* ChainVal = St->getChain().getNode();
8460     // Must be a store of a load.  We currently handle two cases:  the load
8461     // is a direct child, and it's under an intervening TokenFactor.  It is
8462     // possible to dig deeper under nested TokenFactors.
8463     if (ChainVal == LdVal)
8464       Ld = cast<LoadSDNode>(St->getChain());
8465     else if (St->getValue().hasOneUse() &&
8466              ChainVal->getOpcode() == ISD::TokenFactor) {
8467       for (unsigned i=0, e = ChainVal->getNumOperands(); i != e; ++i) {
8468         if (ChainVal->getOperand(i).getNode() == LdVal) {
8469           TokenFactorIndex = i;
8470           Ld = cast<LoadSDNode>(St->getValue());
8471         } else
8472           Ops.push_back(ChainVal->getOperand(i));
8473       }
8474     }
8475
8476     if (!Ld || !ISD::isNormalLoad(Ld))
8477       return SDValue();
8478
8479     // If this is not the MMX case, i.e. we are just turning i64 load/store
8480     // into f64 load/store, avoid the transformation if there are multiple
8481     // uses of the loaded value.
8482     if (!VT.isVector() && !Ld->hasNUsesOfValue(1, 0))
8483       return SDValue();
8484
8485     DebugLoc LdDL = Ld->getDebugLoc();
8486     DebugLoc StDL = N->getDebugLoc();
8487     // If we are a 64-bit capable x86, lower to a single movq load/store pair.
8488     // Otherwise, if it's legal to use f64 SSE instructions, use f64 load/store
8489     // pair instead.
8490     if (Subtarget->is64Bit() || F64IsLegal) {
8491       MVT LdVT = Subtarget->is64Bit() ? MVT::i64 : MVT::f64;
8492       SDValue NewLd = DAG.getLoad(LdVT, LdDL, Ld->getChain(),
8493                                   Ld->getBasePtr(), Ld->getSrcValue(),
8494                                   Ld->getSrcValueOffset(), Ld->isVolatile(),
8495                                   Ld->getAlignment());
8496       SDValue NewChain = NewLd.getValue(1);
8497       if (TokenFactorIndex != -1) {
8498         Ops.push_back(NewChain);
8499         NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, &Ops[0],
8500                                Ops.size());
8501       }
8502       return DAG.getStore(NewChain, StDL, NewLd, St->getBasePtr(),
8503                           St->getSrcValue(), St->getSrcValueOffset(),
8504                           St->isVolatile(), St->getAlignment());
8505     }
8506
8507     // Otherwise, lower to two pairs of 32-bit loads / stores.
8508     SDValue LoAddr = Ld->getBasePtr();
8509     SDValue HiAddr = DAG.getNode(ISD::ADD, LdDL, MVT::i32, LoAddr,
8510                                  DAG.getConstant(4, MVT::i32));
8511
8512     SDValue LoLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), LoAddr,
8513                                Ld->getSrcValue(), Ld->getSrcValueOffset(),
8514                                Ld->isVolatile(), Ld->getAlignment());
8515     SDValue HiLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), HiAddr,
8516                                Ld->getSrcValue(), Ld->getSrcValueOffset()+4,
8517                                Ld->isVolatile(),
8518                                MinAlign(Ld->getAlignment(), 4));
8519
8520     SDValue NewChain = LoLd.getValue(1);
8521     if (TokenFactorIndex != -1) {
8522       Ops.push_back(LoLd);
8523       Ops.push_back(HiLd);
8524       NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, &Ops[0],
8525                              Ops.size());
8526     }
8527
8528     LoAddr = St->getBasePtr();
8529     HiAddr = DAG.getNode(ISD::ADD, StDL, MVT::i32, LoAddr,
8530                          DAG.getConstant(4, MVT::i32));
8531
8532     SDValue LoSt = DAG.getStore(NewChain, StDL, LoLd, LoAddr,
8533                                 St->getSrcValue(), St->getSrcValueOffset(),
8534                                 St->isVolatile(), St->getAlignment());
8535     SDValue HiSt = DAG.getStore(NewChain, StDL, HiLd, HiAddr,
8536                                 St->getSrcValue(),
8537                                 St->getSrcValueOffset() + 4,
8538                                 St->isVolatile(),
8539                                 MinAlign(St->getAlignment(), 4));
8540     return DAG.getNode(ISD::TokenFactor, StDL, MVT::Other, LoSt, HiSt);
8541   }
8542   return SDValue();
8543 }
8544
8545 /// PerformFORCombine - Do target-specific dag combines on X86ISD::FOR and
8546 /// X86ISD::FXOR nodes.
8547 static SDValue PerformFORCombine(SDNode *N, SelectionDAG &DAG) {
8548   assert(N->getOpcode() == X86ISD::FOR || N->getOpcode() == X86ISD::FXOR);
8549   // F[X]OR(0.0, x) -> x
8550   // F[X]OR(x, 0.0) -> x
8551   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
8552     if (C->getValueAPF().isPosZero())
8553       return N->getOperand(1);
8554   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
8555     if (C->getValueAPF().isPosZero())
8556       return N->getOperand(0);
8557   return SDValue();
8558 }
8559
8560 /// PerformFANDCombine - Do target-specific dag combines on X86ISD::FAND nodes.
8561 static SDValue PerformFANDCombine(SDNode *N, SelectionDAG &DAG) {
8562   // FAND(0.0, x) -> 0.0
8563   // FAND(x, 0.0) -> 0.0
8564   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
8565     if (C->getValueAPF().isPosZero())
8566       return N->getOperand(0);
8567   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
8568     if (C->getValueAPF().isPosZero())
8569       return N->getOperand(1);
8570   return SDValue();
8571 }
8572
8573 static SDValue PerformBTCombine(SDNode *N,
8574                                 SelectionDAG &DAG,
8575                                 TargetLowering::DAGCombinerInfo &DCI) {
8576   // BT ignores high bits in the bit index operand.
8577   SDValue Op1 = N->getOperand(1);
8578   if (Op1.hasOneUse()) {
8579     unsigned BitWidth = Op1.getValueSizeInBits();
8580     APInt DemandedMask = APInt::getLowBitsSet(BitWidth, Log2_32(BitWidth));
8581     APInt KnownZero, KnownOne;
8582     TargetLowering::TargetLoweringOpt TLO(DAG);
8583     TargetLowering &TLI = DAG.getTargetLoweringInfo();
8584     if (TLO.ShrinkDemandedConstant(Op1, DemandedMask) ||
8585         TLI.SimplifyDemandedBits(Op1, DemandedMask, KnownZero, KnownOne, TLO))
8586       DCI.CommitTargetLoweringOpt(TLO);
8587   }
8588   return SDValue();
8589 }
8590
8591 static SDValue PerformVZEXT_MOVLCombine(SDNode *N, SelectionDAG &DAG) {
8592   SDValue Op = N->getOperand(0);
8593   if (Op.getOpcode() == ISD::BIT_CONVERT)
8594     Op = Op.getOperand(0);
8595   MVT VT = N->getValueType(0), OpVT = Op.getValueType();
8596   if (Op.getOpcode() == X86ISD::VZEXT_LOAD &&
8597       VT.getVectorElementType().getSizeInBits() == 
8598       OpVT.getVectorElementType().getSizeInBits()) {
8599     return DAG.getNode(ISD::BIT_CONVERT, N->getDebugLoc(), VT, Op);
8600   }
8601   return SDValue();
8602 }
8603
8604 // On X86 and X86-64, atomic operations are lowered to locked instructions.
8605 // Locked instructions, in turn, have implicit fence semantics (all memory
8606 // operations are flushed before issuing the locked instruction, and the
8607 // are not buffered), so we can fold away the common pattern of 
8608 // fence-atomic-fence.
8609 static SDValue PerformMEMBARRIERCombine(SDNode* N, SelectionDAG &DAG) {
8610   SDValue atomic = N->getOperand(0);
8611   switch (atomic.getOpcode()) {
8612     case ISD::ATOMIC_CMP_SWAP:
8613     case ISD::ATOMIC_SWAP:
8614     case ISD::ATOMIC_LOAD_ADD:
8615     case ISD::ATOMIC_LOAD_SUB:
8616     case ISD::ATOMIC_LOAD_AND:
8617     case ISD::ATOMIC_LOAD_OR:
8618     case ISD::ATOMIC_LOAD_XOR:
8619     case ISD::ATOMIC_LOAD_NAND:
8620     case ISD::ATOMIC_LOAD_MIN:
8621     case ISD::ATOMIC_LOAD_MAX:
8622     case ISD::ATOMIC_LOAD_UMIN:
8623     case ISD::ATOMIC_LOAD_UMAX:
8624       break;
8625     default:
8626       return SDValue();
8627   }
8628   
8629   SDValue fence = atomic.getOperand(0);
8630   if (fence.getOpcode() != ISD::MEMBARRIER)
8631     return SDValue();
8632   
8633   switch (atomic.getOpcode()) {
8634     case ISD::ATOMIC_CMP_SWAP:
8635       return DAG.UpdateNodeOperands(atomic, fence.getOperand(0),
8636                                     atomic.getOperand(1), atomic.getOperand(2),
8637                                     atomic.getOperand(3));
8638     case ISD::ATOMIC_SWAP:
8639     case ISD::ATOMIC_LOAD_ADD:
8640     case ISD::ATOMIC_LOAD_SUB:
8641     case ISD::ATOMIC_LOAD_AND:
8642     case ISD::ATOMIC_LOAD_OR:
8643     case ISD::ATOMIC_LOAD_XOR:
8644     case ISD::ATOMIC_LOAD_NAND:
8645     case ISD::ATOMIC_LOAD_MIN:
8646     case ISD::ATOMIC_LOAD_MAX:
8647     case ISD::ATOMIC_LOAD_UMIN:
8648     case ISD::ATOMIC_LOAD_UMAX:
8649       return DAG.UpdateNodeOperands(atomic, fence.getOperand(0),
8650                                     atomic.getOperand(1), atomic.getOperand(2));
8651     default:
8652       return SDValue();
8653   }
8654 }
8655
8656 SDValue X86TargetLowering::PerformDAGCombine(SDNode *N,
8657                                              DAGCombinerInfo &DCI) const {
8658   SelectionDAG &DAG = DCI.DAG;
8659   switch (N->getOpcode()) {
8660   default: break;
8661   case ISD::VECTOR_SHUFFLE: return PerformShuffleCombine(N, DAG, *this);
8662   case ISD::SELECT:         return PerformSELECTCombine(N, DAG, Subtarget);
8663   case X86ISD::CMOV:        return PerformCMOVCombine(N, DAG, DCI);
8664   case ISD::MUL:            return PerformMulCombine(N, DAG, DCI);
8665   case ISD::SHL:
8666   case ISD::SRA:
8667   case ISD::SRL:            return PerformShiftCombine(N, DAG, Subtarget);
8668   case ISD::STORE:          return PerformSTORECombine(N, DAG, Subtarget);
8669   case X86ISD::FXOR:
8670   case X86ISD::FOR:         return PerformFORCombine(N, DAG);
8671   case X86ISD::FAND:        return PerformFANDCombine(N, DAG);
8672   case X86ISD::BT:          return PerformBTCombine(N, DAG, DCI);
8673   case X86ISD::VZEXT_MOVL:  return PerformVZEXT_MOVLCombine(N, DAG);
8674   case ISD::MEMBARRIER:     return PerformMEMBARRIERCombine(N, DAG);
8675   }
8676
8677   return SDValue();
8678 }
8679
8680 //===----------------------------------------------------------------------===//
8681 //                           X86 Inline Assembly Support
8682 //===----------------------------------------------------------------------===//
8683
8684 static bool LowerToBSwap(CallInst *CI) {
8685   // FIXME: this should verify that we are targetting a 486 or better.  If not,
8686   // we will turn this bswap into something that will be lowered to logical ops
8687   // instead of emitting the bswap asm.  For now, we don't support 486 or lower
8688   // so don't worry about this.
8689   
8690   // Verify this is a simple bswap.
8691   if (CI->getNumOperands() != 2 ||
8692       CI->getType() != CI->getOperand(1)->getType() ||
8693       !CI->getType()->isInteger())
8694     return false;
8695   
8696   const IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
8697   if (!Ty || Ty->getBitWidth() % 16 != 0)
8698     return false;
8699   
8700   // Okay, we can do this xform, do so now.
8701   const Type *Tys[] = { Ty };
8702   Module *M = CI->getParent()->getParent()->getParent();
8703   Constant *Int = Intrinsic::getDeclaration(M, Intrinsic::bswap, Tys, 1);
8704   
8705   Value *Op = CI->getOperand(1);
8706   Op = CallInst::Create(Int, Op, CI->getName(), CI);
8707   
8708   CI->replaceAllUsesWith(Op);
8709   CI->eraseFromParent();
8710   return true;
8711 }
8712
8713 bool X86TargetLowering::ExpandInlineAsm(CallInst *CI) const {
8714   InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue());
8715   std::vector<InlineAsm::ConstraintInfo> Constraints = IA->ParseConstraints();
8716
8717   std::string AsmStr = IA->getAsmString();
8718
8719   // TODO: should remove alternatives from the asmstring: "foo {a|b}" -> "foo a"
8720   std::vector<std::string> AsmPieces;
8721   SplitString(AsmStr, AsmPieces, "\n");  // ; as separator?
8722
8723   switch (AsmPieces.size()) {
8724   default: return false;
8725   case 1:
8726     AsmStr = AsmPieces[0];
8727     AsmPieces.clear();
8728     SplitString(AsmStr, AsmPieces, " \t");  // Split with whitespace.
8729
8730     // bswap $0
8731     if (AsmPieces.size() == 2 &&
8732         (AsmPieces[0] == "bswap" ||
8733          AsmPieces[0] == "bswapq" ||
8734          AsmPieces[0] == "bswapl") &&
8735         (AsmPieces[1] == "$0" ||
8736          AsmPieces[1] == "${0:q}")) {
8737       // No need to check constraints, nothing other than the equivalent of
8738       // "=r,0" would be valid here.
8739       return LowerToBSwap(CI);
8740     }
8741     // rorw $$8, ${0:w}  -->  llvm.bswap.i16
8742     if (CI->getType() == Type::Int16Ty &&
8743         AsmPieces.size() == 3 &&
8744         AsmPieces[0] == "rorw" &&
8745         AsmPieces[1] == "$$8," &&
8746         AsmPieces[2] == "${0:w}" &&
8747         IA->getConstraintString() == "=r,0,~{dirflag},~{fpsr},~{flags},~{cc}") {
8748       return LowerToBSwap(CI);
8749     }
8750     break;
8751   case 3:
8752     if (CI->getType() == Type::Int64Ty && Constraints.size() >= 2 &&
8753         Constraints[0].Codes.size() == 1 && Constraints[0].Codes[0] == "A" &&
8754         Constraints[1].Codes.size() == 1 && Constraints[1].Codes[0] == "0") {
8755       // bswap %eax / bswap %edx / xchgl %eax, %edx  -> llvm.bswap.i64
8756       std::vector<std::string> Words;
8757       SplitString(AsmPieces[0], Words, " \t");
8758       if (Words.size() == 2 && Words[0] == "bswap" && Words[1] == "%eax") {
8759         Words.clear();
8760         SplitString(AsmPieces[1], Words, " \t");
8761         if (Words.size() == 2 && Words[0] == "bswap" && Words[1] == "%edx") {
8762           Words.clear();
8763           SplitString(AsmPieces[2], Words, " \t,");
8764           if (Words.size() == 3 && Words[0] == "xchgl" && Words[1] == "%eax" &&
8765               Words[2] == "%edx") {
8766             return LowerToBSwap(CI);
8767           }
8768         }
8769       }
8770     }
8771     break;
8772   }
8773   return false;
8774 }
8775
8776
8777
8778 /// getConstraintType - Given a constraint letter, return the type of
8779 /// constraint it is for this target.
8780 X86TargetLowering::ConstraintType
8781 X86TargetLowering::getConstraintType(const std::string &Constraint) const {
8782   if (Constraint.size() == 1) {
8783     switch (Constraint[0]) {
8784     case 'A':
8785       return C_Register;
8786     case 'f':
8787     case 'r':
8788     case 'R':
8789     case 'l':
8790     case 'q':
8791     case 'Q':
8792     case 'x':
8793     case 'y':
8794     case 'Y':
8795       return C_RegisterClass;
8796     case 'e':
8797     case 'Z':
8798       return C_Other;
8799     default:
8800       break;
8801     }
8802   }
8803   return TargetLowering::getConstraintType(Constraint);
8804 }
8805
8806 /// LowerXConstraint - try to replace an X constraint, which matches anything,
8807 /// with another that has more specific requirements based on the type of the
8808 /// corresponding operand.
8809 const char *X86TargetLowering::
8810 LowerXConstraint(MVT ConstraintVT) const {
8811   // FP X constraints get lowered to SSE1/2 registers if available, otherwise
8812   // 'f' like normal targets.
8813   if (ConstraintVT.isFloatingPoint()) {
8814     if (Subtarget->hasSSE2())
8815       return "Y";
8816     if (Subtarget->hasSSE1())
8817       return "x";
8818   }
8819
8820   return TargetLowering::LowerXConstraint(ConstraintVT);
8821 }
8822
8823 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
8824 /// vector.  If it is invalid, don't add anything to Ops.
8825 void X86TargetLowering::LowerAsmOperandForConstraint(SDValue Op,
8826                                                      char Constraint,
8827                                                      bool hasMemory,
8828                                                      std::vector<SDValue>&Ops,
8829                                                      SelectionDAG &DAG) const {
8830   SDValue Result(0, 0);
8831
8832   switch (Constraint) {
8833   default: break;
8834   case 'I':
8835     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
8836       if (C->getZExtValue() <= 31) {
8837         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
8838         break;
8839       }
8840     }
8841     return;
8842   case 'J':
8843     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
8844       if (C->getZExtValue() <= 63) {
8845         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
8846         break;
8847       }
8848     }
8849     return;
8850   case 'K':
8851     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
8852       if ((int8_t)C->getSExtValue() == C->getSExtValue()) {
8853         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
8854         break;
8855       }
8856     }
8857     return;
8858   case 'N':
8859     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
8860       if (C->getZExtValue() <= 255) {
8861         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
8862         break;
8863       }
8864     }
8865     return;
8866   case 'e': {
8867     // 32-bit signed value
8868     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
8869       const ConstantInt *CI = C->getConstantIntValue();
8870       if (CI->isValueValidForType(Type::Int32Ty, C->getSExtValue())) {
8871         // Widen to 64 bits here to get it sign extended.
8872         Result = DAG.getTargetConstant(C->getSExtValue(), MVT::i64);
8873         break;
8874       }
8875     // FIXME gcc accepts some relocatable values here too, but only in certain
8876     // memory models; it's complicated.
8877     }
8878     return;
8879   }
8880   case 'Z': {
8881     // 32-bit unsigned value
8882     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
8883       const ConstantInt *CI = C->getConstantIntValue();
8884       if (CI->isValueValidForType(Type::Int32Ty, C->getZExtValue())) {
8885         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
8886         break;
8887       }
8888     }
8889     // FIXME gcc accepts some relocatable values here too, but only in certain
8890     // memory models; it's complicated.
8891     return;
8892   }
8893   case 'i': {
8894     // Literal immediates are always ok.
8895     if (ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op)) {
8896       // Widen to 64 bits here to get it sign extended.
8897       Result = DAG.getTargetConstant(CST->getSExtValue(), MVT::i64);
8898       break;
8899     }
8900
8901     // If we are in non-pic codegen mode, we allow the address of a global (with
8902     // an optional displacement) to be used with 'i'.
8903     GlobalAddressSDNode *GA = 0;
8904     int64_t Offset = 0;
8905
8906     // Match either (GA), (GA+C), (GA+C1+C2), etc.
8907     while (1) {
8908       if ((GA = dyn_cast<GlobalAddressSDNode>(Op))) {
8909         Offset += GA->getOffset();
8910         break;
8911       } else if (Op.getOpcode() == ISD::ADD) {
8912         if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
8913           Offset += C->getZExtValue();
8914           Op = Op.getOperand(0);
8915           continue;
8916         }
8917       } else if (Op.getOpcode() == ISD::SUB) {
8918         if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
8919           Offset += -C->getZExtValue();
8920           Op = Op.getOperand(0);
8921           continue;
8922         }
8923       }
8924
8925       // Otherwise, this isn't something we can handle, reject it.
8926       return;
8927     }
8928     
8929     GlobalValue *GV = GA->getGlobal();
8930     // If we require an extra load to get this address, as in PIC mode, we
8931     // can't accept it.
8932     if (isGlobalStubReference(Subtarget->ClassifyGlobalReference(GV,
8933                                                         getTargetMachine())))
8934       return;
8935
8936     if (hasMemory)
8937       Op = LowerGlobalAddress(GV, Op.getDebugLoc(), Offset, DAG);
8938     else
8939       Op = DAG.getTargetGlobalAddress(GV, GA->getValueType(0), Offset);
8940     Result = Op;
8941     break;
8942   }
8943   }
8944
8945   if (Result.getNode()) {
8946     Ops.push_back(Result);
8947     return;
8948   }
8949   return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, hasMemory,
8950                                                       Ops, DAG);
8951 }
8952
8953 std::vector<unsigned> X86TargetLowering::
8954 getRegClassForInlineAsmConstraint(const std::string &Constraint,
8955                                   MVT VT) const {
8956   if (Constraint.size() == 1) {
8957     // FIXME: not handling fp-stack yet!
8958     switch (Constraint[0]) {      // GCC X86 Constraint Letters
8959     default: break;  // Unknown constraint letter
8960     case 'q':   // GENERAL_REGS in 64-bit mode, Q_REGS in 32-bit mode.
8961       if (Subtarget->is64Bit()) {
8962         if (VT == MVT::i32)
8963           return make_vector<unsigned>(X86::EAX, X86::EDX, X86::ECX, X86::EBX,
8964                                        X86::ESI, X86::EDI, X86::R8D, X86::R9D,
8965                                        X86::R10D,X86::R11D,X86::R12D,
8966                                        X86::R13D,X86::R14D,X86::R15D,
8967                                        X86::EBP, X86::ESP, 0);
8968         else if (VT == MVT::i16)
8969           return make_vector<unsigned>(X86::AX,  X86::DX,  X86::CX, X86::BX,
8970                                        X86::SI,  X86::DI,  X86::R8W,X86::R9W,
8971                                        X86::R10W,X86::R11W,X86::R12W,
8972                                        X86::R13W,X86::R14W,X86::R15W,
8973                                        X86::BP,  X86::SP, 0);
8974         else if (VT == MVT::i8)
8975           return make_vector<unsigned>(X86::AL,  X86::DL,  X86::CL, X86::BL,
8976                                        X86::SIL, X86::DIL, X86::R8B,X86::R9B,
8977                                        X86::R10B,X86::R11B,X86::R12B,
8978                                        X86::R13B,X86::R14B,X86::R15B,
8979                                        X86::BPL, X86::SPL, 0);
8980
8981         else if (VT == MVT::i64)
8982           return make_vector<unsigned>(X86::RAX, X86::RDX, X86::RCX, X86::RBX,
8983                                        X86::RSI, X86::RDI, X86::R8,  X86::R9,
8984                                        X86::R10, X86::R11, X86::R12,
8985                                        X86::R13, X86::R14, X86::R15,
8986                                        X86::RBP, X86::RSP, 0);
8987
8988         break;
8989       }
8990       // 32-bit fallthrough 
8991     case 'Q':   // Q_REGS
8992       if (VT == MVT::i32)
8993         return make_vector<unsigned>(X86::EAX, X86::EDX, X86::ECX, X86::EBX, 0);
8994       else if (VT == MVT::i16)
8995         return make_vector<unsigned>(X86::AX, X86::DX, X86::CX, X86::BX, 0);
8996       else if (VT == MVT::i8)
8997         return make_vector<unsigned>(X86::AL, X86::DL, X86::CL, X86::BL, 0);
8998       else if (VT == MVT::i64)
8999         return make_vector<unsigned>(X86::RAX, X86::RDX, X86::RCX, X86::RBX, 0);
9000       break;
9001     }
9002   }
9003
9004   return std::vector<unsigned>();
9005 }
9006
9007 std::pair<unsigned, const TargetRegisterClass*>
9008 X86TargetLowering::getRegForInlineAsmConstraint(const std::string &Constraint,
9009                                                 MVT VT) const {
9010   // First, see if this is a constraint that directly corresponds to an LLVM
9011   // register class.
9012   if (Constraint.size() == 1) {
9013     // GCC Constraint Letters
9014     switch (Constraint[0]) {
9015     default: break;
9016     case 'r':   // GENERAL_REGS
9017     case 'R':   // LEGACY_REGS
9018     case 'l':   // INDEX_REGS
9019       if (VT == MVT::i8)
9020         return std::make_pair(0U, X86::GR8RegisterClass);
9021       if (VT == MVT::i16)
9022         return std::make_pair(0U, X86::GR16RegisterClass);
9023       if (VT == MVT::i32 || !Subtarget->is64Bit())
9024         return std::make_pair(0U, X86::GR32RegisterClass);
9025       return std::make_pair(0U, X86::GR64RegisterClass);
9026     case 'f':  // FP Stack registers.
9027       // If SSE is enabled for this VT, use f80 to ensure the isel moves the
9028       // value to the correct fpstack register class.
9029       if (VT == MVT::f32 && !isScalarFPTypeInSSEReg(VT))
9030         return std::make_pair(0U, X86::RFP32RegisterClass);
9031       if (VT == MVT::f64 && !isScalarFPTypeInSSEReg(VT))
9032         return std::make_pair(0U, X86::RFP64RegisterClass);
9033       return std::make_pair(0U, X86::RFP80RegisterClass);
9034     case 'y':   // MMX_REGS if MMX allowed.
9035       if (!Subtarget->hasMMX()) break;
9036       return std::make_pair(0U, X86::VR64RegisterClass);
9037     case 'Y':   // SSE_REGS if SSE2 allowed
9038       if (!Subtarget->hasSSE2()) break;
9039       // FALL THROUGH.
9040     case 'x':   // SSE_REGS if SSE1 allowed
9041       if (!Subtarget->hasSSE1()) break;
9042
9043       switch (VT.getSimpleVT()) {
9044       default: break;
9045       // Scalar SSE types.
9046       case MVT::f32:
9047       case MVT::i32:
9048         return std::make_pair(0U, X86::FR32RegisterClass);
9049       case MVT::f64:
9050       case MVT::i64:
9051         return std::make_pair(0U, X86::FR64RegisterClass);
9052       // Vector types.
9053       case MVT::v16i8:
9054       case MVT::v8i16:
9055       case MVT::v4i32:
9056       case MVT::v2i64:
9057       case MVT::v4f32:
9058       case MVT::v2f64:
9059         return std::make_pair(0U, X86::VR128RegisterClass);
9060       }
9061       break;
9062     }
9063   }
9064
9065   // Use the default implementation in TargetLowering to convert the register
9066   // constraint into a member of a register class.
9067   std::pair<unsigned, const TargetRegisterClass*> Res;
9068   Res = TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
9069
9070   // Not found as a standard register?
9071   if (Res.second == 0) {
9072     // GCC calls "st(0)" just plain "st".
9073     if (StringsEqualNoCase("{st}", Constraint)) {
9074       Res.first = X86::ST0;
9075       Res.second = X86::RFP80RegisterClass;
9076     }
9077     // 'A' means EAX + EDX.
9078     if (Constraint == "A") {
9079       Res.first = X86::EAX;
9080       Res.second = X86::GRADRegisterClass;
9081     }
9082     return Res;
9083   }
9084
9085   // Otherwise, check to see if this is a register class of the wrong value
9086   // type.  For example, we want to map "{ax},i32" -> {eax}, we don't want it to
9087   // turn into {ax},{dx}.
9088   if (Res.second->hasType(VT))
9089     return Res;   // Correct type already, nothing to do.
9090
9091   // All of the single-register GCC register classes map their values onto
9092   // 16-bit register pieces "ax","dx","cx","bx","si","di","bp","sp".  If we
9093   // really want an 8-bit or 32-bit register, map to the appropriate register
9094   // class and return the appropriate register.
9095   if (Res.second == X86::GR16RegisterClass) {
9096     if (VT == MVT::i8) {
9097       unsigned DestReg = 0;
9098       switch (Res.first) {
9099       default: break;
9100       case X86::AX: DestReg = X86::AL; break;
9101       case X86::DX: DestReg = X86::DL; break;
9102       case X86::CX: DestReg = X86::CL; break;
9103       case X86::BX: DestReg = X86::BL; break;
9104       }
9105       if (DestReg) {
9106         Res.first = DestReg;
9107         Res.second = X86::GR8RegisterClass;
9108       }
9109     } else if (VT == MVT::i32) {
9110       unsigned DestReg = 0;
9111       switch (Res.first) {
9112       default: break;
9113       case X86::AX: DestReg = X86::EAX; break;
9114       case X86::DX: DestReg = X86::EDX; break;
9115       case X86::CX: DestReg = X86::ECX; break;
9116       case X86::BX: DestReg = X86::EBX; break;
9117       case X86::SI: DestReg = X86::ESI; break;
9118       case X86::DI: DestReg = X86::EDI; break;
9119       case X86::BP: DestReg = X86::EBP; break;
9120       case X86::SP: DestReg = X86::ESP; break;
9121       }
9122       if (DestReg) {
9123         Res.first = DestReg;
9124         Res.second = X86::GR32RegisterClass;
9125       }
9126     } else if (VT == MVT::i64) {
9127       unsigned DestReg = 0;
9128       switch (Res.first) {
9129       default: break;
9130       case X86::AX: DestReg = X86::RAX; break;
9131       case X86::DX: DestReg = X86::RDX; break;
9132       case X86::CX: DestReg = X86::RCX; break;
9133       case X86::BX: DestReg = X86::RBX; break;
9134       case X86::SI: DestReg = X86::RSI; break;
9135       case X86::DI: DestReg = X86::RDI; break;
9136       case X86::BP: DestReg = X86::RBP; break;
9137       case X86::SP: DestReg = X86::RSP; break;
9138       }
9139       if (DestReg) {
9140         Res.first = DestReg;
9141         Res.second = X86::GR64RegisterClass;
9142       }
9143     }
9144   } else if (Res.second == X86::FR32RegisterClass ||
9145              Res.second == X86::FR64RegisterClass ||
9146              Res.second == X86::VR128RegisterClass) {
9147     // Handle references to XMM physical registers that got mapped into the
9148     // wrong class.  This can happen with constraints like {xmm0} where the
9149     // target independent register mapper will just pick the first match it can
9150     // find, ignoring the required type.
9151     if (VT == MVT::f32)
9152       Res.second = X86::FR32RegisterClass;
9153     else if (VT == MVT::f64)
9154       Res.second = X86::FR64RegisterClass;
9155     else if (X86::VR128RegisterClass->hasType(VT))
9156       Res.second = X86::VR128RegisterClass;
9157   }
9158
9159   return Res;
9160 }
9161
9162 //===----------------------------------------------------------------------===//
9163 //                           X86 Widen vector type
9164 //===----------------------------------------------------------------------===//
9165
9166 /// getWidenVectorType: given a vector type, returns the type to widen
9167 /// to (e.g., v7i8 to v8i8). If the vector type is legal, it returns itself.
9168 /// If there is no vector type that we want to widen to, returns MVT::Other
9169 /// When and where to widen is target dependent based on the cost of
9170 /// scalarizing vs using the wider vector type.
9171
9172 MVT X86TargetLowering::getWidenVectorType(MVT VT) const {
9173   assert(VT.isVector());
9174   if (isTypeLegal(VT))
9175     return VT;
9176
9177   // TODO: In computeRegisterProperty, we can compute the list of legal vector
9178   //       type based on element type.  This would speed up our search (though
9179   //       it may not be worth it since the size of the list is relatively
9180   //       small).
9181   MVT EltVT = VT.getVectorElementType();
9182   unsigned NElts = VT.getVectorNumElements();
9183
9184   // On X86, it make sense to widen any vector wider than 1
9185   if (NElts <= 1)
9186     return MVT::Other;
9187
9188   for (unsigned nVT = MVT::FIRST_VECTOR_VALUETYPE;
9189        nVT <= MVT::LAST_VECTOR_VALUETYPE; ++nVT) {
9190     MVT SVT = (MVT::SimpleValueType)nVT;
9191
9192     if (isTypeLegal(SVT) &&
9193         SVT.getVectorElementType() == EltVT &&
9194         SVT.getVectorNumElements() > NElts)
9195       return SVT;
9196   }
9197   return MVT::Other;
9198 }