Code refactoring, no functionality change.
[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 "X86TargetObjectFile.h"
20 #include "llvm/CallingConv.h"
21 #include "llvm/Constants.h"
22 #include "llvm/DerivedTypes.h"
23 #include "llvm/GlobalAlias.h"
24 #include "llvm/GlobalVariable.h"
25 #include "llvm/Function.h"
26 #include "llvm/Instructions.h"
27 #include "llvm/Intrinsics.h"
28 #include "llvm/LLVMContext.h"
29 #include "llvm/CodeGen/MachineFrameInfo.h"
30 #include "llvm/CodeGen/MachineFunction.h"
31 #include "llvm/CodeGen/MachineInstrBuilder.h"
32 #include "llvm/CodeGen/MachineJumpTableInfo.h"
33 #include "llvm/CodeGen/MachineModuleInfo.h"
34 #include "llvm/CodeGen/MachineRegisterInfo.h"
35 #include "llvm/CodeGen/PseudoSourceValue.h"
36 #include "llvm/MC/MCAsmInfo.h"
37 #include "llvm/MC/MCContext.h"
38 #include "llvm/MC/MCExpr.h"
39 #include "llvm/MC/MCSymbol.h"
40 #include "llvm/ADT/BitVector.h"
41 #include "llvm/ADT/SmallSet.h"
42 #include "llvm/ADT/StringExtras.h"
43 #include "llvm/ADT/VectorExtras.h"
44 #include "llvm/Support/CommandLine.h"
45 #include "llvm/Support/Debug.h"
46 #include "llvm/Support/ErrorHandling.h"
47 #include "llvm/Support/MathExtras.h"
48 #include "llvm/Support/raw_ostream.h"
49 using namespace llvm;
50
51 static cl::opt<bool>
52 DisableMMX("disable-mmx", cl::Hidden, cl::desc("Disable use of MMX"));
53
54 // Disable16Bit - 16-bit operations typically have a larger encoding than
55 // corresponding 32-bit instructions, and 16-bit code is slow on some
56 // processors. This is an experimental flag to disable 16-bit operations
57 // (which forces them to be Legalized to 32-bit operations).
58 static cl::opt<bool>
59 Disable16Bit("disable-16bit", cl::Hidden,
60              cl::desc("Disable use of 16-bit instructions"));
61
62 // Forward declarations.
63 static SDValue getMOVL(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
64                        SDValue V2);
65
66 static TargetLoweringObjectFile *createTLOF(X86TargetMachine &TM) {
67   switch (TM.getSubtarget<X86Subtarget>().TargetType) {
68   default: llvm_unreachable("unknown subtarget type");
69   case X86Subtarget::isDarwin:
70     if (TM.getSubtarget<X86Subtarget>().is64Bit())
71       return new X8664_MachoTargetObjectFile();
72     return new X8632_MachoTargetObjectFile();
73   case X86Subtarget::isELF:
74     return new TargetLoweringObjectFileELF();
75   case X86Subtarget::isMingw:
76   case X86Subtarget::isCygwin:
77   case X86Subtarget::isWindows:
78     return new TargetLoweringObjectFileCOFF();
79   }
80
81 }
82
83 X86TargetLowering::X86TargetLowering(X86TargetMachine &TM)
84   : TargetLowering(TM, createTLOF(TM)) {
85   Subtarget = &TM.getSubtarget<X86Subtarget>();
86   X86ScalarSSEf64 = Subtarget->hasSSE2();
87   X86ScalarSSEf32 = Subtarget->hasSSE1();
88   X86StackPtr = Subtarget->is64Bit() ? X86::RSP : X86::ESP;
89
90   RegInfo = TM.getRegisterInfo();
91   TD = getTargetData();
92
93   // Set up the TargetLowering object.
94
95   // X86 is weird, it always uses i8 for shift amounts and setcc results.
96   setShiftAmountType(MVT::i8);
97   setBooleanContents(ZeroOrOneBooleanContent);
98   setSchedulingPreference(SchedulingForRegPressure);
99   setStackPointerRegisterToSaveRestore(X86StackPtr);
100
101   if (Subtarget->isTargetDarwin()) {
102     // Darwin should use _setjmp/_longjmp instead of setjmp/longjmp.
103     setUseUnderscoreSetJmp(false);
104     setUseUnderscoreLongJmp(false);
105   } else if (Subtarget->isTargetMingw()) {
106     // MS runtime is weird: it exports _setjmp, but longjmp!
107     setUseUnderscoreSetJmp(true);
108     setUseUnderscoreLongJmp(false);
109   } else {
110     setUseUnderscoreSetJmp(true);
111     setUseUnderscoreLongJmp(true);
112   }
113
114   // Set up the register classes.
115   addRegisterClass(MVT::i8, X86::GR8RegisterClass);
116   if (!Disable16Bit)
117     addRegisterClass(MVT::i16, X86::GR16RegisterClass);
118   addRegisterClass(MVT::i32, X86::GR32RegisterClass);
119   if (Subtarget->is64Bit())
120     addRegisterClass(MVT::i64, X86::GR64RegisterClass);
121
122   setLoadExtAction(ISD::SEXTLOAD, MVT::i1, Promote);
123
124   // We don't accept any truncstore of integer registers.
125   setTruncStoreAction(MVT::i64, MVT::i32, Expand);
126   if (!Disable16Bit)
127     setTruncStoreAction(MVT::i64, MVT::i16, Expand);
128   setTruncStoreAction(MVT::i64, MVT::i8 , Expand);
129   if (!Disable16Bit)
130     setTruncStoreAction(MVT::i32, MVT::i16, Expand);
131   setTruncStoreAction(MVT::i32, MVT::i8 , Expand);
132   setTruncStoreAction(MVT::i16, MVT::i8,  Expand);
133
134   // SETOEQ and SETUNE require checking two conditions.
135   setCondCodeAction(ISD::SETOEQ, MVT::f32, Expand);
136   setCondCodeAction(ISD::SETOEQ, MVT::f64, Expand);
137   setCondCodeAction(ISD::SETOEQ, MVT::f80, Expand);
138   setCondCodeAction(ISD::SETUNE, MVT::f32, Expand);
139   setCondCodeAction(ISD::SETUNE, MVT::f64, Expand);
140   setCondCodeAction(ISD::SETUNE, MVT::f80, Expand);
141
142   // Promote all UINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have this
143   // operation.
144   setOperationAction(ISD::UINT_TO_FP       , MVT::i1   , Promote);
145   setOperationAction(ISD::UINT_TO_FP       , MVT::i8   , Promote);
146   setOperationAction(ISD::UINT_TO_FP       , MVT::i16  , Promote);
147
148   if (Subtarget->is64Bit()) {
149     setOperationAction(ISD::UINT_TO_FP     , MVT::i32  , Promote);
150     setOperationAction(ISD::UINT_TO_FP     , MVT::i64  , Expand);
151   } else if (!UseSoftFloat) {
152     if (X86ScalarSSEf64) {
153       // We have an impenetrably clever algorithm for ui64->double only.
154       setOperationAction(ISD::UINT_TO_FP   , MVT::i64  , Custom);
155     }
156     // We have an algorithm for SSE2, and we turn this into a 64-bit
157     // FILD for other targets.
158     setOperationAction(ISD::UINT_TO_FP   , MVT::i32  , Custom);
159   }
160
161   // Promote i1/i8 SINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have
162   // this operation.
163   setOperationAction(ISD::SINT_TO_FP       , MVT::i1   , Promote);
164   setOperationAction(ISD::SINT_TO_FP       , MVT::i8   , Promote);
165
166   if (!UseSoftFloat) {
167     // SSE has no i16 to fp conversion, only i32
168     if (X86ScalarSSEf32) {
169       setOperationAction(ISD::SINT_TO_FP     , MVT::i16  , Promote);
170       // f32 and f64 cases are Legal, f80 case is not
171       setOperationAction(ISD::SINT_TO_FP     , MVT::i32  , Custom);
172     } else {
173       setOperationAction(ISD::SINT_TO_FP     , MVT::i16  , Custom);
174       setOperationAction(ISD::SINT_TO_FP     , MVT::i32  , Custom);
175     }
176   } else {
177     setOperationAction(ISD::SINT_TO_FP     , MVT::i16  , Promote);
178     setOperationAction(ISD::SINT_TO_FP     , MVT::i32  , Promote);
179   }
180
181   // In 32-bit mode these are custom lowered.  In 64-bit mode F32 and F64
182   // are Legal, f80 is custom lowered.
183   setOperationAction(ISD::FP_TO_SINT     , MVT::i64  , Custom);
184   setOperationAction(ISD::SINT_TO_FP     , MVT::i64  , Custom);
185
186   // Promote i1/i8 FP_TO_SINT to larger FP_TO_SINTS's, as X86 doesn't have
187   // this operation.
188   setOperationAction(ISD::FP_TO_SINT       , MVT::i1   , Promote);
189   setOperationAction(ISD::FP_TO_SINT       , MVT::i8   , Promote);
190
191   if (X86ScalarSSEf32) {
192     setOperationAction(ISD::FP_TO_SINT     , MVT::i16  , Promote);
193     // f32 and f64 cases are Legal, f80 case is not
194     setOperationAction(ISD::FP_TO_SINT     , MVT::i32  , Custom);
195   } else {
196     setOperationAction(ISD::FP_TO_SINT     , MVT::i16  , Custom);
197     setOperationAction(ISD::FP_TO_SINT     , MVT::i32  , Custom);
198   }
199
200   // Handle FP_TO_UINT by promoting the destination to a larger signed
201   // conversion.
202   setOperationAction(ISD::FP_TO_UINT       , MVT::i1   , Promote);
203   setOperationAction(ISD::FP_TO_UINT       , MVT::i8   , Promote);
204   setOperationAction(ISD::FP_TO_UINT       , MVT::i16  , Promote);
205
206   if (Subtarget->is64Bit()) {
207     setOperationAction(ISD::FP_TO_UINT     , MVT::i64  , Expand);
208     setOperationAction(ISD::FP_TO_UINT     , MVT::i32  , Promote);
209   } else if (!UseSoftFloat) {
210     if (X86ScalarSSEf32 && !Subtarget->hasSSE3())
211       // Expand FP_TO_UINT into a select.
212       // FIXME: We would like to use a Custom expander here eventually to do
213       // the optimal thing for SSE vs. the default expansion in the legalizer.
214       setOperationAction(ISD::FP_TO_UINT   , MVT::i32  , Expand);
215     else
216       // With SSE3 we can use fisttpll to convert to a signed i64; without
217       // SSE, we're stuck with a fistpll.
218       setOperationAction(ISD::FP_TO_UINT   , MVT::i32  , Custom);
219   }
220
221   // TODO: when we have SSE, these could be more efficient, by using movd/movq.
222   if (!X86ScalarSSEf64) {
223     setOperationAction(ISD::BIT_CONVERT      , MVT::f32  , Expand);
224     setOperationAction(ISD::BIT_CONVERT      , MVT::i32  , Expand);
225   }
226
227   // Scalar integer divide and remainder are lowered to use operations that
228   // produce two results, to match the available instructions. This exposes
229   // the two-result form to trivial CSE, which is able to combine x/y and x%y
230   // into a single instruction.
231   //
232   // Scalar integer multiply-high is also lowered to use two-result
233   // operations, to match the available instructions. However, plain multiply
234   // (low) operations are left as Legal, as there are single-result
235   // instructions for this in x86. Using the two-result multiply instructions
236   // when both high and low results are needed must be arranged by dagcombine.
237   setOperationAction(ISD::MULHS           , MVT::i8    , Expand);
238   setOperationAction(ISD::MULHU           , MVT::i8    , Expand);
239   setOperationAction(ISD::SDIV            , MVT::i8    , Expand);
240   setOperationAction(ISD::UDIV            , MVT::i8    , Expand);
241   setOperationAction(ISD::SREM            , MVT::i8    , Expand);
242   setOperationAction(ISD::UREM            , MVT::i8    , Expand);
243   setOperationAction(ISD::MULHS           , MVT::i16   , Expand);
244   setOperationAction(ISD::MULHU           , MVT::i16   , Expand);
245   setOperationAction(ISD::SDIV            , MVT::i16   , Expand);
246   setOperationAction(ISD::UDIV            , MVT::i16   , Expand);
247   setOperationAction(ISD::SREM            , MVT::i16   , Expand);
248   setOperationAction(ISD::UREM            , MVT::i16   , Expand);
249   setOperationAction(ISD::MULHS           , MVT::i32   , Expand);
250   setOperationAction(ISD::MULHU           , MVT::i32   , Expand);
251   setOperationAction(ISD::SDIV            , MVT::i32   , Expand);
252   setOperationAction(ISD::UDIV            , MVT::i32   , Expand);
253   setOperationAction(ISD::SREM            , MVT::i32   , Expand);
254   setOperationAction(ISD::UREM            , MVT::i32   , Expand);
255   setOperationAction(ISD::MULHS           , MVT::i64   , Expand);
256   setOperationAction(ISD::MULHU           , MVT::i64   , Expand);
257   setOperationAction(ISD::SDIV            , MVT::i64   , Expand);
258   setOperationAction(ISD::UDIV            , MVT::i64   , Expand);
259   setOperationAction(ISD::SREM            , MVT::i64   , Expand);
260   setOperationAction(ISD::UREM            , MVT::i64   , Expand);
261
262   setOperationAction(ISD::BR_JT            , MVT::Other, Expand);
263   setOperationAction(ISD::BRCOND           , MVT::Other, Custom);
264   setOperationAction(ISD::BR_CC            , MVT::Other, Expand);
265   setOperationAction(ISD::SELECT_CC        , MVT::Other, Expand);
266   if (Subtarget->is64Bit())
267     setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i32, Legal);
268   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16  , Legal);
269   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8   , Legal);
270   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1   , Expand);
271   setOperationAction(ISD::FP_ROUND_INREG   , MVT::f32  , Expand);
272   setOperationAction(ISD::FREM             , MVT::f32  , Expand);
273   setOperationAction(ISD::FREM             , MVT::f64  , Expand);
274   setOperationAction(ISD::FREM             , MVT::f80  , Expand);
275   setOperationAction(ISD::FLT_ROUNDS_      , MVT::i32  , Custom);
276
277   setOperationAction(ISD::CTPOP            , MVT::i8   , Expand);
278   setOperationAction(ISD::CTTZ             , MVT::i8   , Custom);
279   setOperationAction(ISD::CTLZ             , MVT::i8   , Custom);
280   setOperationAction(ISD::CTPOP            , MVT::i16  , Expand);
281   if (Disable16Bit) {
282     setOperationAction(ISD::CTTZ           , MVT::i16  , Expand);
283     setOperationAction(ISD::CTLZ           , MVT::i16  , Expand);
284   } else {
285     setOperationAction(ISD::CTTZ           , MVT::i16  , Custom);
286     setOperationAction(ISD::CTLZ           , MVT::i16  , Custom);
287   }
288   setOperationAction(ISD::CTPOP            , MVT::i32  , Expand);
289   setOperationAction(ISD::CTTZ             , MVT::i32  , Custom);
290   setOperationAction(ISD::CTLZ             , MVT::i32  , Custom);
291   if (Subtarget->is64Bit()) {
292     setOperationAction(ISD::CTPOP          , MVT::i64  , Expand);
293     setOperationAction(ISD::CTTZ           , MVT::i64  , Custom);
294     setOperationAction(ISD::CTLZ           , MVT::i64  , Custom);
295   }
296
297   setOperationAction(ISD::READCYCLECOUNTER , MVT::i64  , Custom);
298   setOperationAction(ISD::BSWAP            , MVT::i16  , Expand);
299
300   // These should be promoted to a larger select which is supported.
301   setOperationAction(ISD::SELECT          , MVT::i1   , Promote);
302   // X86 wants to expand cmov itself.
303   setOperationAction(ISD::SELECT          , MVT::i8   , Custom);
304   if (Disable16Bit)
305     setOperationAction(ISD::SELECT        , MVT::i16  , Expand);
306   else
307     setOperationAction(ISD::SELECT        , MVT::i16  , Custom);
308   setOperationAction(ISD::SELECT          , MVT::i32  , Custom);
309   setOperationAction(ISD::SELECT          , MVT::f32  , Custom);
310   setOperationAction(ISD::SELECT          , MVT::f64  , Custom);
311   setOperationAction(ISD::SELECT          , MVT::f80  , Custom);
312   setOperationAction(ISD::SETCC           , MVT::i8   , Custom);
313   if (Disable16Bit)
314     setOperationAction(ISD::SETCC         , MVT::i16  , Expand);
315   else
316     setOperationAction(ISD::SETCC         , MVT::i16  , Custom);
317   setOperationAction(ISD::SETCC           , MVT::i32  , Custom);
318   setOperationAction(ISD::SETCC           , MVT::f32  , Custom);
319   setOperationAction(ISD::SETCC           , MVT::f64  , Custom);
320   setOperationAction(ISD::SETCC           , MVT::f80  , Custom);
321   if (Subtarget->is64Bit()) {
322     setOperationAction(ISD::SELECT        , MVT::i64  , Custom);
323     setOperationAction(ISD::SETCC         , MVT::i64  , Custom);
324   }
325   setOperationAction(ISD::EH_RETURN       , MVT::Other, Custom);
326
327   // Darwin ABI issue.
328   setOperationAction(ISD::ConstantPool    , MVT::i32  , Custom);
329   setOperationAction(ISD::JumpTable       , MVT::i32  , Custom);
330   setOperationAction(ISD::GlobalAddress   , MVT::i32  , Custom);
331   setOperationAction(ISD::GlobalTLSAddress, MVT::i32  , Custom);
332   if (Subtarget->is64Bit())
333     setOperationAction(ISD::GlobalTLSAddress, MVT::i64, Custom);
334   setOperationAction(ISD::ExternalSymbol  , MVT::i32  , Custom);
335   setOperationAction(ISD::BlockAddress    , MVT::i32  , Custom);
336   if (Subtarget->is64Bit()) {
337     setOperationAction(ISD::ConstantPool  , MVT::i64  , Custom);
338     setOperationAction(ISD::JumpTable     , MVT::i64  , Custom);
339     setOperationAction(ISD::GlobalAddress , MVT::i64  , Custom);
340     setOperationAction(ISD::ExternalSymbol, MVT::i64  , Custom);
341     setOperationAction(ISD::BlockAddress  , MVT::i64  , Custom);
342   }
343   // 64-bit addm sub, shl, sra, srl (iff 32-bit x86)
344   setOperationAction(ISD::SHL_PARTS       , MVT::i32  , Custom);
345   setOperationAction(ISD::SRA_PARTS       , MVT::i32  , Custom);
346   setOperationAction(ISD::SRL_PARTS       , MVT::i32  , Custom);
347   if (Subtarget->is64Bit()) {
348     setOperationAction(ISD::SHL_PARTS     , MVT::i64  , Custom);
349     setOperationAction(ISD::SRA_PARTS     , MVT::i64  , Custom);
350     setOperationAction(ISD::SRL_PARTS     , MVT::i64  , Custom);
351   }
352
353   if (Subtarget->hasSSE1())
354     setOperationAction(ISD::PREFETCH      , MVT::Other, Legal);
355
356   if (!Subtarget->hasSSE2())
357     setOperationAction(ISD::MEMBARRIER    , MVT::Other, Expand);
358
359   // Expand certain atomics
360   setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i8, Custom);
361   setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i16, Custom);
362   setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i32, Custom);
363   setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i64, Custom);
364
365   setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i8, Custom);
366   setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i16, Custom);
367   setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i32, Custom);
368   setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i64, Custom);
369
370   if (!Subtarget->is64Bit()) {
371     setOperationAction(ISD::ATOMIC_LOAD_ADD, MVT::i64, Custom);
372     setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i64, Custom);
373     setOperationAction(ISD::ATOMIC_LOAD_AND, MVT::i64, Custom);
374     setOperationAction(ISD::ATOMIC_LOAD_OR, MVT::i64, Custom);
375     setOperationAction(ISD::ATOMIC_LOAD_XOR, MVT::i64, Custom);
376     setOperationAction(ISD::ATOMIC_LOAD_NAND, MVT::i64, Custom);
377     setOperationAction(ISD::ATOMIC_SWAP, MVT::i64, Custom);
378   }
379
380   // FIXME - use subtarget debug flags
381   if (!Subtarget->isTargetDarwin() &&
382       !Subtarget->isTargetELF() &&
383       !Subtarget->isTargetCygMing()) {
384     setOperationAction(ISD::EH_LABEL, MVT::Other, Expand);
385   }
386
387   setOperationAction(ISD::EXCEPTIONADDR, MVT::i64, Expand);
388   setOperationAction(ISD::EHSELECTION,   MVT::i64, Expand);
389   setOperationAction(ISD::EXCEPTIONADDR, MVT::i32, Expand);
390   setOperationAction(ISD::EHSELECTION,   MVT::i32, Expand);
391   if (Subtarget->is64Bit()) {
392     setExceptionPointerRegister(X86::RAX);
393     setExceptionSelectorRegister(X86::RDX);
394   } else {
395     setExceptionPointerRegister(X86::EAX);
396     setExceptionSelectorRegister(X86::EDX);
397   }
398   setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i32, Custom);
399   setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i64, Custom);
400
401   setOperationAction(ISD::TRAMPOLINE, MVT::Other, Custom);
402
403   setOperationAction(ISD::TRAP, MVT::Other, Legal);
404
405   // VASTART needs to be custom lowered to use the VarArgsFrameIndex
406   setOperationAction(ISD::VASTART           , MVT::Other, Custom);
407   setOperationAction(ISD::VAEND             , MVT::Other, Expand);
408   if (Subtarget->is64Bit()) {
409     setOperationAction(ISD::VAARG           , MVT::Other, Custom);
410     setOperationAction(ISD::VACOPY          , MVT::Other, Custom);
411   } else {
412     setOperationAction(ISD::VAARG           , MVT::Other, Expand);
413     setOperationAction(ISD::VACOPY          , MVT::Other, Expand);
414   }
415
416   setOperationAction(ISD::STACKSAVE,          MVT::Other, Expand);
417   setOperationAction(ISD::STACKRESTORE,       MVT::Other, Expand);
418   if (Subtarget->is64Bit())
419     setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i64, Expand);
420   if (Subtarget->isTargetCygMing())
421     setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Custom);
422   else
423     setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Expand);
424
425   if (!UseSoftFloat && X86ScalarSSEf64) {
426     // f32 and f64 use SSE.
427     // Set up the FP register classes.
428     addRegisterClass(MVT::f32, X86::FR32RegisterClass);
429     addRegisterClass(MVT::f64, X86::FR64RegisterClass);
430
431     // Use ANDPD to simulate FABS.
432     setOperationAction(ISD::FABS , MVT::f64, Custom);
433     setOperationAction(ISD::FABS , MVT::f32, Custom);
434
435     // Use XORP to simulate FNEG.
436     setOperationAction(ISD::FNEG , MVT::f64, Custom);
437     setOperationAction(ISD::FNEG , MVT::f32, Custom);
438
439     // Use ANDPD and ORPD to simulate FCOPYSIGN.
440     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
441     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
442
443     // We don't support sin/cos/fmod
444     setOperationAction(ISD::FSIN , MVT::f64, Expand);
445     setOperationAction(ISD::FCOS , MVT::f64, Expand);
446     setOperationAction(ISD::FSIN , MVT::f32, Expand);
447     setOperationAction(ISD::FCOS , MVT::f32, Expand);
448
449     // Expand FP immediates into loads from the stack, except for the special
450     // cases we handle.
451     addLegalFPImmediate(APFloat(+0.0)); // xorpd
452     addLegalFPImmediate(APFloat(+0.0f)); // xorps
453   } else if (!UseSoftFloat && X86ScalarSSEf32) {
454     // Use SSE for f32, x87 for f64.
455     // Set up the FP register classes.
456     addRegisterClass(MVT::f32, X86::FR32RegisterClass);
457     addRegisterClass(MVT::f64, X86::RFP64RegisterClass);
458
459     // Use ANDPS to simulate FABS.
460     setOperationAction(ISD::FABS , MVT::f32, Custom);
461
462     // Use XORP to simulate FNEG.
463     setOperationAction(ISD::FNEG , MVT::f32, Custom);
464
465     setOperationAction(ISD::UNDEF,     MVT::f64, Expand);
466
467     // Use ANDPS and ORPS to simulate FCOPYSIGN.
468     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
469     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
470
471     // We don't support sin/cos/fmod
472     setOperationAction(ISD::FSIN , MVT::f32, Expand);
473     setOperationAction(ISD::FCOS , MVT::f32, Expand);
474
475     // Special cases we handle for FP constants.
476     addLegalFPImmediate(APFloat(+0.0f)); // xorps
477     addLegalFPImmediate(APFloat(+0.0)); // FLD0
478     addLegalFPImmediate(APFloat(+1.0)); // FLD1
479     addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
480     addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
481
482     if (!UnsafeFPMath) {
483       setOperationAction(ISD::FSIN           , MVT::f64  , Expand);
484       setOperationAction(ISD::FCOS           , MVT::f64  , Expand);
485     }
486   } else if (!UseSoftFloat) {
487     // f32 and f64 in x87.
488     // Set up the FP register classes.
489     addRegisterClass(MVT::f64, X86::RFP64RegisterClass);
490     addRegisterClass(MVT::f32, X86::RFP32RegisterClass);
491
492     setOperationAction(ISD::UNDEF,     MVT::f64, Expand);
493     setOperationAction(ISD::UNDEF,     MVT::f32, Expand);
494     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
495     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand);
496
497     if (!UnsafeFPMath) {
498       setOperationAction(ISD::FSIN           , MVT::f64  , Expand);
499       setOperationAction(ISD::FCOS           , MVT::f64  , Expand);
500     }
501     addLegalFPImmediate(APFloat(+0.0)); // FLD0
502     addLegalFPImmediate(APFloat(+1.0)); // FLD1
503     addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
504     addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
505     addLegalFPImmediate(APFloat(+0.0f)); // FLD0
506     addLegalFPImmediate(APFloat(+1.0f)); // FLD1
507     addLegalFPImmediate(APFloat(-0.0f)); // FLD0/FCHS
508     addLegalFPImmediate(APFloat(-1.0f)); // FLD1/FCHS
509   }
510
511   // Long double always uses X87.
512   if (!UseSoftFloat) {
513     addRegisterClass(MVT::f80, X86::RFP80RegisterClass);
514     setOperationAction(ISD::UNDEF,     MVT::f80, Expand);
515     setOperationAction(ISD::FCOPYSIGN, MVT::f80, Expand);
516     {
517       bool ignored;
518       APFloat TmpFlt(+0.0);
519       TmpFlt.convert(APFloat::x87DoubleExtended, APFloat::rmNearestTiesToEven,
520                      &ignored);
521       addLegalFPImmediate(TmpFlt);  // FLD0
522       TmpFlt.changeSign();
523       addLegalFPImmediate(TmpFlt);  // FLD0/FCHS
524       APFloat TmpFlt2(+1.0);
525       TmpFlt2.convert(APFloat::x87DoubleExtended, APFloat::rmNearestTiesToEven,
526                       &ignored);
527       addLegalFPImmediate(TmpFlt2);  // FLD1
528       TmpFlt2.changeSign();
529       addLegalFPImmediate(TmpFlt2);  // FLD1/FCHS
530     }
531
532     if (!UnsafeFPMath) {
533       setOperationAction(ISD::FSIN           , MVT::f80  , Expand);
534       setOperationAction(ISD::FCOS           , MVT::f80  , Expand);
535     }
536   }
537
538   // Always use a library call for pow.
539   setOperationAction(ISD::FPOW             , MVT::f32  , Expand);
540   setOperationAction(ISD::FPOW             , MVT::f64  , Expand);
541   setOperationAction(ISD::FPOW             , MVT::f80  , Expand);
542
543   setOperationAction(ISD::FLOG, MVT::f80, Expand);
544   setOperationAction(ISD::FLOG2, MVT::f80, Expand);
545   setOperationAction(ISD::FLOG10, MVT::f80, Expand);
546   setOperationAction(ISD::FEXP, MVT::f80, Expand);
547   setOperationAction(ISD::FEXP2, MVT::f80, Expand);
548
549   // First set operation action for all vector types to either promote
550   // (for widening) or expand (for scalarization). Then we will selectively
551   // turn on ones that can be effectively codegen'd.
552   for (unsigned VT = (unsigned)MVT::FIRST_VECTOR_VALUETYPE;
553        VT <= (unsigned)MVT::LAST_VECTOR_VALUETYPE; ++VT) {
554     setOperationAction(ISD::ADD , (MVT::SimpleValueType)VT, Expand);
555     setOperationAction(ISD::SUB , (MVT::SimpleValueType)VT, Expand);
556     setOperationAction(ISD::FADD, (MVT::SimpleValueType)VT, Expand);
557     setOperationAction(ISD::FNEG, (MVT::SimpleValueType)VT, Expand);
558     setOperationAction(ISD::FSUB, (MVT::SimpleValueType)VT, Expand);
559     setOperationAction(ISD::MUL , (MVT::SimpleValueType)VT, Expand);
560     setOperationAction(ISD::FMUL, (MVT::SimpleValueType)VT, Expand);
561     setOperationAction(ISD::SDIV, (MVT::SimpleValueType)VT, Expand);
562     setOperationAction(ISD::UDIV, (MVT::SimpleValueType)VT, Expand);
563     setOperationAction(ISD::FDIV, (MVT::SimpleValueType)VT, Expand);
564     setOperationAction(ISD::SREM, (MVT::SimpleValueType)VT, Expand);
565     setOperationAction(ISD::UREM, (MVT::SimpleValueType)VT, Expand);
566     setOperationAction(ISD::LOAD, (MVT::SimpleValueType)VT, Expand);
567     setOperationAction(ISD::VECTOR_SHUFFLE, (MVT::SimpleValueType)VT, Expand);
568     setOperationAction(ISD::EXTRACT_VECTOR_ELT,(MVT::SimpleValueType)VT,Expand);
569     setOperationAction(ISD::EXTRACT_SUBVECTOR,(MVT::SimpleValueType)VT,Expand);
570     setOperationAction(ISD::INSERT_VECTOR_ELT,(MVT::SimpleValueType)VT, Expand);
571     setOperationAction(ISD::FABS, (MVT::SimpleValueType)VT, Expand);
572     setOperationAction(ISD::FSIN, (MVT::SimpleValueType)VT, Expand);
573     setOperationAction(ISD::FCOS, (MVT::SimpleValueType)VT, Expand);
574     setOperationAction(ISD::FREM, (MVT::SimpleValueType)VT, Expand);
575     setOperationAction(ISD::FPOWI, (MVT::SimpleValueType)VT, Expand);
576     setOperationAction(ISD::FSQRT, (MVT::SimpleValueType)VT, Expand);
577     setOperationAction(ISD::FCOPYSIGN, (MVT::SimpleValueType)VT, Expand);
578     setOperationAction(ISD::SMUL_LOHI, (MVT::SimpleValueType)VT, Expand);
579     setOperationAction(ISD::UMUL_LOHI, (MVT::SimpleValueType)VT, Expand);
580     setOperationAction(ISD::SDIVREM, (MVT::SimpleValueType)VT, Expand);
581     setOperationAction(ISD::UDIVREM, (MVT::SimpleValueType)VT, Expand);
582     setOperationAction(ISD::FPOW, (MVT::SimpleValueType)VT, Expand);
583     setOperationAction(ISD::CTPOP, (MVT::SimpleValueType)VT, Expand);
584     setOperationAction(ISD::CTTZ, (MVT::SimpleValueType)VT, Expand);
585     setOperationAction(ISD::CTLZ, (MVT::SimpleValueType)VT, Expand);
586     setOperationAction(ISD::SHL, (MVT::SimpleValueType)VT, Expand);
587     setOperationAction(ISD::SRA, (MVT::SimpleValueType)VT, Expand);
588     setOperationAction(ISD::SRL, (MVT::SimpleValueType)VT, Expand);
589     setOperationAction(ISD::ROTL, (MVT::SimpleValueType)VT, Expand);
590     setOperationAction(ISD::ROTR, (MVT::SimpleValueType)VT, Expand);
591     setOperationAction(ISD::BSWAP, (MVT::SimpleValueType)VT, Expand);
592     setOperationAction(ISD::VSETCC, (MVT::SimpleValueType)VT, Expand);
593     setOperationAction(ISD::FLOG, (MVT::SimpleValueType)VT, Expand);
594     setOperationAction(ISD::FLOG2, (MVT::SimpleValueType)VT, Expand);
595     setOperationAction(ISD::FLOG10, (MVT::SimpleValueType)VT, Expand);
596     setOperationAction(ISD::FEXP, (MVT::SimpleValueType)VT, Expand);
597     setOperationAction(ISD::FEXP2, (MVT::SimpleValueType)VT, Expand);
598     setOperationAction(ISD::FP_TO_UINT, (MVT::SimpleValueType)VT, Expand);
599     setOperationAction(ISD::FP_TO_SINT, (MVT::SimpleValueType)VT, Expand);
600     setOperationAction(ISD::UINT_TO_FP, (MVT::SimpleValueType)VT, Expand);
601     setOperationAction(ISD::SINT_TO_FP, (MVT::SimpleValueType)VT, Expand);
602     setOperationAction(ISD::SIGN_EXTEND_INREG, (MVT::SimpleValueType)VT,Expand);
603     setOperationAction(ISD::TRUNCATE,  (MVT::SimpleValueType)VT, Expand);
604     setOperationAction(ISD::SIGN_EXTEND,  (MVT::SimpleValueType)VT, Expand);
605     setOperationAction(ISD::ZERO_EXTEND,  (MVT::SimpleValueType)VT, Expand);
606     setOperationAction(ISD::ANY_EXTEND,  (MVT::SimpleValueType)VT, Expand);
607     for (unsigned InnerVT = (unsigned)MVT::FIRST_VECTOR_VALUETYPE;
608          InnerVT <= (unsigned)MVT::LAST_VECTOR_VALUETYPE; ++InnerVT)
609       setTruncStoreAction((MVT::SimpleValueType)VT,
610                           (MVT::SimpleValueType)InnerVT, Expand);
611     setLoadExtAction(ISD::SEXTLOAD, (MVT::SimpleValueType)VT, Expand);
612     setLoadExtAction(ISD::ZEXTLOAD, (MVT::SimpleValueType)VT, Expand);
613     setLoadExtAction(ISD::EXTLOAD, (MVT::SimpleValueType)VT, Expand);
614   }
615
616   // FIXME: In order to prevent SSE instructions being expanded to MMX ones
617   // with -msoft-float, disable use of MMX as well.
618   if (!UseSoftFloat && !DisableMMX && Subtarget->hasMMX()) {
619     addRegisterClass(MVT::v8i8,  X86::VR64RegisterClass);
620     addRegisterClass(MVT::v4i16, X86::VR64RegisterClass);
621     addRegisterClass(MVT::v2i32, X86::VR64RegisterClass);
622     addRegisterClass(MVT::v2f32, X86::VR64RegisterClass);
623     addRegisterClass(MVT::v1i64, X86::VR64RegisterClass);
624
625     setOperationAction(ISD::ADD,                MVT::v8i8,  Legal);
626     setOperationAction(ISD::ADD,                MVT::v4i16, Legal);
627     setOperationAction(ISD::ADD,                MVT::v2i32, Legal);
628     setOperationAction(ISD::ADD,                MVT::v1i64, Legal);
629
630     setOperationAction(ISD::SUB,                MVT::v8i8,  Legal);
631     setOperationAction(ISD::SUB,                MVT::v4i16, Legal);
632     setOperationAction(ISD::SUB,                MVT::v2i32, Legal);
633     setOperationAction(ISD::SUB,                MVT::v1i64, Legal);
634
635     setOperationAction(ISD::MULHS,              MVT::v4i16, Legal);
636     setOperationAction(ISD::MUL,                MVT::v4i16, Legal);
637
638     setOperationAction(ISD::AND,                MVT::v8i8,  Promote);
639     AddPromotedToType (ISD::AND,                MVT::v8i8,  MVT::v1i64);
640     setOperationAction(ISD::AND,                MVT::v4i16, Promote);
641     AddPromotedToType (ISD::AND,                MVT::v4i16, MVT::v1i64);
642     setOperationAction(ISD::AND,                MVT::v2i32, Promote);
643     AddPromotedToType (ISD::AND,                MVT::v2i32, MVT::v1i64);
644     setOperationAction(ISD::AND,                MVT::v1i64, Legal);
645
646     setOperationAction(ISD::OR,                 MVT::v8i8,  Promote);
647     AddPromotedToType (ISD::OR,                 MVT::v8i8,  MVT::v1i64);
648     setOperationAction(ISD::OR,                 MVT::v4i16, Promote);
649     AddPromotedToType (ISD::OR,                 MVT::v4i16, MVT::v1i64);
650     setOperationAction(ISD::OR,                 MVT::v2i32, Promote);
651     AddPromotedToType (ISD::OR,                 MVT::v2i32, MVT::v1i64);
652     setOperationAction(ISD::OR,                 MVT::v1i64, Legal);
653
654     setOperationAction(ISD::XOR,                MVT::v8i8,  Promote);
655     AddPromotedToType (ISD::XOR,                MVT::v8i8,  MVT::v1i64);
656     setOperationAction(ISD::XOR,                MVT::v4i16, Promote);
657     AddPromotedToType (ISD::XOR,                MVT::v4i16, MVT::v1i64);
658     setOperationAction(ISD::XOR,                MVT::v2i32, Promote);
659     AddPromotedToType (ISD::XOR,                MVT::v2i32, MVT::v1i64);
660     setOperationAction(ISD::XOR,                MVT::v1i64, Legal);
661
662     setOperationAction(ISD::LOAD,               MVT::v8i8,  Promote);
663     AddPromotedToType (ISD::LOAD,               MVT::v8i8,  MVT::v1i64);
664     setOperationAction(ISD::LOAD,               MVT::v4i16, Promote);
665     AddPromotedToType (ISD::LOAD,               MVT::v4i16, MVT::v1i64);
666     setOperationAction(ISD::LOAD,               MVT::v2i32, Promote);
667     AddPromotedToType (ISD::LOAD,               MVT::v2i32, MVT::v1i64);
668     setOperationAction(ISD::LOAD,               MVT::v2f32, Promote);
669     AddPromotedToType (ISD::LOAD,               MVT::v2f32, MVT::v1i64);
670     setOperationAction(ISD::LOAD,               MVT::v1i64, Legal);
671
672     setOperationAction(ISD::BUILD_VECTOR,       MVT::v8i8,  Custom);
673     setOperationAction(ISD::BUILD_VECTOR,       MVT::v4i16, Custom);
674     setOperationAction(ISD::BUILD_VECTOR,       MVT::v2i32, Custom);
675     setOperationAction(ISD::BUILD_VECTOR,       MVT::v2f32, Custom);
676     setOperationAction(ISD::BUILD_VECTOR,       MVT::v1i64, Custom);
677
678     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v8i8,  Custom);
679     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v4i16, Custom);
680     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v2i32, Custom);
681     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v1i64, Custom);
682
683     setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v2f32, Custom);
684     setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v8i8,  Custom);
685     setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v4i16, Custom);
686     setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v1i64, Custom);
687
688     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4i16, Custom);
689
690     setOperationAction(ISD::SELECT,             MVT::v8i8, Promote);
691     setOperationAction(ISD::SELECT,             MVT::v4i16, Promote);
692     setOperationAction(ISD::SELECT,             MVT::v2i32, Promote);
693     setOperationAction(ISD::SELECT,             MVT::v1i64, Custom);
694     setOperationAction(ISD::VSETCC,             MVT::v8i8, Custom);
695     setOperationAction(ISD::VSETCC,             MVT::v4i16, Custom);
696     setOperationAction(ISD::VSETCC,             MVT::v2i32, Custom);
697   }
698
699   if (!UseSoftFloat && Subtarget->hasSSE1()) {
700     addRegisterClass(MVT::v4f32, X86::VR128RegisterClass);
701
702     setOperationAction(ISD::FADD,               MVT::v4f32, Legal);
703     setOperationAction(ISD::FSUB,               MVT::v4f32, Legal);
704     setOperationAction(ISD::FMUL,               MVT::v4f32, Legal);
705     setOperationAction(ISD::FDIV,               MVT::v4f32, Legal);
706     setOperationAction(ISD::FSQRT,              MVT::v4f32, Legal);
707     setOperationAction(ISD::FNEG,               MVT::v4f32, Custom);
708     setOperationAction(ISD::LOAD,               MVT::v4f32, Legal);
709     setOperationAction(ISD::BUILD_VECTOR,       MVT::v4f32, Custom);
710     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v4f32, Custom);
711     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
712     setOperationAction(ISD::SELECT,             MVT::v4f32, Custom);
713     setOperationAction(ISD::VSETCC,             MVT::v4f32, Custom);
714   }
715
716   if (!UseSoftFloat && Subtarget->hasSSE2()) {
717     addRegisterClass(MVT::v2f64, X86::VR128RegisterClass);
718
719     // FIXME: Unfortunately -soft-float and -no-implicit-float means XMM
720     // registers cannot be used even for integer operations.
721     addRegisterClass(MVT::v16i8, X86::VR128RegisterClass);
722     addRegisterClass(MVT::v8i16, X86::VR128RegisterClass);
723     addRegisterClass(MVT::v4i32, X86::VR128RegisterClass);
724     addRegisterClass(MVT::v2i64, X86::VR128RegisterClass);
725
726     setOperationAction(ISD::ADD,                MVT::v16i8, Legal);
727     setOperationAction(ISD::ADD,                MVT::v8i16, Legal);
728     setOperationAction(ISD::ADD,                MVT::v4i32, Legal);
729     setOperationAction(ISD::ADD,                MVT::v2i64, Legal);
730     setOperationAction(ISD::MUL,                MVT::v2i64, Custom);
731     setOperationAction(ISD::SUB,                MVT::v16i8, Legal);
732     setOperationAction(ISD::SUB,                MVT::v8i16, Legal);
733     setOperationAction(ISD::SUB,                MVT::v4i32, Legal);
734     setOperationAction(ISD::SUB,                MVT::v2i64, Legal);
735     setOperationAction(ISD::MUL,                MVT::v8i16, Legal);
736     setOperationAction(ISD::FADD,               MVT::v2f64, Legal);
737     setOperationAction(ISD::FSUB,               MVT::v2f64, Legal);
738     setOperationAction(ISD::FMUL,               MVT::v2f64, Legal);
739     setOperationAction(ISD::FDIV,               MVT::v2f64, Legal);
740     setOperationAction(ISD::FSQRT,              MVT::v2f64, Legal);
741     setOperationAction(ISD::FNEG,               MVT::v2f64, Custom);
742
743     setOperationAction(ISD::VSETCC,             MVT::v2f64, Custom);
744     setOperationAction(ISD::VSETCC,             MVT::v16i8, Custom);
745     setOperationAction(ISD::VSETCC,             MVT::v8i16, Custom);
746     setOperationAction(ISD::VSETCC,             MVT::v4i32, Custom);
747
748     setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v16i8, Custom);
749     setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v8i16, Custom);
750     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v8i16, Custom);
751     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4i32, Custom);
752     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4f32, Custom);
753
754     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v2f64, Custom);
755     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v2i64, Custom);
756     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v16i8, Custom);
757     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v8i16, Custom);
758     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v4i32, Custom);
759
760     // Custom lower build_vector, vector_shuffle, and extract_vector_elt.
761     for (unsigned i = (unsigned)MVT::v16i8; i != (unsigned)MVT::v2i64; ++i) {
762       EVT VT = (MVT::SimpleValueType)i;
763       // Do not attempt to custom lower non-power-of-2 vectors
764       if (!isPowerOf2_32(VT.getVectorNumElements()))
765         continue;
766       // Do not attempt to custom lower non-128-bit vectors
767       if (!VT.is128BitVector())
768         continue;
769       setOperationAction(ISD::BUILD_VECTOR,
770                          VT.getSimpleVT().SimpleTy, Custom);
771       setOperationAction(ISD::VECTOR_SHUFFLE,
772                          VT.getSimpleVT().SimpleTy, Custom);
773       setOperationAction(ISD::EXTRACT_VECTOR_ELT,
774                          VT.getSimpleVT().SimpleTy, Custom);
775     }
776
777     setOperationAction(ISD::BUILD_VECTOR,       MVT::v2f64, Custom);
778     setOperationAction(ISD::BUILD_VECTOR,       MVT::v2i64, Custom);
779     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v2f64, Custom);
780     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v2i64, Custom);
781     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2f64, Custom);
782     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Custom);
783
784     if (Subtarget->is64Bit()) {
785       setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2i64, Custom);
786       setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
787     }
788
789     // Promote v16i8, v8i16, v4i32 load, select, and, or, xor to v2i64.
790     for (unsigned i = (unsigned)MVT::v16i8; i != (unsigned)MVT::v2i64; i++) {
791       MVT::SimpleValueType SVT = (MVT::SimpleValueType)i;
792       EVT VT = SVT;
793
794       // Do not attempt to promote non-128-bit vectors
795       if (!VT.is128BitVector()) {
796         continue;
797       }
798       setOperationAction(ISD::AND,    SVT, Promote);
799       AddPromotedToType (ISD::AND,    SVT, MVT::v2i64);
800       setOperationAction(ISD::OR,     SVT, Promote);
801       AddPromotedToType (ISD::OR,     SVT, MVT::v2i64);
802       setOperationAction(ISD::XOR,    SVT, Promote);
803       AddPromotedToType (ISD::XOR,    SVT, MVT::v2i64);
804       setOperationAction(ISD::LOAD,   SVT, Promote);
805       AddPromotedToType (ISD::LOAD,   SVT, MVT::v2i64);
806       setOperationAction(ISD::SELECT, SVT, Promote);
807       AddPromotedToType (ISD::SELECT, SVT, MVT::v2i64);
808     }
809
810     setTruncStoreAction(MVT::f64, MVT::f32, Expand);
811
812     // Custom lower v2i64 and v2f64 selects.
813     setOperationAction(ISD::LOAD,               MVT::v2f64, Legal);
814     setOperationAction(ISD::LOAD,               MVT::v2i64, Legal);
815     setOperationAction(ISD::SELECT,             MVT::v2f64, Custom);
816     setOperationAction(ISD::SELECT,             MVT::v2i64, Custom);
817
818     setOperationAction(ISD::FP_TO_SINT,         MVT::v4i32, Legal);
819     setOperationAction(ISD::SINT_TO_FP,         MVT::v4i32, Legal);
820     if (!DisableMMX && Subtarget->hasMMX()) {
821       setOperationAction(ISD::FP_TO_SINT,         MVT::v2i32, Custom);
822       setOperationAction(ISD::SINT_TO_FP,         MVT::v2i32, Custom);
823     }
824   }
825
826   if (Subtarget->hasSSE41()) {
827     // FIXME: Do we need to handle scalar-to-vector here?
828     setOperationAction(ISD::MUL,                MVT::v4i32, Legal);
829
830     // i8 and i16 vectors are custom , because the source register and source
831     // source memory operand types are not the same width.  f32 vectors are
832     // custom since the immediate controlling the insert encodes additional
833     // information.
834     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v16i8, Custom);
835     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v8i16, Custom);
836     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4i32, Custom);
837     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4f32, Custom);
838
839     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i8, Custom);
840     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i16, Custom);
841     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i32, Custom);
842     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
843
844     if (Subtarget->is64Bit()) {
845       setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2i64, Legal);
846       setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Legal);
847     }
848   }
849
850   if (Subtarget->hasSSE42()) {
851     setOperationAction(ISD::VSETCC,             MVT::v2i64, Custom);
852   }
853
854   if (!UseSoftFloat && Subtarget->hasAVX()) {
855     addRegisterClass(MVT::v8f32, X86::VR256RegisterClass);
856     addRegisterClass(MVT::v4f64, X86::VR256RegisterClass);
857     addRegisterClass(MVT::v8i32, X86::VR256RegisterClass);
858     addRegisterClass(MVT::v4i64, X86::VR256RegisterClass);
859
860     setOperationAction(ISD::LOAD,               MVT::v8f32, Legal);
861     setOperationAction(ISD::LOAD,               MVT::v8i32, Legal);
862     setOperationAction(ISD::LOAD,               MVT::v4f64, Legal);
863     setOperationAction(ISD::LOAD,               MVT::v4i64, Legal);
864     setOperationAction(ISD::FADD,               MVT::v8f32, Legal);
865     setOperationAction(ISD::FSUB,               MVT::v8f32, Legal);
866     setOperationAction(ISD::FMUL,               MVT::v8f32, Legal);
867     setOperationAction(ISD::FDIV,               MVT::v8f32, Legal);
868     setOperationAction(ISD::FSQRT,              MVT::v8f32, Legal);
869     setOperationAction(ISD::FNEG,               MVT::v8f32, Custom);
870     //setOperationAction(ISD::BUILD_VECTOR,       MVT::v8f32, Custom);
871     //setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v8f32, Custom);
872     //setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8f32, Custom);
873     //setOperationAction(ISD::SELECT,             MVT::v8f32, Custom);
874     //setOperationAction(ISD::VSETCC,             MVT::v8f32, Custom);
875
876     // Operations to consider commented out -v16i16 v32i8
877     //setOperationAction(ISD::ADD,                MVT::v16i16, Legal);
878     setOperationAction(ISD::ADD,                MVT::v8i32, Custom);
879     setOperationAction(ISD::ADD,                MVT::v4i64, Custom);
880     //setOperationAction(ISD::SUB,                MVT::v32i8, Legal);
881     //setOperationAction(ISD::SUB,                MVT::v16i16, Legal);
882     setOperationAction(ISD::SUB,                MVT::v8i32, Custom);
883     setOperationAction(ISD::SUB,                MVT::v4i64, Custom);
884     //setOperationAction(ISD::MUL,                MVT::v16i16, Legal);
885     setOperationAction(ISD::FADD,               MVT::v4f64, Legal);
886     setOperationAction(ISD::FSUB,               MVT::v4f64, Legal);
887     setOperationAction(ISD::FMUL,               MVT::v4f64, Legal);
888     setOperationAction(ISD::FDIV,               MVT::v4f64, Legal);
889     setOperationAction(ISD::FSQRT,              MVT::v4f64, Legal);
890     setOperationAction(ISD::FNEG,               MVT::v4f64, Custom);
891
892     setOperationAction(ISD::VSETCC,             MVT::v4f64, Custom);
893     // setOperationAction(ISD::VSETCC,             MVT::v32i8, Custom);
894     // setOperationAction(ISD::VSETCC,             MVT::v16i16, Custom);
895     setOperationAction(ISD::VSETCC,             MVT::v8i32, Custom);
896
897     // setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v32i8, Custom);
898     // setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v16i16, Custom);
899     // setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v16i16, Custom);
900     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v8i32, Custom);
901     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v8f32, Custom);
902
903     setOperationAction(ISD::BUILD_VECTOR,       MVT::v4f64, Custom);
904     setOperationAction(ISD::BUILD_VECTOR,       MVT::v4i64, Custom);
905     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v4f64, Custom);
906     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v4i64, Custom);
907     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4f64, Custom);
908     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f64, Custom);
909
910 #if 0
911     // Not sure we want to do this since there are no 256-bit integer
912     // operations in AVX
913
914     // Custom lower build_vector, vector_shuffle, and extract_vector_elt.
915     // This includes 256-bit vectors
916     for (unsigned i = (unsigned)MVT::v16i8; i != (unsigned)MVT::v4i64; ++i) {
917       EVT VT = (MVT::SimpleValueType)i;
918
919       // Do not attempt to custom lower non-power-of-2 vectors
920       if (!isPowerOf2_32(VT.getVectorNumElements()))
921         continue;
922
923       setOperationAction(ISD::BUILD_VECTOR,       VT, Custom);
924       setOperationAction(ISD::VECTOR_SHUFFLE,     VT, Custom);
925       setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
926     }
927
928     if (Subtarget->is64Bit()) {
929       setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4i64, Custom);
930       setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i64, Custom);
931     }
932 #endif
933
934 #if 0
935     // Not sure we want to do this since there are no 256-bit integer
936     // operations in AVX
937
938     // Promote v32i8, v16i16, v8i32 load, select, and, or, xor to v4i64.
939     // Including 256-bit vectors
940     for (unsigned i = (unsigned)MVT::v16i8; i != (unsigned)MVT::v4i64; i++) {
941       EVT VT = (MVT::SimpleValueType)i;
942
943       if (!VT.is256BitVector()) {
944         continue;
945       }
946       setOperationAction(ISD::AND,    VT, Promote);
947       AddPromotedToType (ISD::AND,    VT, MVT::v4i64);
948       setOperationAction(ISD::OR,     VT, Promote);
949       AddPromotedToType (ISD::OR,     VT, MVT::v4i64);
950       setOperationAction(ISD::XOR,    VT, Promote);
951       AddPromotedToType (ISD::XOR,    VT, MVT::v4i64);
952       setOperationAction(ISD::LOAD,   VT, Promote);
953       AddPromotedToType (ISD::LOAD,   VT, MVT::v4i64);
954       setOperationAction(ISD::SELECT, VT, Promote);
955       AddPromotedToType (ISD::SELECT, VT, MVT::v4i64);
956     }
957
958     setTruncStoreAction(MVT::f64, MVT::f32, Expand);
959 #endif
960   }
961
962   // We want to custom lower some of our intrinsics.
963   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
964
965   // Add/Sub/Mul with overflow operations are custom lowered.
966   setOperationAction(ISD::SADDO, MVT::i32, Custom);
967   setOperationAction(ISD::SADDO, MVT::i64, Custom);
968   setOperationAction(ISD::UADDO, MVT::i32, Custom);
969   setOperationAction(ISD::UADDO, MVT::i64, Custom);
970   setOperationAction(ISD::SSUBO, MVT::i32, Custom);
971   setOperationAction(ISD::SSUBO, MVT::i64, Custom);
972   setOperationAction(ISD::USUBO, MVT::i32, Custom);
973   setOperationAction(ISD::USUBO, MVT::i64, Custom);
974   setOperationAction(ISD::SMULO, MVT::i32, Custom);
975   setOperationAction(ISD::SMULO, MVT::i64, Custom);
976
977   if (!Subtarget->is64Bit()) {
978     // These libcalls are not available in 32-bit.
979     setLibcallName(RTLIB::SHL_I128, 0);
980     setLibcallName(RTLIB::SRL_I128, 0);
981     setLibcallName(RTLIB::SRA_I128, 0);
982   }
983
984   // We have target-specific dag combine patterns for the following nodes:
985   setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
986   setTargetDAGCombine(ISD::BUILD_VECTOR);
987   setTargetDAGCombine(ISD::SELECT);
988   setTargetDAGCombine(ISD::SHL);
989   setTargetDAGCombine(ISD::SRA);
990   setTargetDAGCombine(ISD::SRL);
991   setTargetDAGCombine(ISD::OR);
992   setTargetDAGCombine(ISD::STORE);
993   setTargetDAGCombine(ISD::MEMBARRIER);
994   setTargetDAGCombine(ISD::ZERO_EXTEND);
995   if (Subtarget->is64Bit())
996     setTargetDAGCombine(ISD::MUL);
997
998   computeRegisterProperties();
999
1000   // Divide and reminder operations have no vector equivalent and can
1001   // trap. Do a custom widening for these operations in which we never
1002   // generate more divides/remainder than the original vector width.
1003   for (unsigned VT = (unsigned)MVT::FIRST_VECTOR_VALUETYPE;
1004        VT <= (unsigned)MVT::LAST_VECTOR_VALUETYPE; ++VT) {
1005     if (!isTypeLegal((MVT::SimpleValueType)VT)) {
1006       setOperationAction(ISD::SDIV, (MVT::SimpleValueType) VT, Custom);
1007       setOperationAction(ISD::UDIV, (MVT::SimpleValueType) VT, Custom);
1008       setOperationAction(ISD::SREM, (MVT::SimpleValueType) VT, Custom);
1009       setOperationAction(ISD::UREM, (MVT::SimpleValueType) VT, Custom);
1010     }
1011   }
1012
1013   // FIXME: These should be based on subtarget info. Plus, the values should
1014   // be smaller when we are in optimizing for size mode.
1015   maxStoresPerMemset = 16; // For @llvm.memset -> sequence of stores
1016   maxStoresPerMemcpy = 16; // For @llvm.memcpy -> sequence of stores
1017   maxStoresPerMemmove = 3; // For @llvm.memmove -> sequence of stores
1018   setPrefLoopAlignment(16);
1019   benefitFromCodePlacementOpt = true;
1020 }
1021
1022
1023 MVT::SimpleValueType X86TargetLowering::getSetCCResultType(EVT VT) const {
1024   return MVT::i8;
1025 }
1026
1027
1028 /// getMaxByValAlign - Helper for getByValTypeAlignment to determine
1029 /// the desired ByVal argument alignment.
1030 static void getMaxByValAlign(const Type *Ty, unsigned &MaxAlign) {
1031   if (MaxAlign == 16)
1032     return;
1033   if (const VectorType *VTy = dyn_cast<VectorType>(Ty)) {
1034     if (VTy->getBitWidth() == 128)
1035       MaxAlign = 16;
1036   } else if (const ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
1037     unsigned EltAlign = 0;
1038     getMaxByValAlign(ATy->getElementType(), EltAlign);
1039     if (EltAlign > MaxAlign)
1040       MaxAlign = EltAlign;
1041   } else if (const StructType *STy = dyn_cast<StructType>(Ty)) {
1042     for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
1043       unsigned EltAlign = 0;
1044       getMaxByValAlign(STy->getElementType(i), EltAlign);
1045       if (EltAlign > MaxAlign)
1046         MaxAlign = EltAlign;
1047       if (MaxAlign == 16)
1048         break;
1049     }
1050   }
1051   return;
1052 }
1053
1054 /// getByValTypeAlignment - Return the desired alignment for ByVal aggregate
1055 /// function arguments in the caller parameter area. For X86, aggregates
1056 /// that contain SSE vectors are placed at 16-byte boundaries while the rest
1057 /// are at 4-byte boundaries.
1058 unsigned X86TargetLowering::getByValTypeAlignment(const Type *Ty) const {
1059   if (Subtarget->is64Bit()) {
1060     // Max of 8 and alignment of type.
1061     unsigned TyAlign = TD->getABITypeAlignment(Ty);
1062     if (TyAlign > 8)
1063       return TyAlign;
1064     return 8;
1065   }
1066
1067   unsigned Align = 4;
1068   if (Subtarget->hasSSE1())
1069     getMaxByValAlign(Ty, Align);
1070   return Align;
1071 }
1072
1073 /// getOptimalMemOpType - Returns the target specific optimal type for load
1074 /// and store operations as a result of memset, memcpy, and memmove
1075 /// lowering. It returns MVT::iAny if SelectionDAG should be responsible for
1076 /// determining it.
1077 EVT
1078 X86TargetLowering::getOptimalMemOpType(uint64_t Size, unsigned Align,
1079                                        bool isSrcConst, bool isSrcStr,
1080                                        SelectionDAG &DAG) const {
1081   // FIXME: This turns off use of xmm stores for memset/memcpy on targets like
1082   // linux.  This is because the stack realignment code can't handle certain
1083   // cases like PR2962.  This should be removed when PR2962 is fixed.
1084   const Function *F = DAG.getMachineFunction().getFunction();
1085   bool NoImplicitFloatOps = F->hasFnAttr(Attribute::NoImplicitFloat);
1086   if (!NoImplicitFloatOps && Subtarget->getStackAlignment() >= 16) {
1087     if ((isSrcConst || isSrcStr) && Subtarget->hasSSE2() && Size >= 16)
1088       return MVT::v4i32;
1089     if ((isSrcConst || isSrcStr) && Subtarget->hasSSE1() && Size >= 16)
1090       return MVT::v4f32;
1091   }
1092   if (Subtarget->is64Bit() && Size >= 8)
1093     return MVT::i64;
1094   return MVT::i32;
1095 }
1096
1097 /// getJumpTableEncoding - Return the entry encoding for a jump table in the
1098 /// current function.  The returned value is a member of the
1099 /// MachineJumpTableInfo::JTEntryKind enum.
1100 unsigned X86TargetLowering::getJumpTableEncoding() const {
1101   // In GOT pic mode, each entry in the jump table is emitted as a @GOTOFF
1102   // symbol.
1103   if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1104       Subtarget->isPICStyleGOT())
1105     return MachineJumpTableInfo::EK_Custom32;
1106   
1107   // Otherwise, use the normal jump table encoding heuristics.
1108   return TargetLowering::getJumpTableEncoding();
1109 }
1110
1111 /// getPICBaseSymbol - Return the X86-32 PIC base.
1112 MCSymbol *
1113 X86TargetLowering::getPICBaseSymbol(const MachineFunction *MF,
1114                                     MCContext &Ctx) const {
1115   const MCAsmInfo &MAI = *getTargetMachine().getMCAsmInfo();
1116   return Ctx.GetOrCreateSymbol(Twine(MAI.getPrivateGlobalPrefix())+
1117                                Twine(MF->getFunctionNumber())+"$pb");
1118 }
1119
1120
1121 const MCExpr *
1122 X86TargetLowering::LowerCustomJumpTableEntry(const MachineJumpTableInfo *MJTI,
1123                                              const MachineBasicBlock *MBB,
1124                                              unsigned uid,MCContext &Ctx) const{
1125   assert(getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1126          Subtarget->isPICStyleGOT());
1127   // In 32-bit ELF systems, our jump table entries are formed with @GOTOFF
1128   // entries.
1129
1130   // FIXME: @GOTOFF should be a property of MCSymbolRefExpr not in the MCSymbol.
1131   std::string Name = MBB->getSymbol(Ctx)->getName() + "@GOTOFF";
1132   return MCSymbolRefExpr::Create(Ctx.GetOrCreateSymbol(StringRef(Name)), Ctx);
1133 }
1134
1135 /// getPICJumpTableRelocaBase - Returns relocation base for the given PIC
1136 /// jumptable.
1137 SDValue X86TargetLowering::getPICJumpTableRelocBase(SDValue Table,
1138                                                     SelectionDAG &DAG) const {
1139   if (!Subtarget->is64Bit())
1140     // This doesn't have DebugLoc associated with it, but is not really the
1141     // same as a Register.
1142     return DAG.getNode(X86ISD::GlobalBaseReg, DebugLoc::getUnknownLoc(),
1143                        getPointerTy());
1144   return Table;
1145 }
1146
1147 /// getPICJumpTableRelocBaseExpr - This returns the relocation base for the
1148 /// given PIC jumptable, the same as getPICJumpTableRelocBase, but as an
1149 /// MCExpr.
1150 const MCExpr *X86TargetLowering::
1151 getPICJumpTableRelocBaseExpr(const MachineFunction *MF, unsigned JTI,
1152                              MCContext &Ctx) const {
1153   // X86-64 uses RIP relative addressing based on the jump table label.
1154   if (Subtarget->isPICStyleRIPRel())
1155     return TargetLowering::getPICJumpTableRelocBaseExpr(MF, JTI, Ctx);
1156
1157   // Otherwise, the reference is relative to the PIC base.
1158   return MCSymbolRefExpr::Create(getPICBaseSymbol(MF, Ctx), Ctx);
1159 }
1160
1161 /// getFunctionAlignment - Return the Log2 alignment of this function.
1162 unsigned X86TargetLowering::getFunctionAlignment(const Function *F) const {
1163   return F->hasFnAttr(Attribute::OptimizeForSize) ? 0 : 4;
1164 }
1165
1166 //===----------------------------------------------------------------------===//
1167 //               Return Value Calling Convention Implementation
1168 //===----------------------------------------------------------------------===//
1169
1170 #include "X86GenCallingConv.inc"
1171
1172 bool 
1173 X86TargetLowering::CanLowerReturn(CallingConv::ID CallConv, bool isVarArg,
1174                         const SmallVectorImpl<EVT> &OutTys,
1175                         const SmallVectorImpl<ISD::ArgFlagsTy> &ArgsFlags,
1176                         SelectionDAG &DAG) {
1177   SmallVector<CCValAssign, 16> RVLocs;
1178   CCState CCInfo(CallConv, isVarArg, getTargetMachine(),
1179                  RVLocs, *DAG.getContext());
1180   return CCInfo.CheckReturn(OutTys, ArgsFlags, RetCC_X86);
1181 }
1182
1183 SDValue
1184 X86TargetLowering::LowerReturn(SDValue Chain,
1185                                CallingConv::ID CallConv, bool isVarArg,
1186                                const SmallVectorImpl<ISD::OutputArg> &Outs,
1187                                DebugLoc dl, SelectionDAG &DAG) {
1188
1189   SmallVector<CCValAssign, 16> RVLocs;
1190   CCState CCInfo(CallConv, isVarArg, getTargetMachine(),
1191                  RVLocs, *DAG.getContext());
1192   CCInfo.AnalyzeReturn(Outs, RetCC_X86);
1193
1194   // If this is the first return lowered for this function, add the regs to the
1195   // liveout set for the function.
1196   if (DAG.getMachineFunction().getRegInfo().liveout_empty()) {
1197     for (unsigned i = 0; i != RVLocs.size(); ++i)
1198       if (RVLocs[i].isRegLoc())
1199         DAG.getMachineFunction().getRegInfo().addLiveOut(RVLocs[i].getLocReg());
1200   }
1201
1202   SDValue Flag;
1203
1204   SmallVector<SDValue, 6> RetOps;
1205   RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
1206   // Operand #1 = Bytes To Pop
1207   RetOps.push_back(DAG.getTargetConstant(getBytesToPopOnReturn(), MVT::i16));
1208
1209   // Copy the result values into the output registers.
1210   for (unsigned i = 0; i != RVLocs.size(); ++i) {
1211     CCValAssign &VA = RVLocs[i];
1212     assert(VA.isRegLoc() && "Can only return in registers!");
1213     SDValue ValToCopy = Outs[i].Val;
1214
1215     // Returns in ST0/ST1 are handled specially: these are pushed as operands to
1216     // the RET instruction and handled by the FP Stackifier.
1217     if (VA.getLocReg() == X86::ST0 ||
1218         VA.getLocReg() == X86::ST1) {
1219       // If this is a copy from an xmm register to ST(0), use an FPExtend to
1220       // change the value to the FP stack register class.
1221       if (isScalarFPTypeInSSEReg(VA.getValVT()))
1222         ValToCopy = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f80, ValToCopy);
1223       RetOps.push_back(ValToCopy);
1224       // Don't emit a copytoreg.
1225       continue;
1226     }
1227
1228     // 64-bit vector (MMX) values are returned in XMM0 / XMM1 except for v1i64
1229     // which is returned in RAX / RDX.
1230     if (Subtarget->is64Bit()) {
1231       EVT ValVT = ValToCopy.getValueType();
1232       if (ValVT.isVector() && ValVT.getSizeInBits() == 64) {
1233         ValToCopy = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::i64, ValToCopy);
1234         if (VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1)
1235           ValToCopy = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64, ValToCopy);
1236       }
1237     }
1238
1239     Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), ValToCopy, Flag);
1240     Flag = Chain.getValue(1);
1241   }
1242
1243   // The x86-64 ABI for returning structs by value requires that we copy
1244   // the sret argument into %rax for the return. We saved the argument into
1245   // a virtual register in the entry block, so now we copy the value out
1246   // and into %rax.
1247   if (Subtarget->is64Bit() &&
1248       DAG.getMachineFunction().getFunction()->hasStructRetAttr()) {
1249     MachineFunction &MF = DAG.getMachineFunction();
1250     X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1251     unsigned Reg = FuncInfo->getSRetReturnReg();
1252     if (!Reg) {
1253       Reg = MF.getRegInfo().createVirtualRegister(getRegClassFor(MVT::i64));
1254       FuncInfo->setSRetReturnReg(Reg);
1255     }
1256     SDValue Val = DAG.getCopyFromReg(Chain, dl, Reg, getPointerTy());
1257
1258     Chain = DAG.getCopyToReg(Chain, dl, X86::RAX, Val, Flag);
1259     Flag = Chain.getValue(1);
1260
1261     // RAX now acts like a return value.
1262     MF.getRegInfo().addLiveOut(X86::RAX);
1263   }
1264
1265   RetOps[0] = Chain;  // Update chain.
1266
1267   // Add the flag if we have it.
1268   if (Flag.getNode())
1269     RetOps.push_back(Flag);
1270
1271   return DAG.getNode(X86ISD::RET_FLAG, dl,
1272                      MVT::Other, &RetOps[0], RetOps.size());
1273 }
1274
1275 /// LowerCallResult - Lower the result values of a call into the
1276 /// appropriate copies out of appropriate physical registers.
1277 ///
1278 SDValue
1279 X86TargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
1280                                    CallingConv::ID CallConv, bool isVarArg,
1281                                    const SmallVectorImpl<ISD::InputArg> &Ins,
1282                                    DebugLoc dl, SelectionDAG &DAG,
1283                                    SmallVectorImpl<SDValue> &InVals) {
1284
1285   // Assign locations to each value returned by this call.
1286   SmallVector<CCValAssign, 16> RVLocs;
1287   bool Is64Bit = Subtarget->is64Bit();
1288   CCState CCInfo(CallConv, isVarArg, getTargetMachine(),
1289                  RVLocs, *DAG.getContext());
1290   CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
1291
1292   // Copy all of the result registers out of their specified physreg.
1293   for (unsigned i = 0; i != RVLocs.size(); ++i) {
1294     CCValAssign &VA = RVLocs[i];
1295     EVT CopyVT = VA.getValVT();
1296
1297     // If this is x86-64, and we disabled SSE, we can't return FP values
1298     if ((CopyVT == MVT::f32 || CopyVT == MVT::f64) &&
1299         ((Is64Bit || Ins[i].Flags.isInReg()) && !Subtarget->hasSSE1())) {
1300       llvm_report_error("SSE register return with SSE disabled");
1301     }
1302
1303     // If this is a call to a function that returns an fp value on the floating
1304     // point stack, but where we prefer to use the value in xmm registers, copy
1305     // it out as F80 and use a truncate to move it from fp stack reg to xmm reg.
1306     if ((VA.getLocReg() == X86::ST0 ||
1307          VA.getLocReg() == X86::ST1) &&
1308         isScalarFPTypeInSSEReg(VA.getValVT())) {
1309       CopyVT = MVT::f80;
1310     }
1311
1312     SDValue Val;
1313     if (Is64Bit && CopyVT.isVector() && CopyVT.getSizeInBits() == 64) {
1314       // For x86-64, MMX values are returned in XMM0 / XMM1 except for v1i64.
1315       if (VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) {
1316         Chain = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(),
1317                                    MVT::v2i64, InFlag).getValue(1);
1318         Val = Chain.getValue(0);
1319         Val = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i64,
1320                           Val, DAG.getConstant(0, MVT::i64));
1321       } else {
1322         Chain = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(),
1323                                    MVT::i64, InFlag).getValue(1);
1324         Val = Chain.getValue(0);
1325       }
1326       Val = DAG.getNode(ISD::BIT_CONVERT, dl, CopyVT, Val);
1327     } else {
1328       Chain = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(),
1329                                  CopyVT, InFlag).getValue(1);
1330       Val = Chain.getValue(0);
1331     }
1332     InFlag = Chain.getValue(2);
1333
1334     if (CopyVT != VA.getValVT()) {
1335       // Round the F80 the right size, which also moves to the appropriate xmm
1336       // register.
1337       Val = DAG.getNode(ISD::FP_ROUND, dl, VA.getValVT(), Val,
1338                         // This truncation won't change the value.
1339                         DAG.getIntPtrConstant(1));
1340     }
1341
1342     InVals.push_back(Val);
1343   }
1344
1345   return Chain;
1346 }
1347
1348
1349 //===----------------------------------------------------------------------===//
1350 //                C & StdCall & Fast Calling Convention implementation
1351 //===----------------------------------------------------------------------===//
1352 //  StdCall calling convention seems to be standard for many Windows' API
1353 //  routines and around. It differs from C calling convention just a little:
1354 //  callee should clean up the stack, not caller. Symbols should be also
1355 //  decorated in some fancy way :) It doesn't support any vector arguments.
1356 //  For info on fast calling convention see Fast Calling Convention (tail call)
1357 //  implementation LowerX86_32FastCCCallTo.
1358
1359 /// CallIsStructReturn - Determines whether a call uses struct return
1360 /// semantics.
1361 static bool CallIsStructReturn(const SmallVectorImpl<ISD::OutputArg> &Outs) {
1362   if (Outs.empty())
1363     return false;
1364
1365   return Outs[0].Flags.isSRet();
1366 }
1367
1368 /// ArgsAreStructReturn - Determines whether a function uses struct
1369 /// return semantics.
1370 static bool
1371 ArgsAreStructReturn(const SmallVectorImpl<ISD::InputArg> &Ins) {
1372   if (Ins.empty())
1373     return false;
1374
1375   return Ins[0].Flags.isSRet();
1376 }
1377
1378 /// IsCalleePop - Determines whether the callee is required to pop its
1379 /// own arguments. Callee pop is necessary to support tail calls.
1380 bool X86TargetLowering::IsCalleePop(bool IsVarArg, CallingConv::ID CallingConv){
1381   if (IsVarArg)
1382     return false;
1383
1384   switch (CallingConv) {
1385   default:
1386     return false;
1387   case CallingConv::X86_StdCall:
1388     return !Subtarget->is64Bit();
1389   case CallingConv::X86_FastCall:
1390     return !Subtarget->is64Bit();
1391   case CallingConv::Fast:
1392     return PerformTailCallOpt;
1393   }
1394 }
1395
1396 /// CCAssignFnForNode - Selects the correct CCAssignFn for a the
1397 /// given CallingConvention value.
1398 CCAssignFn *X86TargetLowering::CCAssignFnForNode(CallingConv::ID CC) const {
1399   if (Subtarget->is64Bit()) {
1400     if (Subtarget->isTargetWin64())
1401       return CC_X86_Win64_C;
1402     else
1403       return CC_X86_64_C;
1404   }
1405
1406   if (CC == CallingConv::X86_FastCall)
1407     return CC_X86_32_FastCall;
1408   else if (CC == CallingConv::Fast)
1409     return CC_X86_32_FastCC;
1410   else
1411     return CC_X86_32_C;
1412 }
1413
1414 /// NameDecorationForCallConv - Selects the appropriate decoration to
1415 /// apply to a MachineFunction containing a given calling convention.
1416 NameDecorationStyle
1417 X86TargetLowering::NameDecorationForCallConv(CallingConv::ID CallConv) {
1418   if (CallConv == CallingConv::X86_FastCall)
1419     return FastCall;
1420   else if (CallConv == CallingConv::X86_StdCall)
1421     return StdCall;
1422   return None;
1423 }
1424
1425
1426 /// CreateCopyOfByValArgument - Make a copy of an aggregate at address specified
1427 /// by "Src" to address "Dst" with size and alignment information specified by
1428 /// the specific parameter attribute. The copy will be passed as a byval
1429 /// function parameter.
1430 static SDValue
1431 CreateCopyOfByValArgument(SDValue Src, SDValue Dst, SDValue Chain,
1432                           ISD::ArgFlagsTy Flags, SelectionDAG &DAG,
1433                           DebugLoc dl) {
1434   SDValue SizeNode     = DAG.getConstant(Flags.getByValSize(), MVT::i32);
1435   return DAG.getMemcpy(Chain, dl, Dst, Src, SizeNode, Flags.getByValAlign(),
1436                        /*AlwaysInline=*/true, NULL, 0, NULL, 0);
1437 }
1438
1439 SDValue
1440 X86TargetLowering::LowerMemArgument(SDValue Chain,
1441                                     CallingConv::ID CallConv,
1442                                     const SmallVectorImpl<ISD::InputArg> &Ins,
1443                                     DebugLoc dl, SelectionDAG &DAG,
1444                                     const CCValAssign &VA,
1445                                     MachineFrameInfo *MFI,
1446                                     unsigned i) {
1447
1448   // Create the nodes corresponding to a load from this parameter slot.
1449   ISD::ArgFlagsTy Flags = Ins[i].Flags;
1450   bool AlwaysUseMutable = X86::IsEligibleForTailCallOpt(CallConv);
1451   bool isImmutable = !AlwaysUseMutable && !Flags.isByVal();
1452   EVT ValVT;
1453
1454   // If value is passed by pointer we have address passed instead of the value
1455   // itself.
1456   if (VA.getLocInfo() == CCValAssign::Indirect)
1457     ValVT = VA.getLocVT();
1458   else
1459     ValVT = VA.getValVT();
1460
1461   // FIXME: For now, all byval parameter objects are marked mutable. This can be
1462   // changed with more analysis.
1463   // In case of tail call optimization mark all arguments mutable. Since they
1464   // could be overwritten by lowering of arguments in case of a tail call.
1465   int FI = MFI->CreateFixedObject(ValVT.getSizeInBits()/8,
1466                                   VA.getLocMemOffset(), isImmutable, false);
1467   SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
1468   if (Flags.isByVal())
1469     return FIN;
1470   return DAG.getLoad(ValVT, dl, Chain, FIN,
1471                      PseudoSourceValue::getFixedStack(FI), 0);
1472 }
1473
1474 SDValue
1475 X86TargetLowering::LowerFormalArguments(SDValue Chain,
1476                                         CallingConv::ID CallConv,
1477                                         bool isVarArg,
1478                                       const SmallVectorImpl<ISD::InputArg> &Ins,
1479                                         DebugLoc dl,
1480                                         SelectionDAG &DAG,
1481                                         SmallVectorImpl<SDValue> &InVals) {
1482
1483   MachineFunction &MF = DAG.getMachineFunction();
1484   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1485
1486   const Function* Fn = MF.getFunction();
1487   if (Fn->hasExternalLinkage() &&
1488       Subtarget->isTargetCygMing() &&
1489       Fn->getName() == "main")
1490     FuncInfo->setForceFramePointer(true);
1491
1492   // Decorate the function name.
1493   FuncInfo->setDecorationStyle(NameDecorationForCallConv(CallConv));
1494
1495   MachineFrameInfo *MFI = MF.getFrameInfo();
1496   bool Is64Bit = Subtarget->is64Bit();
1497   bool IsWin64 = Subtarget->isTargetWin64();
1498
1499   assert(!(isVarArg && CallConv == CallingConv::Fast) &&
1500          "Var args not supported with calling convention fastcc");
1501
1502   // Assign locations to all of the incoming arguments.
1503   SmallVector<CCValAssign, 16> ArgLocs;
1504   CCState CCInfo(CallConv, isVarArg, getTargetMachine(),
1505                  ArgLocs, *DAG.getContext());
1506   CCInfo.AnalyzeFormalArguments(Ins, CCAssignFnForNode(CallConv));
1507
1508   unsigned LastVal = ~0U;
1509   SDValue ArgValue;
1510   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
1511     CCValAssign &VA = ArgLocs[i];
1512     // TODO: If an arg is passed in two places (e.g. reg and stack), skip later
1513     // places.
1514     assert(VA.getValNo() != LastVal &&
1515            "Don't support value assigned to multiple locs yet");
1516     LastVal = VA.getValNo();
1517
1518     if (VA.isRegLoc()) {
1519       EVT RegVT = VA.getLocVT();
1520       TargetRegisterClass *RC = NULL;
1521       if (RegVT == MVT::i32)
1522         RC = X86::GR32RegisterClass;
1523       else if (Is64Bit && RegVT == MVT::i64)
1524         RC = X86::GR64RegisterClass;
1525       else if (RegVT == MVT::f32)
1526         RC = X86::FR32RegisterClass;
1527       else if (RegVT == MVT::f64)
1528         RC = X86::FR64RegisterClass;
1529       else if (RegVT.isVector() && RegVT.getSizeInBits() == 128)
1530         RC = X86::VR128RegisterClass;
1531       else if (RegVT.isVector() && RegVT.getSizeInBits() == 64)
1532         RC = X86::VR64RegisterClass;
1533       else
1534         llvm_unreachable("Unknown argument type!");
1535
1536       unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
1537       ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
1538
1539       // If this is an 8 or 16-bit value, it is really passed promoted to 32
1540       // bits.  Insert an assert[sz]ext to capture this, then truncate to the
1541       // right size.
1542       if (VA.getLocInfo() == CCValAssign::SExt)
1543         ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
1544                                DAG.getValueType(VA.getValVT()));
1545       else if (VA.getLocInfo() == CCValAssign::ZExt)
1546         ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
1547                                DAG.getValueType(VA.getValVT()));
1548       else if (VA.getLocInfo() == CCValAssign::BCvt)
1549         ArgValue = DAG.getNode(ISD::BIT_CONVERT, dl, VA.getValVT(), ArgValue);
1550
1551       if (VA.isExtInLoc()) {
1552         // Handle MMX values passed in XMM regs.
1553         if (RegVT.isVector()) {
1554           ArgValue = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i64,
1555                                  ArgValue, DAG.getConstant(0, MVT::i64));
1556           ArgValue = DAG.getNode(ISD::BIT_CONVERT, dl, VA.getValVT(), ArgValue);
1557         } else
1558           ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
1559       }
1560     } else {
1561       assert(VA.isMemLoc());
1562       ArgValue = LowerMemArgument(Chain, CallConv, Ins, dl, DAG, VA, MFI, i);
1563     }
1564
1565     // If value is passed via pointer - do a load.
1566     if (VA.getLocInfo() == CCValAssign::Indirect)
1567       ArgValue = DAG.getLoad(VA.getValVT(), dl, Chain, ArgValue, NULL, 0);
1568
1569     InVals.push_back(ArgValue);
1570   }
1571
1572   // The x86-64 ABI for returning structs by value requires that we copy
1573   // the sret argument into %rax for the return. Save the argument into
1574   // a virtual register so that we can access it from the return points.
1575   if (Is64Bit && MF.getFunction()->hasStructRetAttr()) {
1576     X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1577     unsigned Reg = FuncInfo->getSRetReturnReg();
1578     if (!Reg) {
1579       Reg = MF.getRegInfo().createVirtualRegister(getRegClassFor(MVT::i64));
1580       FuncInfo->setSRetReturnReg(Reg);
1581     }
1582     SDValue Copy = DAG.getCopyToReg(DAG.getEntryNode(), dl, Reg, InVals[0]);
1583     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Copy, Chain);
1584   }
1585
1586   unsigned StackSize = CCInfo.getNextStackOffset();
1587   // align stack specially for tail calls
1588   if (X86::IsEligibleForTailCallOpt(CallConv))
1589     StackSize = GetAlignedArgumentStackSize(StackSize, DAG);
1590
1591   // If the function takes variable number of arguments, make a frame index for
1592   // the start of the first vararg value... for expansion of llvm.va_start.
1593   if (isVarArg) {
1594     if (Is64Bit || CallConv != CallingConv::X86_FastCall) {
1595       VarArgsFrameIndex = MFI->CreateFixedObject(1, StackSize, true, false);
1596     }
1597     if (Is64Bit) {
1598       unsigned TotalNumIntRegs = 0, TotalNumXMMRegs = 0;
1599
1600       // FIXME: We should really autogenerate these arrays
1601       static const unsigned GPR64ArgRegsWin64[] = {
1602         X86::RCX, X86::RDX, X86::R8,  X86::R9
1603       };
1604       static const unsigned XMMArgRegsWin64[] = {
1605         X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3
1606       };
1607       static const unsigned GPR64ArgRegs64Bit[] = {
1608         X86::RDI, X86::RSI, X86::RDX, X86::RCX, X86::R8, X86::R9
1609       };
1610       static const unsigned XMMArgRegs64Bit[] = {
1611         X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
1612         X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
1613       };
1614       const unsigned *GPR64ArgRegs, *XMMArgRegs;
1615
1616       if (IsWin64) {
1617         TotalNumIntRegs = 4; TotalNumXMMRegs = 4;
1618         GPR64ArgRegs = GPR64ArgRegsWin64;
1619         XMMArgRegs = XMMArgRegsWin64;
1620       } else {
1621         TotalNumIntRegs = 6; TotalNumXMMRegs = 8;
1622         GPR64ArgRegs = GPR64ArgRegs64Bit;
1623         XMMArgRegs = XMMArgRegs64Bit;
1624       }
1625       unsigned NumIntRegs = CCInfo.getFirstUnallocated(GPR64ArgRegs,
1626                                                        TotalNumIntRegs);
1627       unsigned NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs,
1628                                                        TotalNumXMMRegs);
1629
1630       bool NoImplicitFloatOps = Fn->hasFnAttr(Attribute::NoImplicitFloat);
1631       assert(!(NumXMMRegs && !Subtarget->hasSSE1()) &&
1632              "SSE register cannot be used when SSE is disabled!");
1633       assert(!(NumXMMRegs && UseSoftFloat && NoImplicitFloatOps) &&
1634              "SSE register cannot be used when SSE is disabled!");
1635       if (UseSoftFloat || NoImplicitFloatOps || !Subtarget->hasSSE1())
1636         // Kernel mode asks for SSE to be disabled, so don't push them
1637         // on the stack.
1638         TotalNumXMMRegs = 0;
1639
1640       // For X86-64, if there are vararg parameters that are passed via
1641       // registers, then we must store them to their spots on the stack so they
1642       // may be loaded by deferencing the result of va_next.
1643       VarArgsGPOffset = NumIntRegs * 8;
1644       VarArgsFPOffset = TotalNumIntRegs * 8 + NumXMMRegs * 16;
1645       RegSaveFrameIndex = MFI->CreateStackObject(TotalNumIntRegs * 8 +
1646                                                  TotalNumXMMRegs * 16, 16,
1647                                                  false);
1648
1649       // Store the integer parameter registers.
1650       SmallVector<SDValue, 8> MemOps;
1651       SDValue RSFIN = DAG.getFrameIndex(RegSaveFrameIndex, getPointerTy());
1652       unsigned Offset = VarArgsGPOffset;
1653       for (; NumIntRegs != TotalNumIntRegs; ++NumIntRegs) {
1654         SDValue FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(), RSFIN,
1655                                   DAG.getIntPtrConstant(Offset));
1656         unsigned VReg = MF.addLiveIn(GPR64ArgRegs[NumIntRegs],
1657                                      X86::GR64RegisterClass);
1658         SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
1659         SDValue Store =
1660           DAG.getStore(Val.getValue(1), dl, Val, FIN,
1661                        PseudoSourceValue::getFixedStack(RegSaveFrameIndex),
1662                        Offset);
1663         MemOps.push_back(Store);
1664         Offset += 8;
1665       }
1666
1667       if (TotalNumXMMRegs != 0 && NumXMMRegs != TotalNumXMMRegs) {
1668         // Now store the XMM (fp + vector) parameter registers.
1669         SmallVector<SDValue, 11> SaveXMMOps;
1670         SaveXMMOps.push_back(Chain);
1671
1672         unsigned AL = MF.addLiveIn(X86::AL, X86::GR8RegisterClass);
1673         SDValue ALVal = DAG.getCopyFromReg(DAG.getEntryNode(), dl, AL, MVT::i8);
1674         SaveXMMOps.push_back(ALVal);
1675
1676         SaveXMMOps.push_back(DAG.getIntPtrConstant(RegSaveFrameIndex));
1677         SaveXMMOps.push_back(DAG.getIntPtrConstant(VarArgsFPOffset));
1678
1679         for (; NumXMMRegs != TotalNumXMMRegs; ++NumXMMRegs) {
1680           unsigned VReg = MF.addLiveIn(XMMArgRegs[NumXMMRegs],
1681                                        X86::VR128RegisterClass);
1682           SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::v4f32);
1683           SaveXMMOps.push_back(Val);
1684         }
1685         MemOps.push_back(DAG.getNode(X86ISD::VASTART_SAVE_XMM_REGS, dl,
1686                                      MVT::Other,
1687                                      &SaveXMMOps[0], SaveXMMOps.size()));
1688       }
1689
1690       if (!MemOps.empty())
1691         Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
1692                             &MemOps[0], MemOps.size());
1693     }
1694   }
1695
1696   // Some CCs need callee pop.
1697   if (IsCalleePop(isVarArg, CallConv)) {
1698     BytesToPopOnReturn  = StackSize; // Callee pops everything.
1699     BytesCallerReserves = 0;
1700   } else {
1701     BytesToPopOnReturn  = 0; // Callee pops nothing.
1702     // If this is an sret function, the return should pop the hidden pointer.
1703     if (!Is64Bit && CallConv != CallingConv::Fast && ArgsAreStructReturn(Ins))
1704       BytesToPopOnReturn = 4;
1705     BytesCallerReserves = StackSize;
1706   }
1707
1708   if (!Is64Bit) {
1709     RegSaveFrameIndex = 0xAAAAAAA;   // RegSaveFrameIndex is X86-64 only.
1710     if (CallConv == CallingConv::X86_FastCall)
1711       VarArgsFrameIndex = 0xAAAAAAA;   // fastcc functions can't have varargs.
1712   }
1713
1714   FuncInfo->setBytesToPopOnReturn(BytesToPopOnReturn);
1715
1716   return Chain;
1717 }
1718
1719 SDValue
1720 X86TargetLowering::LowerMemOpCallTo(SDValue Chain,
1721                                     SDValue StackPtr, SDValue Arg,
1722                                     DebugLoc dl, SelectionDAG &DAG,
1723                                     const CCValAssign &VA,
1724                                     ISD::ArgFlagsTy Flags) {
1725   const unsigned FirstStackArgOffset = (Subtarget->isTargetWin64() ? 32 : 0);
1726   unsigned LocMemOffset = FirstStackArgOffset + VA.getLocMemOffset();
1727   SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset);
1728   PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, PtrOff);
1729   if (Flags.isByVal()) {
1730     return CreateCopyOfByValArgument(Arg, PtrOff, Chain, Flags, DAG, dl);
1731   }
1732   return DAG.getStore(Chain, dl, Arg, PtrOff,
1733                       PseudoSourceValue::getStack(), LocMemOffset);
1734 }
1735
1736 /// EmitTailCallLoadRetAddr - Emit a load of return address if tail call
1737 /// optimization is performed and it is required.
1738 SDValue
1739 X86TargetLowering::EmitTailCallLoadRetAddr(SelectionDAG &DAG,
1740                                            SDValue &OutRetAddr, SDValue Chain,
1741                                            bool IsTailCall, bool Is64Bit,
1742                                            int FPDiff, DebugLoc dl) {
1743   if (!IsTailCall || FPDiff==0) return Chain;
1744
1745   // Adjust the Return address stack slot.
1746   EVT VT = getPointerTy();
1747   OutRetAddr = getReturnAddressFrameIndex(DAG);
1748
1749   // Load the "old" Return address.
1750   OutRetAddr = DAG.getLoad(VT, dl, Chain, OutRetAddr, NULL, 0);
1751   return SDValue(OutRetAddr.getNode(), 1);
1752 }
1753
1754 /// EmitTailCallStoreRetAddr - Emit a store of the return adress if tail call
1755 /// optimization is performed and it is required (FPDiff!=0).
1756 static SDValue
1757 EmitTailCallStoreRetAddr(SelectionDAG & DAG, MachineFunction &MF,
1758                          SDValue Chain, SDValue RetAddrFrIdx,
1759                          bool Is64Bit, int FPDiff, DebugLoc dl) {
1760   // Store the return address to the appropriate stack slot.
1761   if (!FPDiff) return Chain;
1762   // Calculate the new stack slot for the return address.
1763   int SlotSize = Is64Bit ? 8 : 4;
1764   int NewReturnAddrFI =
1765     MF.getFrameInfo()->CreateFixedObject(SlotSize, FPDiff-SlotSize, true,false);
1766   EVT VT = Is64Bit ? MVT::i64 : MVT::i32;
1767   SDValue NewRetAddrFrIdx = DAG.getFrameIndex(NewReturnAddrFI, VT);
1768   Chain = DAG.getStore(Chain, dl, RetAddrFrIdx, NewRetAddrFrIdx,
1769                        PseudoSourceValue::getFixedStack(NewReturnAddrFI), 0);
1770   return Chain;
1771 }
1772
1773 SDValue
1774 X86TargetLowering::LowerCall(SDValue Chain, SDValue Callee,
1775                              CallingConv::ID CallConv, bool isVarArg,
1776                              bool isTailCall,
1777                              const SmallVectorImpl<ISD::OutputArg> &Outs,
1778                              const SmallVectorImpl<ISD::InputArg> &Ins,
1779                              DebugLoc dl, SelectionDAG &DAG,
1780                              SmallVectorImpl<SDValue> &InVals) {
1781
1782   MachineFunction &MF = DAG.getMachineFunction();
1783   bool Is64Bit        = Subtarget->is64Bit();
1784   bool IsStructRet    = CallIsStructReturn(Outs);
1785
1786   assert((!isTailCall || X86::IsEligibleForTailCallOpt(CallConv)) &&
1787          "Call is not eligible for tail call optimization!");
1788   assert(!(isVarArg && CallConv == CallingConv::Fast) &&
1789          "Var args not supported with calling convention fastcc");
1790
1791   // Analyze operands of the call, assigning locations to each operand.
1792   SmallVector<CCValAssign, 16> ArgLocs;
1793   CCState CCInfo(CallConv, isVarArg, getTargetMachine(),
1794                  ArgLocs, *DAG.getContext());
1795   CCInfo.AnalyzeCallOperands(Outs, CCAssignFnForNode(CallConv));
1796
1797   // Get a count of how many bytes are to be pushed on the stack.
1798   unsigned NumBytes = CCInfo.getNextStackOffset();
1799   if (X86::IsEligibleForTailCallOpt(CallConv))
1800     NumBytes = GetAlignedArgumentStackSize(NumBytes, DAG);
1801
1802   int FPDiff = 0;
1803   if (isTailCall) {
1804     // Lower arguments at fp - stackoffset + fpdiff.
1805     unsigned NumBytesCallerPushed =
1806       MF.getInfo<X86MachineFunctionInfo>()->getBytesToPopOnReturn();
1807     FPDiff = NumBytesCallerPushed - NumBytes;
1808
1809     // Set the delta of movement of the returnaddr stackslot.
1810     // But only set if delta is greater than previous delta.
1811     if (FPDiff < (MF.getInfo<X86MachineFunctionInfo>()->getTCReturnAddrDelta()))
1812       MF.getInfo<X86MachineFunctionInfo>()->setTCReturnAddrDelta(FPDiff);
1813   }
1814
1815   Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes, true));
1816
1817   SDValue RetAddrFrIdx;
1818   // Load return adress for tail calls.
1819   Chain = EmitTailCallLoadRetAddr(DAG, RetAddrFrIdx, Chain, isTailCall, Is64Bit,
1820                                   FPDiff, dl);
1821
1822   SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
1823   SmallVector<SDValue, 8> MemOpChains;
1824   SDValue StackPtr;
1825
1826   // Walk the register/memloc assignments, inserting copies/loads.  In the case
1827   // of tail call optimization arguments are handle later.
1828   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
1829     CCValAssign &VA = ArgLocs[i];
1830     EVT RegVT = VA.getLocVT();
1831     SDValue Arg = Outs[i].Val;
1832     ISD::ArgFlagsTy Flags = Outs[i].Flags;
1833     bool isByVal = Flags.isByVal();
1834
1835     // Promote the value if needed.
1836     switch (VA.getLocInfo()) {
1837     default: llvm_unreachable("Unknown loc info!");
1838     case CCValAssign::Full: break;
1839     case CCValAssign::SExt:
1840       Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, RegVT, Arg);
1841       break;
1842     case CCValAssign::ZExt:
1843       Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, RegVT, Arg);
1844       break;
1845     case CCValAssign::AExt:
1846       if (RegVT.isVector() && RegVT.getSizeInBits() == 128) {
1847         // Special case: passing MMX values in XMM registers.
1848         Arg = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::i64, Arg);
1849         Arg = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64, Arg);
1850         Arg = getMOVL(DAG, dl, MVT::v2i64, DAG.getUNDEF(MVT::v2i64), Arg);
1851       } else
1852         Arg = DAG.getNode(ISD::ANY_EXTEND, dl, RegVT, Arg);
1853       break;
1854     case CCValAssign::BCvt:
1855       Arg = DAG.getNode(ISD::BIT_CONVERT, dl, RegVT, Arg);
1856       break;
1857     case CCValAssign::Indirect: {
1858       // Store the argument.
1859       SDValue SpillSlot = DAG.CreateStackTemporary(VA.getValVT());
1860       int FI = cast<FrameIndexSDNode>(SpillSlot)->getIndex();
1861       Chain = DAG.getStore(Chain, dl, Arg, SpillSlot,
1862                            PseudoSourceValue::getFixedStack(FI), 0);
1863       Arg = SpillSlot;
1864       break;
1865     }
1866     }
1867
1868     if (VA.isRegLoc()) {
1869       RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
1870     } else {
1871       if (!isTailCall || (isTailCall && isByVal)) {
1872         assert(VA.isMemLoc());
1873         if (StackPtr.getNode() == 0)
1874           StackPtr = DAG.getCopyFromReg(Chain, dl, X86StackPtr, getPointerTy());
1875
1876         MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg,
1877                                                dl, DAG, VA, Flags));
1878       }
1879     }
1880   }
1881
1882   if (!MemOpChains.empty())
1883     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
1884                         &MemOpChains[0], MemOpChains.size());
1885
1886   // Build a sequence of copy-to-reg nodes chained together with token chain
1887   // and flag operands which copy the outgoing args into registers.
1888   SDValue InFlag;
1889   // Tail call byval lowering might overwrite argument registers so in case of
1890   // tail call optimization the copies to registers are lowered later.
1891   if (!isTailCall)
1892     for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
1893       Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
1894                                RegsToPass[i].second, InFlag);
1895       InFlag = Chain.getValue(1);
1896     }
1897
1898
1899   if (Subtarget->isPICStyleGOT()) {
1900     // ELF / PIC requires GOT in the EBX register before function calls via PLT
1901     // GOT pointer.
1902     if (!isTailCall) {
1903       Chain = DAG.getCopyToReg(Chain, dl, X86::EBX,
1904                                DAG.getNode(X86ISD::GlobalBaseReg,
1905                                            DebugLoc::getUnknownLoc(),
1906                                            getPointerTy()),
1907                                InFlag);
1908       InFlag = Chain.getValue(1);
1909     } else {
1910       // If we are tail calling and generating PIC/GOT style code load the
1911       // address of the callee into ECX. The value in ecx is used as target of
1912       // the tail jump. This is done to circumvent the ebx/callee-saved problem
1913       // for tail calls on PIC/GOT architectures. Normally we would just put the
1914       // address of GOT into ebx and then call target@PLT. But for tail calls
1915       // ebx would be restored (since ebx is callee saved) before jumping to the
1916       // target@PLT.
1917
1918       // Note: The actual moving to ECX is done further down.
1919       GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee);
1920       if (G && !G->getGlobal()->hasHiddenVisibility() &&
1921           !G->getGlobal()->hasProtectedVisibility())
1922         Callee = LowerGlobalAddress(Callee, DAG);
1923       else if (isa<ExternalSymbolSDNode>(Callee))
1924         Callee = LowerExternalSymbol(Callee, DAG);
1925     }
1926   }
1927
1928   if (Is64Bit && isVarArg) {
1929     // From AMD64 ABI document:
1930     // For calls that may call functions that use varargs or stdargs
1931     // (prototype-less calls or calls to functions containing ellipsis (...) in
1932     // the declaration) %al is used as hidden argument to specify the number
1933     // of SSE registers used. The contents of %al do not need to match exactly
1934     // the number of registers, but must be an ubound on the number of SSE
1935     // registers used and is in the range 0 - 8 inclusive.
1936
1937     // FIXME: Verify this on Win64
1938     // Count the number of XMM registers allocated.
1939     static const unsigned XMMArgRegs[] = {
1940       X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
1941       X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
1942     };
1943     unsigned NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs, 8);
1944     assert((Subtarget->hasSSE1() || !NumXMMRegs)
1945            && "SSE registers cannot be used when SSE is disabled");
1946
1947     Chain = DAG.getCopyToReg(Chain, dl, X86::AL,
1948                              DAG.getConstant(NumXMMRegs, MVT::i8), InFlag);
1949     InFlag = Chain.getValue(1);
1950   }
1951
1952
1953   // For tail calls lower the arguments to the 'real' stack slot.
1954   if (isTailCall) {
1955     // Force all the incoming stack arguments to be loaded from the stack
1956     // before any new outgoing arguments are stored to the stack, because the
1957     // outgoing stack slots may alias the incoming argument stack slots, and
1958     // the alias isn't otherwise explicit. This is slightly more conservative
1959     // than necessary, because it means that each store effectively depends
1960     // on every argument instead of just those arguments it would clobber.
1961     SDValue ArgChain = DAG.getStackArgumentTokenFactor(Chain);
1962
1963     SmallVector<SDValue, 8> MemOpChains2;
1964     SDValue FIN;
1965     int FI = 0;
1966     // Do not flag preceeding copytoreg stuff together with the following stuff.
1967     InFlag = SDValue();
1968     for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
1969       CCValAssign &VA = ArgLocs[i];
1970       if (!VA.isRegLoc()) {
1971         assert(VA.isMemLoc());
1972         SDValue Arg = Outs[i].Val;
1973         ISD::ArgFlagsTy Flags = Outs[i].Flags;
1974         // Create frame index.
1975         int32_t Offset = VA.getLocMemOffset()+FPDiff;
1976         uint32_t OpSize = (VA.getLocVT().getSizeInBits()+7)/8;
1977         FI = MF.getFrameInfo()->CreateFixedObject(OpSize, Offset, true, false);
1978         FIN = DAG.getFrameIndex(FI, getPointerTy());
1979
1980         if (Flags.isByVal()) {
1981           // Copy relative to framepointer.
1982           SDValue Source = DAG.getIntPtrConstant(VA.getLocMemOffset());
1983           if (StackPtr.getNode() == 0)
1984             StackPtr = DAG.getCopyFromReg(Chain, dl, X86StackPtr,
1985                                           getPointerTy());
1986           Source = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, Source);
1987
1988           MemOpChains2.push_back(CreateCopyOfByValArgument(Source, FIN,
1989                                                            ArgChain,
1990                                                            Flags, DAG, dl));
1991         } else {
1992           // Store relative to framepointer.
1993           MemOpChains2.push_back(
1994             DAG.getStore(ArgChain, dl, Arg, FIN,
1995                          PseudoSourceValue::getFixedStack(FI), 0));
1996         }
1997       }
1998     }
1999
2000     if (!MemOpChains2.empty())
2001       Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
2002                           &MemOpChains2[0], MemOpChains2.size());
2003
2004     // Copy arguments to their registers.
2005     for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
2006       Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
2007                                RegsToPass[i].second, InFlag);
2008       InFlag = Chain.getValue(1);
2009     }
2010     InFlag =SDValue();
2011
2012     // Store the return address to the appropriate stack slot.
2013     Chain = EmitTailCallStoreRetAddr(DAG, MF, Chain, RetAddrFrIdx, Is64Bit,
2014                                      FPDiff, dl);
2015   }
2016
2017   bool WasGlobalOrExternal = false;
2018   if (getTargetMachine().getCodeModel() == CodeModel::Large) {
2019     assert(Is64Bit && "Large code model is only legal in 64-bit mode.");
2020     // In the 64-bit large code model, we have to make all calls
2021     // through a register, since the call instruction's 32-bit
2022     // pc-relative offset may not be large enough to hold the whole
2023     // address.
2024   } else if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
2025     WasGlobalOrExternal = true;
2026     // If the callee is a GlobalAddress node (quite common, every direct call
2027     // is) turn it into a TargetGlobalAddress node so that legalize doesn't hack
2028     // it.
2029
2030     // We should use extra load for direct calls to dllimported functions in
2031     // non-JIT mode.
2032     GlobalValue *GV = G->getGlobal();
2033     if (!GV->hasDLLImportLinkage()) {
2034       unsigned char OpFlags = 0;
2035
2036       // On ELF targets, in both X86-64 and X86-32 mode, direct calls to
2037       // external symbols most go through the PLT in PIC mode.  If the symbol
2038       // has hidden or protected visibility, or if it is static or local, then
2039       // we don't need to use the PLT - we can directly call it.
2040       if (Subtarget->isTargetELF() &&
2041           getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
2042           GV->hasDefaultVisibility() && !GV->hasLocalLinkage()) {
2043         OpFlags = X86II::MO_PLT;
2044       } else if (Subtarget->isPICStyleStubAny() &&
2045                (GV->isDeclaration() || GV->isWeakForLinker()) &&
2046                Subtarget->getDarwinVers() < 9) {
2047         // PC-relative references to external symbols should go through $stub,
2048         // unless we're building with the leopard linker or later, which
2049         // automatically synthesizes these stubs.
2050         OpFlags = X86II::MO_DARWIN_STUB;
2051       }
2052
2053       Callee = DAG.getTargetGlobalAddress(GV, getPointerTy(),
2054                                           G->getOffset(), OpFlags);
2055     }
2056   } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
2057     WasGlobalOrExternal = true;
2058     unsigned char OpFlags = 0;
2059
2060     // On ELF targets, in either X86-64 or X86-32 mode, direct calls to external
2061     // symbols should go through the PLT.
2062     if (Subtarget->isTargetELF() &&
2063         getTargetMachine().getRelocationModel() == Reloc::PIC_) {
2064       OpFlags = X86II::MO_PLT;
2065     } else if (Subtarget->isPICStyleStubAny() &&
2066              Subtarget->getDarwinVers() < 9) {
2067       // PC-relative references to external symbols should go through $stub,
2068       // unless we're building with the leopard linker or later, which
2069       // automatically synthesizes these stubs.
2070       OpFlags = X86II::MO_DARWIN_STUB;
2071     }
2072
2073     Callee = DAG.getTargetExternalSymbol(S->getSymbol(), getPointerTy(),
2074                                          OpFlags);
2075   }
2076
2077   if (isTailCall && !WasGlobalOrExternal) {
2078     unsigned Opc = Is64Bit ? X86::R11 : X86::EAX;
2079
2080     Chain = DAG.getCopyToReg(Chain,  dl,
2081                              DAG.getRegister(Opc, getPointerTy()),
2082                              Callee,InFlag);
2083     Callee = DAG.getRegister(Opc, getPointerTy());
2084     // Add register as live out.
2085     MF.getRegInfo().addLiveOut(Opc);
2086   }
2087
2088   // Returns a chain & a flag for retval copy to use.
2089   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Flag);
2090   SmallVector<SDValue, 8> Ops;
2091
2092   if (isTailCall) {
2093     Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, true),
2094                            DAG.getIntPtrConstant(0, true), InFlag);
2095     InFlag = Chain.getValue(1);
2096   }
2097
2098   Ops.push_back(Chain);
2099   Ops.push_back(Callee);
2100
2101   if (isTailCall)
2102     Ops.push_back(DAG.getConstant(FPDiff, MVT::i32));
2103
2104   // Add argument registers to the end of the list so that they are known live
2105   // into the call.
2106   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
2107     Ops.push_back(DAG.getRegister(RegsToPass[i].first,
2108                                   RegsToPass[i].second.getValueType()));
2109
2110   // Add an implicit use GOT pointer in EBX.
2111   if (!isTailCall && Subtarget->isPICStyleGOT())
2112     Ops.push_back(DAG.getRegister(X86::EBX, getPointerTy()));
2113
2114   // Add an implicit use of AL for x86 vararg functions.
2115   if (Is64Bit && isVarArg)
2116     Ops.push_back(DAG.getRegister(X86::AL, MVT::i8));
2117
2118   if (InFlag.getNode())
2119     Ops.push_back(InFlag);
2120
2121   if (isTailCall) {
2122     // If this is the first return lowered for this function, add the regs
2123     // to the liveout set for the function.
2124     if (MF.getRegInfo().liveout_empty()) {
2125       SmallVector<CCValAssign, 16> RVLocs;
2126       CCState CCInfo(CallConv, isVarArg, getTargetMachine(), RVLocs,
2127                      *DAG.getContext());
2128       CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
2129       for (unsigned i = 0; i != RVLocs.size(); ++i)
2130         if (RVLocs[i].isRegLoc())
2131           MF.getRegInfo().addLiveOut(RVLocs[i].getLocReg());
2132     }
2133
2134     assert(((Callee.getOpcode() == ISD::Register &&
2135                (cast<RegisterSDNode>(Callee)->getReg() == X86::EAX ||
2136                 cast<RegisterSDNode>(Callee)->getReg() == X86::R11)) ||
2137               Callee.getOpcode() == ISD::TargetExternalSymbol ||
2138               Callee.getOpcode() == ISD::TargetGlobalAddress) &&
2139            "Expecting a global address, external symbol, or scratch register");
2140
2141     return DAG.getNode(X86ISD::TC_RETURN, dl,
2142                        NodeTys, &Ops[0], Ops.size());
2143   }
2144
2145   Chain = DAG.getNode(X86ISD::CALL, dl, NodeTys, &Ops[0], Ops.size());
2146   InFlag = Chain.getValue(1);
2147
2148   // Create the CALLSEQ_END node.
2149   unsigned NumBytesForCalleeToPush;
2150   if (IsCalleePop(isVarArg, CallConv))
2151     NumBytesForCalleeToPush = NumBytes;    // Callee pops everything
2152   else if (!Is64Bit && CallConv != CallingConv::Fast && IsStructRet)
2153     // If this is is a call to a struct-return function, the callee
2154     // pops the hidden struct pointer, so we have to push it back.
2155     // This is common for Darwin/X86, Linux & Mingw32 targets.
2156     NumBytesForCalleeToPush = 4;
2157   else
2158     NumBytesForCalleeToPush = 0;  // Callee pops nothing.
2159
2160   // Returns a flag for retval copy to use.
2161   Chain = DAG.getCALLSEQ_END(Chain,
2162                              DAG.getIntPtrConstant(NumBytes, true),
2163                              DAG.getIntPtrConstant(NumBytesForCalleeToPush,
2164                                                    true),
2165                              InFlag);
2166   InFlag = Chain.getValue(1);
2167
2168   // Handle result values, copying them out of physregs into vregs that we
2169   // return.
2170   return LowerCallResult(Chain, InFlag, CallConv, isVarArg,
2171                          Ins, dl, DAG, InVals);
2172 }
2173
2174
2175 //===----------------------------------------------------------------------===//
2176 //                Fast Calling Convention (tail call) implementation
2177 //===----------------------------------------------------------------------===//
2178
2179 //  Like std call, callee cleans arguments, convention except that ECX is
2180 //  reserved for storing the tail called function address. Only 2 registers are
2181 //  free for argument passing (inreg). Tail call optimization is performed
2182 //  provided:
2183 //                * tailcallopt is enabled
2184 //                * caller/callee are fastcc
2185 //  On X86_64 architecture with GOT-style position independent code only local
2186 //  (within module) calls are supported at the moment.
2187 //  To keep the stack aligned according to platform abi the function
2188 //  GetAlignedArgumentStackSize ensures that argument delta is always multiples
2189 //  of stack alignment. (Dynamic linkers need this - darwin's dyld for example)
2190 //  If a tail called function callee has more arguments than the caller the
2191 //  caller needs to make sure that there is room to move the RETADDR to. This is
2192 //  achieved by reserving an area the size of the argument delta right after the
2193 //  original REtADDR, but before the saved framepointer or the spilled registers
2194 //  e.g. caller(arg1, arg2) calls callee(arg1, arg2,arg3,arg4)
2195 //  stack layout:
2196 //    arg1
2197 //    arg2
2198 //    RETADDR
2199 //    [ new RETADDR
2200 //      move area ]
2201 //    (possible EBP)
2202 //    ESI
2203 //    EDI
2204 //    local1 ..
2205
2206 /// GetAlignedArgumentStackSize - Make the stack size align e.g 16n + 12 aligned
2207 /// for a 16 byte align requirement.
2208 unsigned X86TargetLowering::GetAlignedArgumentStackSize(unsigned StackSize,
2209                                                         SelectionDAG& DAG) {
2210   MachineFunction &MF = DAG.getMachineFunction();
2211   const TargetMachine &TM = MF.getTarget();
2212   const TargetFrameInfo &TFI = *TM.getFrameInfo();
2213   unsigned StackAlignment = TFI.getStackAlignment();
2214   uint64_t AlignMask = StackAlignment - 1;
2215   int64_t Offset = StackSize;
2216   uint64_t SlotSize = TD->getPointerSize();
2217   if ( (Offset & AlignMask) <= (StackAlignment - SlotSize) ) {
2218     // Number smaller than 12 so just add the difference.
2219     Offset += ((StackAlignment - SlotSize) - (Offset & AlignMask));
2220   } else {
2221     // Mask out lower bits, add stackalignment once plus the 12 bytes.
2222     Offset = ((~AlignMask) & Offset) + StackAlignment +
2223       (StackAlignment-SlotSize);
2224   }
2225   return Offset;
2226 }
2227
2228 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
2229 /// for tail call optimization. Targets which want to do tail call
2230 /// optimization should implement this function.
2231 bool
2232 X86TargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
2233                                                      CallingConv::ID CalleeCC,
2234                                                      bool isVarArg,
2235                                       const SmallVectorImpl<ISD::InputArg> &Ins,
2236                                                      SelectionDAG& DAG) const {
2237   return X86::IsEligibleForTailCallOpt(CalleeCC) &&
2238     DAG.getMachineFunction().getFunction()->getCallingConv() == CalleeCC;
2239 }
2240
2241 FastISel *
2242 X86TargetLowering::createFastISel(MachineFunction &mf, MachineModuleInfo *mmo,
2243                             DwarfWriter *dw,
2244                             DenseMap<const Value *, unsigned> &vm,
2245                             DenseMap<const BasicBlock*, MachineBasicBlock*> &bm,
2246                             DenseMap<const AllocaInst *, int> &am
2247 #ifndef NDEBUG
2248                           , SmallSet<Instruction*, 8> &cil
2249 #endif
2250                                   ) {
2251   return X86::createFastISel(mf, mmo, dw, vm, bm, am
2252 #ifndef NDEBUG
2253                              , cil
2254 #endif
2255                              );
2256 }
2257
2258
2259 //===----------------------------------------------------------------------===//
2260 //                           Other Lowering Hooks
2261 //===----------------------------------------------------------------------===//
2262
2263
2264 SDValue X86TargetLowering::getReturnAddressFrameIndex(SelectionDAG &DAG) {
2265   MachineFunction &MF = DAG.getMachineFunction();
2266   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
2267   int ReturnAddrIndex = FuncInfo->getRAIndex();
2268
2269   if (ReturnAddrIndex == 0) {
2270     // Set up a frame object for the return address.
2271     uint64_t SlotSize = TD->getPointerSize();
2272     ReturnAddrIndex = MF.getFrameInfo()->CreateFixedObject(SlotSize, -SlotSize,
2273                                                            true, false);
2274     FuncInfo->setRAIndex(ReturnAddrIndex);
2275   }
2276
2277   return DAG.getFrameIndex(ReturnAddrIndex, getPointerTy());
2278 }
2279
2280
2281 bool X86::isOffsetSuitableForCodeModel(int64_t Offset, CodeModel::Model M,
2282                                        bool hasSymbolicDisplacement) {
2283   // Offset should fit into 32 bit immediate field.
2284   if (!isInt32(Offset))
2285     return false;
2286
2287   // If we don't have a symbolic displacement - we don't have any extra
2288   // restrictions.
2289   if (!hasSymbolicDisplacement)
2290     return true;
2291
2292   // FIXME: Some tweaks might be needed for medium code model.
2293   if (M != CodeModel::Small && M != CodeModel::Kernel)
2294     return false;
2295
2296   // For small code model we assume that latest object is 16MB before end of 31
2297   // bits boundary. We may also accept pretty large negative constants knowing
2298   // that all objects are in the positive half of address space.
2299   if (M == CodeModel::Small && Offset < 16*1024*1024)
2300     return true;
2301
2302   // For kernel code model we know that all object resist in the negative half
2303   // of 32bits address space. We may not accept negative offsets, since they may
2304   // be just off and we may accept pretty large positive ones.
2305   if (M == CodeModel::Kernel && Offset > 0)
2306     return true;
2307
2308   return false;
2309 }
2310
2311 bool X86::IsEligibleForTailCallOpt(CallingConv::ID CC) {
2312   return PerformTailCallOpt && CC == CallingConv::Fast;
2313 }
2314
2315 /// TranslateX86CC - do a one to one translation of a ISD::CondCode to the X86
2316 /// specific condition code, returning the condition code and the LHS/RHS of the
2317 /// comparison to make.
2318 static unsigned TranslateX86CC(ISD::CondCode SetCCOpcode, bool isFP,
2319                                SDValue &LHS, SDValue &RHS, SelectionDAG &DAG) {
2320   if (!isFP) {
2321     if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) {
2322       if (SetCCOpcode == ISD::SETGT && RHSC->isAllOnesValue()) {
2323         // X > -1   -> X == 0, jump !sign.
2324         RHS = DAG.getConstant(0, RHS.getValueType());
2325         return X86::COND_NS;
2326       } else if (SetCCOpcode == ISD::SETLT && RHSC->isNullValue()) {
2327         // X < 0   -> X == 0, jump on sign.
2328         return X86::COND_S;
2329       } else if (SetCCOpcode == ISD::SETLT && RHSC->getZExtValue() == 1) {
2330         // X < 1   -> X <= 0
2331         RHS = DAG.getConstant(0, RHS.getValueType());
2332         return X86::COND_LE;
2333       }
2334     }
2335
2336     switch (SetCCOpcode) {
2337     default: llvm_unreachable("Invalid integer condition!");
2338     case ISD::SETEQ:  return X86::COND_E;
2339     case ISD::SETGT:  return X86::COND_G;
2340     case ISD::SETGE:  return X86::COND_GE;
2341     case ISD::SETLT:  return X86::COND_L;
2342     case ISD::SETLE:  return X86::COND_LE;
2343     case ISD::SETNE:  return X86::COND_NE;
2344     case ISD::SETULT: return X86::COND_B;
2345     case ISD::SETUGT: return X86::COND_A;
2346     case ISD::SETULE: return X86::COND_BE;
2347     case ISD::SETUGE: return X86::COND_AE;
2348     }
2349   }
2350
2351   // First determine if it is required or is profitable to flip the operands.
2352
2353   // If LHS is a foldable load, but RHS is not, flip the condition.
2354   if ((ISD::isNON_EXTLoad(LHS.getNode()) && LHS.hasOneUse()) &&
2355       !(ISD::isNON_EXTLoad(RHS.getNode()) && RHS.hasOneUse())) {
2356     SetCCOpcode = getSetCCSwappedOperands(SetCCOpcode);
2357     std::swap(LHS, RHS);
2358   }
2359
2360   switch (SetCCOpcode) {
2361   default: break;
2362   case ISD::SETOLT:
2363   case ISD::SETOLE:
2364   case ISD::SETUGT:
2365   case ISD::SETUGE:
2366     std::swap(LHS, RHS);
2367     break;
2368   }
2369
2370   // On a floating point condition, the flags are set as follows:
2371   // ZF  PF  CF   op
2372   //  0 | 0 | 0 | X > Y
2373   //  0 | 0 | 1 | X < Y
2374   //  1 | 0 | 0 | X == Y
2375   //  1 | 1 | 1 | unordered
2376   switch (SetCCOpcode) {
2377   default: llvm_unreachable("Condcode should be pre-legalized away");
2378   case ISD::SETUEQ:
2379   case ISD::SETEQ:   return X86::COND_E;
2380   case ISD::SETOLT:              // flipped
2381   case ISD::SETOGT:
2382   case ISD::SETGT:   return X86::COND_A;
2383   case ISD::SETOLE:              // flipped
2384   case ISD::SETOGE:
2385   case ISD::SETGE:   return X86::COND_AE;
2386   case ISD::SETUGT:              // flipped
2387   case ISD::SETULT:
2388   case ISD::SETLT:   return X86::COND_B;
2389   case ISD::SETUGE:              // flipped
2390   case ISD::SETULE:
2391   case ISD::SETLE:   return X86::COND_BE;
2392   case ISD::SETONE:
2393   case ISD::SETNE:   return X86::COND_NE;
2394   case ISD::SETUO:   return X86::COND_P;
2395   case ISD::SETO:    return X86::COND_NP;
2396   case ISD::SETOEQ:
2397   case ISD::SETUNE:  return X86::COND_INVALID;
2398   }
2399 }
2400
2401 /// hasFPCMov - is there a floating point cmov for the specific X86 condition
2402 /// code. Current x86 isa includes the following FP cmov instructions:
2403 /// fcmovb, fcomvbe, fcomve, fcmovu, fcmovae, fcmova, fcmovne, fcmovnu.
2404 static bool hasFPCMov(unsigned X86CC) {
2405   switch (X86CC) {
2406   default:
2407     return false;
2408   case X86::COND_B:
2409   case X86::COND_BE:
2410   case X86::COND_E:
2411   case X86::COND_P:
2412   case X86::COND_A:
2413   case X86::COND_AE:
2414   case X86::COND_NE:
2415   case X86::COND_NP:
2416     return true;
2417   }
2418 }
2419
2420 /// isFPImmLegal - Returns true if the target can instruction select the
2421 /// specified FP immediate natively. If false, the legalizer will
2422 /// materialize the FP immediate as a load from a constant pool.
2423 bool X86TargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
2424   for (unsigned i = 0, e = LegalFPImmediates.size(); i != e; ++i) {
2425     if (Imm.bitwiseIsEqual(LegalFPImmediates[i]))
2426       return true;
2427   }
2428   return false;
2429 }
2430
2431 /// isUndefOrInRange - Return true if Val is undef or if its value falls within
2432 /// the specified range (L, H].
2433 static bool isUndefOrInRange(int Val, int Low, int Hi) {
2434   return (Val < 0) || (Val >= Low && Val < Hi);
2435 }
2436
2437 /// isUndefOrEqual - Val is either less than zero (undef) or equal to the
2438 /// specified value.
2439 static bool isUndefOrEqual(int Val, int CmpVal) {
2440   if (Val < 0 || Val == CmpVal)
2441     return true;
2442   return false;
2443 }
2444
2445 /// isPSHUFDMask - Return true if the node specifies a shuffle of elements that
2446 /// is suitable for input to PSHUFD or PSHUFW.  That is, it doesn't reference
2447 /// the second operand.
2448 static bool isPSHUFDMask(const SmallVectorImpl<int> &Mask, EVT VT) {
2449   if (VT == MVT::v4f32 || VT == MVT::v4i32 || VT == MVT::v4i16)
2450     return (Mask[0] < 4 && Mask[1] < 4 && Mask[2] < 4 && Mask[3] < 4);
2451   if (VT == MVT::v2f64 || VT == MVT::v2i64)
2452     return (Mask[0] < 2 && Mask[1] < 2);
2453   return false;
2454 }
2455
2456 bool X86::isPSHUFDMask(ShuffleVectorSDNode *N) {
2457   SmallVector<int, 8> M;
2458   N->getMask(M);
2459   return ::isPSHUFDMask(M, N->getValueType(0));
2460 }
2461
2462 /// isPSHUFHWMask - Return true if the node specifies a shuffle of elements that
2463 /// is suitable for input to PSHUFHW.
2464 static bool isPSHUFHWMask(const SmallVectorImpl<int> &Mask, EVT VT) {
2465   if (VT != MVT::v8i16)
2466     return false;
2467
2468   // Lower quadword copied in order or undef.
2469   for (int i = 0; i != 4; ++i)
2470     if (Mask[i] >= 0 && Mask[i] != i)
2471       return false;
2472
2473   // Upper quadword shuffled.
2474   for (int i = 4; i != 8; ++i)
2475     if (Mask[i] >= 0 && (Mask[i] < 4 || Mask[i] > 7))
2476       return false;
2477
2478   return true;
2479 }
2480
2481 bool X86::isPSHUFHWMask(ShuffleVectorSDNode *N) {
2482   SmallVector<int, 8> M;
2483   N->getMask(M);
2484   return ::isPSHUFHWMask(M, N->getValueType(0));
2485 }
2486
2487 /// isPSHUFLWMask - Return true if the node specifies a shuffle of elements that
2488 /// is suitable for input to PSHUFLW.
2489 static bool isPSHUFLWMask(const SmallVectorImpl<int> &Mask, EVT VT) {
2490   if (VT != MVT::v8i16)
2491     return false;
2492
2493   // Upper quadword copied in order.
2494   for (int i = 4; i != 8; ++i)
2495     if (Mask[i] >= 0 && Mask[i] != i)
2496       return false;
2497
2498   // Lower quadword shuffled.
2499   for (int i = 0; i != 4; ++i)
2500     if (Mask[i] >= 4)
2501       return false;
2502
2503   return true;
2504 }
2505
2506 bool X86::isPSHUFLWMask(ShuffleVectorSDNode *N) {
2507   SmallVector<int, 8> M;
2508   N->getMask(M);
2509   return ::isPSHUFLWMask(M, N->getValueType(0));
2510 }
2511
2512 /// isPALIGNRMask - Return true if the node specifies a shuffle of elements that
2513 /// is suitable for input to PALIGNR.
2514 static bool isPALIGNRMask(const SmallVectorImpl<int> &Mask, EVT VT,
2515                           bool hasSSSE3) {
2516   int i, e = VT.getVectorNumElements();
2517   
2518   // Do not handle v2i64 / v2f64 shuffles with palignr.
2519   if (e < 4 || !hasSSSE3)
2520     return false;
2521   
2522   for (i = 0; i != e; ++i)
2523     if (Mask[i] >= 0)
2524       break;
2525   
2526   // All undef, not a palignr.
2527   if (i == e)
2528     return false;
2529
2530   // Determine if it's ok to perform a palignr with only the LHS, since we
2531   // don't have access to the actual shuffle elements to see if RHS is undef.
2532   bool Unary = Mask[i] < (int)e;
2533   bool NeedsUnary = false;
2534
2535   int s = Mask[i] - i;
2536   
2537   // Check the rest of the elements to see if they are consecutive.
2538   for (++i; i != e; ++i) {
2539     int m = Mask[i];
2540     if (m < 0) 
2541       continue;
2542     
2543     Unary = Unary && (m < (int)e);
2544     NeedsUnary = NeedsUnary || (m < s);
2545
2546     if (NeedsUnary && !Unary)
2547       return false;
2548     if (Unary && m != ((s+i) & (e-1)))
2549       return false;
2550     if (!Unary && m != (s+i))
2551       return false;
2552   }
2553   return true;
2554 }
2555
2556 bool X86::isPALIGNRMask(ShuffleVectorSDNode *N) {
2557   SmallVector<int, 8> M;
2558   N->getMask(M);
2559   return ::isPALIGNRMask(M, N->getValueType(0), true);
2560 }
2561
2562 /// isSHUFPMask - Return true if the specified VECTOR_SHUFFLE operand
2563 /// specifies a shuffle of elements that is suitable for input to SHUFP*.
2564 static bool isSHUFPMask(const SmallVectorImpl<int> &Mask, EVT VT) {
2565   int NumElems = VT.getVectorNumElements();
2566   if (NumElems != 2 && NumElems != 4)
2567     return false;
2568
2569   int Half = NumElems / 2;
2570   for (int i = 0; i < Half; ++i)
2571     if (!isUndefOrInRange(Mask[i], 0, NumElems))
2572       return false;
2573   for (int i = Half; i < NumElems; ++i)
2574     if (!isUndefOrInRange(Mask[i], NumElems, NumElems*2))
2575       return false;
2576
2577   return true;
2578 }
2579
2580 bool X86::isSHUFPMask(ShuffleVectorSDNode *N) {
2581   SmallVector<int, 8> M;
2582   N->getMask(M);
2583   return ::isSHUFPMask(M, N->getValueType(0));
2584 }
2585
2586 /// isCommutedSHUFP - Returns true if the shuffle mask is exactly
2587 /// the reverse of what x86 shuffles want. x86 shuffles requires the lower
2588 /// half elements to come from vector 1 (which would equal the dest.) and
2589 /// the upper half to come from vector 2.
2590 static bool isCommutedSHUFPMask(const SmallVectorImpl<int> &Mask, EVT VT) {
2591   int NumElems = VT.getVectorNumElements();
2592
2593   if (NumElems != 2 && NumElems != 4)
2594     return false;
2595
2596   int Half = NumElems / 2;
2597   for (int i = 0; i < Half; ++i)
2598     if (!isUndefOrInRange(Mask[i], NumElems, NumElems*2))
2599       return false;
2600   for (int i = Half; i < NumElems; ++i)
2601     if (!isUndefOrInRange(Mask[i], 0, NumElems))
2602       return false;
2603   return true;
2604 }
2605
2606 static bool isCommutedSHUFP(ShuffleVectorSDNode *N) {
2607   SmallVector<int, 8> M;
2608   N->getMask(M);
2609   return isCommutedSHUFPMask(M, N->getValueType(0));
2610 }
2611
2612 /// isMOVHLPSMask - Return true if the specified VECTOR_SHUFFLE operand
2613 /// specifies a shuffle of elements that is suitable for input to MOVHLPS.
2614 bool X86::isMOVHLPSMask(ShuffleVectorSDNode *N) {
2615   if (N->getValueType(0).getVectorNumElements() != 4)
2616     return false;
2617
2618   // Expect bit0 == 6, bit1 == 7, bit2 == 2, bit3 == 3
2619   return isUndefOrEqual(N->getMaskElt(0), 6) &&
2620          isUndefOrEqual(N->getMaskElt(1), 7) &&
2621          isUndefOrEqual(N->getMaskElt(2), 2) &&
2622          isUndefOrEqual(N->getMaskElt(3), 3);
2623 }
2624
2625 /// isMOVHLPS_v_undef_Mask - Special case of isMOVHLPSMask for canonical form
2626 /// of vector_shuffle v, v, <2, 3, 2, 3>, i.e. vector_shuffle v, undef,
2627 /// <2, 3, 2, 3>
2628 bool X86::isMOVHLPS_v_undef_Mask(ShuffleVectorSDNode *N) {
2629   unsigned NumElems = N->getValueType(0).getVectorNumElements();
2630   
2631   if (NumElems != 4)
2632     return false;
2633   
2634   return isUndefOrEqual(N->getMaskElt(0), 2) &&
2635   isUndefOrEqual(N->getMaskElt(1), 3) &&
2636   isUndefOrEqual(N->getMaskElt(2), 2) &&
2637   isUndefOrEqual(N->getMaskElt(3), 3);
2638 }
2639
2640 /// isMOVLPMask - Return true if the specified VECTOR_SHUFFLE operand
2641 /// specifies a shuffle of elements that is suitable for input to MOVLP{S|D}.
2642 bool X86::isMOVLPMask(ShuffleVectorSDNode *N) {
2643   unsigned NumElems = N->getValueType(0).getVectorNumElements();
2644
2645   if (NumElems != 2 && NumElems != 4)
2646     return false;
2647
2648   for (unsigned i = 0; i < NumElems/2; ++i)
2649     if (!isUndefOrEqual(N->getMaskElt(i), i + NumElems))
2650       return false;
2651
2652   for (unsigned i = NumElems/2; i < NumElems; ++i)
2653     if (!isUndefOrEqual(N->getMaskElt(i), i))
2654       return false;
2655
2656   return true;
2657 }
2658
2659 /// isMOVLHPSMask - Return true if the specified VECTOR_SHUFFLE operand
2660 /// specifies a shuffle of elements that is suitable for input to MOVLHPS.
2661 bool X86::isMOVLHPSMask(ShuffleVectorSDNode *N) {
2662   unsigned NumElems = N->getValueType(0).getVectorNumElements();
2663
2664   if (NumElems != 2 && NumElems != 4)
2665     return false;
2666
2667   for (unsigned i = 0; i < NumElems/2; ++i)
2668     if (!isUndefOrEqual(N->getMaskElt(i), i))
2669       return false;
2670
2671   for (unsigned i = 0; i < NumElems/2; ++i)
2672     if (!isUndefOrEqual(N->getMaskElt(i + NumElems/2), i + NumElems))
2673       return false;
2674
2675   return true;
2676 }
2677
2678 /// isUNPCKLMask - Return true if the specified VECTOR_SHUFFLE operand
2679 /// specifies a shuffle of elements that is suitable for input to UNPCKL.
2680 static bool isUNPCKLMask(const SmallVectorImpl<int> &Mask, EVT VT,
2681                          bool V2IsSplat = false) {
2682   int NumElts = VT.getVectorNumElements();
2683   if (NumElts != 2 && NumElts != 4 && NumElts != 8 && NumElts != 16)
2684     return false;
2685
2686   for (int i = 0, j = 0; i != NumElts; i += 2, ++j) {
2687     int BitI  = Mask[i];
2688     int BitI1 = Mask[i+1];
2689     if (!isUndefOrEqual(BitI, j))
2690       return false;
2691     if (V2IsSplat) {
2692       if (!isUndefOrEqual(BitI1, NumElts))
2693         return false;
2694     } else {
2695       if (!isUndefOrEqual(BitI1, j + NumElts))
2696         return false;
2697     }
2698   }
2699   return true;
2700 }
2701
2702 bool X86::isUNPCKLMask(ShuffleVectorSDNode *N, bool V2IsSplat) {
2703   SmallVector<int, 8> M;
2704   N->getMask(M);
2705   return ::isUNPCKLMask(M, N->getValueType(0), V2IsSplat);
2706 }
2707
2708 /// isUNPCKHMask - Return true if the specified VECTOR_SHUFFLE operand
2709 /// specifies a shuffle of elements that is suitable for input to UNPCKH.
2710 static bool isUNPCKHMask(const SmallVectorImpl<int> &Mask, EVT VT,
2711                          bool V2IsSplat = false) {
2712   int NumElts = VT.getVectorNumElements();
2713   if (NumElts != 2 && NumElts != 4 && NumElts != 8 && NumElts != 16)
2714     return false;
2715
2716   for (int i = 0, j = 0; i != NumElts; i += 2, ++j) {
2717     int BitI  = Mask[i];
2718     int BitI1 = Mask[i+1];
2719     if (!isUndefOrEqual(BitI, j + NumElts/2))
2720       return false;
2721     if (V2IsSplat) {
2722       if (isUndefOrEqual(BitI1, NumElts))
2723         return false;
2724     } else {
2725       if (!isUndefOrEqual(BitI1, j + NumElts/2 + NumElts))
2726         return false;
2727     }
2728   }
2729   return true;
2730 }
2731
2732 bool X86::isUNPCKHMask(ShuffleVectorSDNode *N, bool V2IsSplat) {
2733   SmallVector<int, 8> M;
2734   N->getMask(M);
2735   return ::isUNPCKHMask(M, N->getValueType(0), V2IsSplat);
2736 }
2737
2738 /// isUNPCKL_v_undef_Mask - Special case of isUNPCKLMask for canonical form
2739 /// of vector_shuffle v, v, <0, 4, 1, 5>, i.e. vector_shuffle v, undef,
2740 /// <0, 0, 1, 1>
2741 static bool isUNPCKL_v_undef_Mask(const SmallVectorImpl<int> &Mask, EVT VT) {
2742   int NumElems = VT.getVectorNumElements();
2743   if (NumElems != 2 && NumElems != 4 && NumElems != 8 && NumElems != 16)
2744     return false;
2745
2746   for (int i = 0, j = 0; i != NumElems; i += 2, ++j) {
2747     int BitI  = Mask[i];
2748     int BitI1 = Mask[i+1];
2749     if (!isUndefOrEqual(BitI, j))
2750       return false;
2751     if (!isUndefOrEqual(BitI1, j))
2752       return false;
2753   }
2754   return true;
2755 }
2756
2757 bool X86::isUNPCKL_v_undef_Mask(ShuffleVectorSDNode *N) {
2758   SmallVector<int, 8> M;
2759   N->getMask(M);
2760   return ::isUNPCKL_v_undef_Mask(M, N->getValueType(0));
2761 }
2762
2763 /// isUNPCKH_v_undef_Mask - Special case of isUNPCKHMask for canonical form
2764 /// of vector_shuffle v, v, <2, 6, 3, 7>, i.e. vector_shuffle v, undef,
2765 /// <2, 2, 3, 3>
2766 static bool isUNPCKH_v_undef_Mask(const SmallVectorImpl<int> &Mask, EVT VT) {
2767   int NumElems = VT.getVectorNumElements();
2768   if (NumElems != 2 && NumElems != 4 && NumElems != 8 && NumElems != 16)
2769     return false;
2770
2771   for (int i = 0, j = NumElems / 2; i != NumElems; i += 2, ++j) {
2772     int BitI  = Mask[i];
2773     int BitI1 = Mask[i+1];
2774     if (!isUndefOrEqual(BitI, j))
2775       return false;
2776     if (!isUndefOrEqual(BitI1, j))
2777       return false;
2778   }
2779   return true;
2780 }
2781
2782 bool X86::isUNPCKH_v_undef_Mask(ShuffleVectorSDNode *N) {
2783   SmallVector<int, 8> M;
2784   N->getMask(M);
2785   return ::isUNPCKH_v_undef_Mask(M, N->getValueType(0));
2786 }
2787
2788 /// isMOVLMask - Return true if the specified VECTOR_SHUFFLE operand
2789 /// specifies a shuffle of elements that is suitable for input to MOVSS,
2790 /// MOVSD, and MOVD, i.e. setting the lowest element.
2791 static bool isMOVLMask(const SmallVectorImpl<int> &Mask, EVT VT) {
2792   if (VT.getVectorElementType().getSizeInBits() < 32)
2793     return false;
2794
2795   int NumElts = VT.getVectorNumElements();
2796
2797   if (!isUndefOrEqual(Mask[0], NumElts))
2798     return false;
2799
2800   for (int i = 1; i < NumElts; ++i)
2801     if (!isUndefOrEqual(Mask[i], i))
2802       return false;
2803
2804   return true;
2805 }
2806
2807 bool X86::isMOVLMask(ShuffleVectorSDNode *N) {
2808   SmallVector<int, 8> M;
2809   N->getMask(M);
2810   return ::isMOVLMask(M, N->getValueType(0));
2811 }
2812
2813 /// isCommutedMOVL - Returns true if the shuffle mask is except the reverse
2814 /// of what x86 movss want. X86 movs requires the lowest  element to be lowest
2815 /// element of vector 2 and the other elements to come from vector 1 in order.
2816 static bool isCommutedMOVLMask(const SmallVectorImpl<int> &Mask, EVT VT,
2817                                bool V2IsSplat = false, bool V2IsUndef = false) {
2818   int NumOps = VT.getVectorNumElements();
2819   if (NumOps != 2 && NumOps != 4 && NumOps != 8 && NumOps != 16)
2820     return false;
2821
2822   if (!isUndefOrEqual(Mask[0], 0))
2823     return false;
2824
2825   for (int i = 1; i < NumOps; ++i)
2826     if (!(isUndefOrEqual(Mask[i], i+NumOps) ||
2827           (V2IsUndef && isUndefOrInRange(Mask[i], NumOps, NumOps*2)) ||
2828           (V2IsSplat && isUndefOrEqual(Mask[i], NumOps))))
2829       return false;
2830
2831   return true;
2832 }
2833
2834 static bool isCommutedMOVL(ShuffleVectorSDNode *N, bool V2IsSplat = false,
2835                            bool V2IsUndef = false) {
2836   SmallVector<int, 8> M;
2837   N->getMask(M);
2838   return isCommutedMOVLMask(M, N->getValueType(0), V2IsSplat, V2IsUndef);
2839 }
2840
2841 /// isMOVSHDUPMask - Return true if the specified VECTOR_SHUFFLE operand
2842 /// specifies a shuffle of elements that is suitable for input to MOVSHDUP.
2843 bool X86::isMOVSHDUPMask(ShuffleVectorSDNode *N) {
2844   if (N->getValueType(0).getVectorNumElements() != 4)
2845     return false;
2846
2847   // Expect 1, 1, 3, 3
2848   for (unsigned i = 0; i < 2; ++i) {
2849     int Elt = N->getMaskElt(i);
2850     if (Elt >= 0 && Elt != 1)
2851       return false;
2852   }
2853
2854   bool HasHi = false;
2855   for (unsigned i = 2; i < 4; ++i) {
2856     int Elt = N->getMaskElt(i);
2857     if (Elt >= 0 && Elt != 3)
2858       return false;
2859     if (Elt == 3)
2860       HasHi = true;
2861   }
2862   // Don't use movshdup if it can be done with a shufps.
2863   // FIXME: verify that matching u, u, 3, 3 is what we want.
2864   return HasHi;
2865 }
2866
2867 /// isMOVSLDUPMask - Return true if the specified VECTOR_SHUFFLE operand
2868 /// specifies a shuffle of elements that is suitable for input to MOVSLDUP.
2869 bool X86::isMOVSLDUPMask(ShuffleVectorSDNode *N) {
2870   if (N->getValueType(0).getVectorNumElements() != 4)
2871     return false;
2872
2873   // Expect 0, 0, 2, 2
2874   for (unsigned i = 0; i < 2; ++i)
2875     if (N->getMaskElt(i) > 0)
2876       return false;
2877
2878   bool HasHi = false;
2879   for (unsigned i = 2; i < 4; ++i) {
2880     int Elt = N->getMaskElt(i);
2881     if (Elt >= 0 && Elt != 2)
2882       return false;
2883     if (Elt == 2)
2884       HasHi = true;
2885   }
2886   // Don't use movsldup if it can be done with a shufps.
2887   return HasHi;
2888 }
2889
2890 /// isMOVDDUPMask - Return true if the specified VECTOR_SHUFFLE operand
2891 /// specifies a shuffle of elements that is suitable for input to MOVDDUP.
2892 bool X86::isMOVDDUPMask(ShuffleVectorSDNode *N) {
2893   int e = N->getValueType(0).getVectorNumElements() / 2;
2894
2895   for (int i = 0; i < e; ++i)
2896     if (!isUndefOrEqual(N->getMaskElt(i), i))
2897       return false;
2898   for (int i = 0; i < e; ++i)
2899     if (!isUndefOrEqual(N->getMaskElt(e+i), i))
2900       return false;
2901   return true;
2902 }
2903
2904 /// getShuffleSHUFImmediate - Return the appropriate immediate to shuffle
2905 /// the specified VECTOR_SHUFFLE mask with PSHUF* and SHUFP* instructions.
2906 unsigned X86::getShuffleSHUFImmediate(SDNode *N) {
2907   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
2908   int NumOperands = SVOp->getValueType(0).getVectorNumElements();
2909
2910   unsigned Shift = (NumOperands == 4) ? 2 : 1;
2911   unsigned Mask = 0;
2912   for (int i = 0; i < NumOperands; ++i) {
2913     int Val = SVOp->getMaskElt(NumOperands-i-1);
2914     if (Val < 0) Val = 0;
2915     if (Val >= NumOperands) Val -= NumOperands;
2916     Mask |= Val;
2917     if (i != NumOperands - 1)
2918       Mask <<= Shift;
2919   }
2920   return Mask;
2921 }
2922
2923 /// getShufflePSHUFHWImmediate - Return the appropriate immediate to shuffle
2924 /// the specified VECTOR_SHUFFLE mask with the PSHUFHW instruction.
2925 unsigned X86::getShufflePSHUFHWImmediate(SDNode *N) {
2926   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
2927   unsigned Mask = 0;
2928   // 8 nodes, but we only care about the last 4.
2929   for (unsigned i = 7; i >= 4; --i) {
2930     int Val = SVOp->getMaskElt(i);
2931     if (Val >= 0)
2932       Mask |= (Val - 4);
2933     if (i != 4)
2934       Mask <<= 2;
2935   }
2936   return Mask;
2937 }
2938
2939 /// getShufflePSHUFLWImmediate - Return the appropriate immediate to shuffle
2940 /// the specified VECTOR_SHUFFLE mask with the PSHUFLW instruction.
2941 unsigned X86::getShufflePSHUFLWImmediate(SDNode *N) {
2942   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
2943   unsigned Mask = 0;
2944   // 8 nodes, but we only care about the first 4.
2945   for (int i = 3; i >= 0; --i) {
2946     int Val = SVOp->getMaskElt(i);
2947     if (Val >= 0)
2948       Mask |= Val;
2949     if (i != 0)
2950       Mask <<= 2;
2951   }
2952   return Mask;
2953 }
2954
2955 /// getShufflePALIGNRImmediate - Return the appropriate immediate to shuffle
2956 /// the specified VECTOR_SHUFFLE mask with the PALIGNR instruction.
2957 unsigned X86::getShufflePALIGNRImmediate(SDNode *N) {
2958   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
2959   EVT VVT = N->getValueType(0);
2960   unsigned EltSize = VVT.getVectorElementType().getSizeInBits() >> 3;
2961   int Val = 0;
2962
2963   unsigned i, e;
2964   for (i = 0, e = VVT.getVectorNumElements(); i != e; ++i) {
2965     Val = SVOp->getMaskElt(i);
2966     if (Val >= 0)
2967       break;
2968   }
2969   return (Val - i) * EltSize;
2970 }
2971
2972 /// isZeroNode - Returns true if Elt is a constant zero or a floating point
2973 /// constant +0.0.
2974 bool X86::isZeroNode(SDValue Elt) {
2975   return ((isa<ConstantSDNode>(Elt) &&
2976            cast<ConstantSDNode>(Elt)->getZExtValue() == 0) ||
2977           (isa<ConstantFPSDNode>(Elt) &&
2978            cast<ConstantFPSDNode>(Elt)->getValueAPF().isPosZero()));
2979 }
2980
2981 /// CommuteVectorShuffle - Swap vector_shuffle operands as well as values in
2982 /// their permute mask.
2983 static SDValue CommuteVectorShuffle(ShuffleVectorSDNode *SVOp,
2984                                     SelectionDAG &DAG) {
2985   EVT VT = SVOp->getValueType(0);
2986   unsigned NumElems = VT.getVectorNumElements();
2987   SmallVector<int, 8> MaskVec;
2988
2989   for (unsigned i = 0; i != NumElems; ++i) {
2990     int idx = SVOp->getMaskElt(i);
2991     if (idx < 0)
2992       MaskVec.push_back(idx);
2993     else if (idx < (int)NumElems)
2994       MaskVec.push_back(idx + NumElems);
2995     else
2996       MaskVec.push_back(idx - NumElems);
2997   }
2998   return DAG.getVectorShuffle(VT, SVOp->getDebugLoc(), SVOp->getOperand(1),
2999                               SVOp->getOperand(0), &MaskVec[0]);
3000 }
3001
3002 /// CommuteVectorShuffleMask - Change values in a shuffle permute mask assuming
3003 /// the two vector operands have swapped position.
3004 static void CommuteVectorShuffleMask(SmallVectorImpl<int> &Mask, EVT VT) {
3005   unsigned NumElems = VT.getVectorNumElements();
3006   for (unsigned i = 0; i != NumElems; ++i) {
3007     int idx = Mask[i];
3008     if (idx < 0)
3009       continue;
3010     else if (idx < (int)NumElems)
3011       Mask[i] = idx + NumElems;
3012     else
3013       Mask[i] = idx - NumElems;
3014   }
3015 }
3016
3017 /// ShouldXformToMOVHLPS - Return true if the node should be transformed to
3018 /// match movhlps. The lower half elements should come from upper half of
3019 /// V1 (and in order), and the upper half elements should come from the upper
3020 /// half of V2 (and in order).
3021 static bool ShouldXformToMOVHLPS(ShuffleVectorSDNode *Op) {
3022   if (Op->getValueType(0).getVectorNumElements() != 4)
3023     return false;
3024   for (unsigned i = 0, e = 2; i != e; ++i)
3025     if (!isUndefOrEqual(Op->getMaskElt(i), i+2))
3026       return false;
3027   for (unsigned i = 2; i != 4; ++i)
3028     if (!isUndefOrEqual(Op->getMaskElt(i), i+4))
3029       return false;
3030   return true;
3031 }
3032
3033 /// isScalarLoadToVector - Returns true if the node is a scalar load that
3034 /// is promoted to a vector. It also returns the LoadSDNode by reference if
3035 /// required.
3036 static bool isScalarLoadToVector(SDNode *N, LoadSDNode **LD = NULL) {
3037   if (N->getOpcode() != ISD::SCALAR_TO_VECTOR)
3038     return false;
3039   N = N->getOperand(0).getNode();
3040   if (!ISD::isNON_EXTLoad(N))
3041     return false;
3042   if (LD)
3043     *LD = cast<LoadSDNode>(N);
3044   return true;
3045 }
3046
3047 /// ShouldXformToMOVLP{S|D} - Return true if the node should be transformed to
3048 /// match movlp{s|d}. The lower half elements should come from lower half of
3049 /// V1 (and in order), and the upper half elements should come from the upper
3050 /// half of V2 (and in order). And since V1 will become the source of the
3051 /// MOVLP, it must be either a vector load or a scalar load to vector.
3052 static bool ShouldXformToMOVLP(SDNode *V1, SDNode *V2,
3053                                ShuffleVectorSDNode *Op) {
3054   if (!ISD::isNON_EXTLoad(V1) && !isScalarLoadToVector(V1))
3055     return false;
3056   // Is V2 is a vector load, don't do this transformation. We will try to use
3057   // load folding shufps op.
3058   if (ISD::isNON_EXTLoad(V2))
3059     return false;
3060
3061   unsigned NumElems = Op->getValueType(0).getVectorNumElements();
3062
3063   if (NumElems != 2 && NumElems != 4)
3064     return false;
3065   for (unsigned i = 0, e = NumElems/2; i != e; ++i)
3066     if (!isUndefOrEqual(Op->getMaskElt(i), i))
3067       return false;
3068   for (unsigned i = NumElems/2; i != NumElems; ++i)
3069     if (!isUndefOrEqual(Op->getMaskElt(i), i+NumElems))
3070       return false;
3071   return true;
3072 }
3073
3074 /// isSplatVector - Returns true if N is a BUILD_VECTOR node whose elements are
3075 /// all the same.
3076 static bool isSplatVector(SDNode *N) {
3077   if (N->getOpcode() != ISD::BUILD_VECTOR)
3078     return false;
3079
3080   SDValue SplatValue = N->getOperand(0);
3081   for (unsigned i = 1, e = N->getNumOperands(); i != e; ++i)
3082     if (N->getOperand(i) != SplatValue)
3083       return false;
3084   return true;
3085 }
3086
3087 /// isZeroShuffle - Returns true if N is a VECTOR_SHUFFLE that can be resolved
3088 /// to an zero vector.
3089 /// FIXME: move to dag combiner / method on ShuffleVectorSDNode
3090 static bool isZeroShuffle(ShuffleVectorSDNode *N) {
3091   SDValue V1 = N->getOperand(0);
3092   SDValue V2 = N->getOperand(1);
3093   unsigned NumElems = N->getValueType(0).getVectorNumElements();
3094   for (unsigned i = 0; i != NumElems; ++i) {
3095     int Idx = N->getMaskElt(i);
3096     if (Idx >= (int)NumElems) {
3097       unsigned Opc = V2.getOpcode();
3098       if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V2.getNode()))
3099         continue;
3100       if (Opc != ISD::BUILD_VECTOR ||
3101           !X86::isZeroNode(V2.getOperand(Idx-NumElems)))
3102         return false;
3103     } else if (Idx >= 0) {
3104       unsigned Opc = V1.getOpcode();
3105       if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V1.getNode()))
3106         continue;
3107       if (Opc != ISD::BUILD_VECTOR ||
3108           !X86::isZeroNode(V1.getOperand(Idx)))
3109         return false;
3110     }
3111   }
3112   return true;
3113 }
3114
3115 /// getZeroVector - Returns a vector of specified type with all zero elements.
3116 ///
3117 static SDValue getZeroVector(EVT VT, bool HasSSE2, SelectionDAG &DAG,
3118                              DebugLoc dl) {
3119   assert(VT.isVector() && "Expected a vector type");
3120
3121   // Always build zero vectors as <4 x i32> or <2 x i32> bitcasted to their dest
3122   // type.  This ensures they get CSE'd.
3123   SDValue Vec;
3124   if (VT.getSizeInBits() == 64) { // MMX
3125     SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
3126     Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v2i32, Cst, Cst);
3127   } else if (HasSSE2) {  // SSE2
3128     SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
3129     Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
3130   } else { // SSE1
3131     SDValue Cst = DAG.getTargetConstantFP(+0.0, MVT::f32);
3132     Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4f32, Cst, Cst, Cst, Cst);
3133   }
3134   return DAG.getNode(ISD::BIT_CONVERT, dl, VT, Vec);
3135 }
3136
3137 /// getOnesVector - Returns a vector of specified type with all bits set.
3138 ///
3139 static SDValue getOnesVector(EVT VT, SelectionDAG &DAG, DebugLoc dl) {
3140   assert(VT.isVector() && "Expected a vector type");
3141
3142   // Always build ones vectors as <4 x i32> or <2 x i32> bitcasted to their dest
3143   // type.  This ensures they get CSE'd.
3144   SDValue Cst = DAG.getTargetConstant(~0U, MVT::i32);
3145   SDValue Vec;
3146   if (VT.getSizeInBits() == 64)  // MMX
3147     Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v2i32, Cst, Cst);
3148   else                                              // SSE
3149     Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
3150   return DAG.getNode(ISD::BIT_CONVERT, dl, VT, Vec);
3151 }
3152
3153
3154 /// NormalizeMask - V2 is a splat, modify the mask (if needed) so all elements
3155 /// that point to V2 points to its first element.
3156 static SDValue NormalizeMask(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
3157   EVT VT = SVOp->getValueType(0);
3158   unsigned NumElems = VT.getVectorNumElements();
3159
3160   bool Changed = false;
3161   SmallVector<int, 8> MaskVec;
3162   SVOp->getMask(MaskVec);
3163
3164   for (unsigned i = 0; i != NumElems; ++i) {
3165     if (MaskVec[i] > (int)NumElems) {
3166       MaskVec[i] = NumElems;
3167       Changed = true;
3168     }
3169   }
3170   if (Changed)
3171     return DAG.getVectorShuffle(VT, SVOp->getDebugLoc(), SVOp->getOperand(0),
3172                                 SVOp->getOperand(1), &MaskVec[0]);
3173   return SDValue(SVOp, 0);
3174 }
3175
3176 /// getMOVLMask - Returns a vector_shuffle mask for an movs{s|d}, movd
3177 /// operation of specified width.
3178 static SDValue getMOVL(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
3179                        SDValue V2) {
3180   unsigned NumElems = VT.getVectorNumElements();
3181   SmallVector<int, 8> Mask;
3182   Mask.push_back(NumElems);
3183   for (unsigned i = 1; i != NumElems; ++i)
3184     Mask.push_back(i);
3185   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
3186 }
3187
3188 /// getUnpackl - Returns a vector_shuffle node for an unpackl operation.
3189 static SDValue getUnpackl(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
3190                           SDValue V2) {
3191   unsigned NumElems = VT.getVectorNumElements();
3192   SmallVector<int, 8> Mask;
3193   for (unsigned i = 0, e = NumElems/2; i != e; ++i) {
3194     Mask.push_back(i);
3195     Mask.push_back(i + NumElems);
3196   }
3197   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
3198 }
3199
3200 /// getUnpackhMask - Returns a vector_shuffle node for an unpackh operation.
3201 static SDValue getUnpackh(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
3202                           SDValue V2) {
3203   unsigned NumElems = VT.getVectorNumElements();
3204   unsigned Half = NumElems/2;
3205   SmallVector<int, 8> Mask;
3206   for (unsigned i = 0; i != Half; ++i) {
3207     Mask.push_back(i + Half);
3208     Mask.push_back(i + NumElems + Half);
3209   }
3210   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
3211 }
3212
3213 /// PromoteSplat - Promote a splat of v4f32, v8i16 or v16i8 to v4i32.
3214 static SDValue PromoteSplat(ShuffleVectorSDNode *SV, SelectionDAG &DAG,
3215                             bool HasSSE2) {
3216   if (SV->getValueType(0).getVectorNumElements() <= 4)
3217     return SDValue(SV, 0);
3218
3219   EVT PVT = MVT::v4f32;
3220   EVT VT = SV->getValueType(0);
3221   DebugLoc dl = SV->getDebugLoc();
3222   SDValue V1 = SV->getOperand(0);
3223   int NumElems = VT.getVectorNumElements();
3224   int EltNo = SV->getSplatIndex();
3225
3226   // unpack elements to the correct location
3227   while (NumElems > 4) {
3228     if (EltNo < NumElems/2) {
3229       V1 = getUnpackl(DAG, dl, VT, V1, V1);
3230     } else {
3231       V1 = getUnpackh(DAG, dl, VT, V1, V1);
3232       EltNo -= NumElems/2;
3233     }
3234     NumElems >>= 1;
3235   }
3236
3237   // Perform the splat.
3238   int SplatMask[4] = { EltNo, EltNo, EltNo, EltNo };
3239   V1 = DAG.getNode(ISD::BIT_CONVERT, dl, PVT, V1);
3240   V1 = DAG.getVectorShuffle(PVT, dl, V1, DAG.getUNDEF(PVT), &SplatMask[0]);
3241   return DAG.getNode(ISD::BIT_CONVERT, dl, VT, V1);
3242 }
3243
3244 /// getShuffleVectorZeroOrUndef - Return a vector_shuffle of the specified
3245 /// vector of zero or undef vector.  This produces a shuffle where the low
3246 /// element of V2 is swizzled into the zero/undef vector, landing at element
3247 /// Idx.  This produces a shuffle mask like 4,1,2,3 (idx=0) or  0,1,2,4 (idx=3).
3248 static SDValue getShuffleVectorZeroOrUndef(SDValue V2, unsigned Idx,
3249                                              bool isZero, bool HasSSE2,
3250                                              SelectionDAG &DAG) {
3251   EVT VT = V2.getValueType();
3252   SDValue V1 = isZero
3253     ? getZeroVector(VT, HasSSE2, DAG, V2.getDebugLoc()) : DAG.getUNDEF(VT);
3254   unsigned NumElems = VT.getVectorNumElements();
3255   SmallVector<int, 16> MaskVec;
3256   for (unsigned i = 0; i != NumElems; ++i)
3257     // If this is the insertion idx, put the low elt of V2 here.
3258     MaskVec.push_back(i == Idx ? NumElems : i);
3259   return DAG.getVectorShuffle(VT, V2.getDebugLoc(), V1, V2, &MaskVec[0]);
3260 }
3261
3262 /// getNumOfConsecutiveZeros - Return the number of elements in a result of
3263 /// a shuffle that is zero.
3264 static
3265 unsigned getNumOfConsecutiveZeros(ShuffleVectorSDNode *SVOp, int NumElems,
3266                                   bool Low, SelectionDAG &DAG) {
3267   unsigned NumZeros = 0;
3268   for (int i = 0; i < NumElems; ++i) {
3269     unsigned Index = Low ? i : NumElems-i-1;
3270     int Idx = SVOp->getMaskElt(Index);
3271     if (Idx < 0) {
3272       ++NumZeros;
3273       continue;
3274     }
3275     SDValue Elt = DAG.getShuffleScalarElt(SVOp, Index);
3276     if (Elt.getNode() && X86::isZeroNode(Elt))
3277       ++NumZeros;
3278     else
3279       break;
3280   }
3281   return NumZeros;
3282 }
3283
3284 /// isVectorShift - Returns true if the shuffle can be implemented as a
3285 /// logical left or right shift of a vector.
3286 /// FIXME: split into pslldqi, psrldqi, palignr variants.
3287 static bool isVectorShift(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
3288                           bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
3289   int NumElems = SVOp->getValueType(0).getVectorNumElements();
3290
3291   isLeft = true;
3292   unsigned NumZeros = getNumOfConsecutiveZeros(SVOp, NumElems, true, DAG);
3293   if (!NumZeros) {
3294     isLeft = false;
3295     NumZeros = getNumOfConsecutiveZeros(SVOp, NumElems, false, DAG);
3296     if (!NumZeros)
3297       return false;
3298   }
3299   bool SeenV1 = false;
3300   bool SeenV2 = false;
3301   for (int i = NumZeros; i < NumElems; ++i) {
3302     int Val = isLeft ? (i - NumZeros) : i;
3303     int Idx = SVOp->getMaskElt(isLeft ? i : (i - NumZeros));
3304     if (Idx < 0)
3305       continue;
3306     if (Idx < NumElems)
3307       SeenV1 = true;
3308     else {
3309       Idx -= NumElems;
3310       SeenV2 = true;
3311     }
3312     if (Idx != Val)
3313       return false;
3314   }
3315   if (SeenV1 && SeenV2)
3316     return false;
3317
3318   ShVal = SeenV1 ? SVOp->getOperand(0) : SVOp->getOperand(1);
3319   ShAmt = NumZeros;
3320   return true;
3321 }
3322
3323
3324 /// LowerBuildVectorv16i8 - Custom lower build_vector of v16i8.
3325 ///
3326 static SDValue LowerBuildVectorv16i8(SDValue Op, unsigned NonZeros,
3327                                        unsigned NumNonZero, unsigned NumZero,
3328                                        SelectionDAG &DAG, TargetLowering &TLI) {
3329   if (NumNonZero > 8)
3330     return SDValue();
3331
3332   DebugLoc dl = Op.getDebugLoc();
3333   SDValue V(0, 0);
3334   bool First = true;
3335   for (unsigned i = 0; i < 16; ++i) {
3336     bool ThisIsNonZero = (NonZeros & (1 << i)) != 0;
3337     if (ThisIsNonZero && First) {
3338       if (NumZero)
3339         V = getZeroVector(MVT::v8i16, true, DAG, dl);
3340       else
3341         V = DAG.getUNDEF(MVT::v8i16);
3342       First = false;
3343     }
3344
3345     if ((i & 1) != 0) {
3346       SDValue ThisElt(0, 0), LastElt(0, 0);
3347       bool LastIsNonZero = (NonZeros & (1 << (i-1))) != 0;
3348       if (LastIsNonZero) {
3349         LastElt = DAG.getNode(ISD::ZERO_EXTEND, dl,
3350                               MVT::i16, Op.getOperand(i-1));
3351       }
3352       if (ThisIsNonZero) {
3353         ThisElt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i16, Op.getOperand(i));
3354         ThisElt = DAG.getNode(ISD::SHL, dl, MVT::i16,
3355                               ThisElt, DAG.getConstant(8, MVT::i8));
3356         if (LastIsNonZero)
3357           ThisElt = DAG.getNode(ISD::OR, dl, MVT::i16, ThisElt, LastElt);
3358       } else
3359         ThisElt = LastElt;
3360
3361       if (ThisElt.getNode())
3362         V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, V, ThisElt,
3363                         DAG.getIntPtrConstant(i/2));
3364     }
3365   }
3366
3367   return DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v16i8, V);
3368 }
3369
3370 /// LowerBuildVectorv8i16 - Custom lower build_vector of v8i16.
3371 ///
3372 static SDValue LowerBuildVectorv8i16(SDValue Op, unsigned NonZeros,
3373                                        unsigned NumNonZero, unsigned NumZero,
3374                                        SelectionDAG &DAG, TargetLowering &TLI) {
3375   if (NumNonZero > 4)
3376     return SDValue();
3377
3378   DebugLoc dl = Op.getDebugLoc();
3379   SDValue V(0, 0);
3380   bool First = true;
3381   for (unsigned i = 0; i < 8; ++i) {
3382     bool isNonZero = (NonZeros & (1 << i)) != 0;
3383     if (isNonZero) {
3384       if (First) {
3385         if (NumZero)
3386           V = getZeroVector(MVT::v8i16, true, DAG, dl);
3387         else
3388           V = DAG.getUNDEF(MVT::v8i16);
3389         First = false;
3390       }
3391       V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl,
3392                       MVT::v8i16, V, Op.getOperand(i),
3393                       DAG.getIntPtrConstant(i));
3394     }
3395   }
3396
3397   return V;
3398 }
3399
3400 /// getVShift - Return a vector logical shift node.
3401 ///
3402 static SDValue getVShift(bool isLeft, EVT VT, SDValue SrcOp,
3403                          unsigned NumBits, SelectionDAG &DAG,
3404                          const TargetLowering &TLI, DebugLoc dl) {
3405   bool isMMX = VT.getSizeInBits() == 64;
3406   EVT ShVT = isMMX ? MVT::v1i64 : MVT::v2i64;
3407   unsigned Opc = isLeft ? X86ISD::VSHL : X86ISD::VSRL;
3408   SrcOp = DAG.getNode(ISD::BIT_CONVERT, dl, ShVT, SrcOp);
3409   return DAG.getNode(ISD::BIT_CONVERT, dl, VT,
3410                      DAG.getNode(Opc, dl, ShVT, SrcOp,
3411                              DAG.getConstant(NumBits, TLI.getShiftAmountTy())));
3412 }
3413
3414 SDValue
3415 X86TargetLowering::LowerAsSplatVectorLoad(SDValue SrcOp, EVT VT, DebugLoc dl,
3416                                           SelectionDAG &DAG) {
3417   
3418   // Check if the scalar load can be widened into a vector load. And if
3419   // the address is "base + cst" see if the cst can be "absorbed" into
3420   // the shuffle mask.
3421   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(SrcOp)) {
3422     SDValue Ptr = LD->getBasePtr();
3423     if (!ISD::isNormalLoad(LD) || LD->isVolatile())
3424       return SDValue();
3425     EVT PVT = LD->getValueType(0);
3426     if (PVT != MVT::i32 && PVT != MVT::f32)
3427       return SDValue();
3428
3429     int FI = -1;
3430     int64_t Offset = 0;
3431     if (FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr)) {
3432       FI = FINode->getIndex();
3433       Offset = 0;
3434     } else if (Ptr.getOpcode() == ISD::ADD &&
3435                isa<ConstantSDNode>(Ptr.getOperand(1)) &&
3436                isa<FrameIndexSDNode>(Ptr.getOperand(0))) {
3437       FI = cast<FrameIndexSDNode>(Ptr.getOperand(0))->getIndex();
3438       Offset = Ptr.getConstantOperandVal(1);
3439       Ptr = Ptr.getOperand(0);
3440     } else {
3441       return SDValue();
3442     }
3443
3444     SDValue Chain = LD->getChain();
3445     // Make sure the stack object alignment is at least 16.
3446     MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
3447     if (DAG.InferPtrAlignment(Ptr) < 16) {
3448       if (MFI->isFixedObjectIndex(FI)) {
3449         // Can't change the alignment. FIXME: It's possible to compute
3450         // the exact stack offset and reference FI + adjust offset instead.
3451         // If someone *really* cares about this. That's the way to implement it.
3452         return SDValue();
3453       } else {
3454         MFI->setObjectAlignment(FI, 16);
3455       }
3456     }
3457
3458     // (Offset % 16) must be multiple of 4. Then address is then
3459     // Ptr + (Offset & ~15).
3460     if (Offset < 0)
3461       return SDValue();
3462     if ((Offset % 16) & 3)
3463       return SDValue();
3464     int64_t StartOffset = Offset & ~15;
3465     if (StartOffset)
3466       Ptr = DAG.getNode(ISD::ADD, Ptr.getDebugLoc(), Ptr.getValueType(),
3467                         Ptr,DAG.getConstant(StartOffset, Ptr.getValueType()));
3468
3469     int EltNo = (Offset - StartOffset) >> 2;
3470     int Mask[4] = { EltNo, EltNo, EltNo, EltNo };
3471     EVT VT = (PVT == MVT::i32) ? MVT::v4i32 : MVT::v4f32;
3472     SDValue V1 = DAG.getLoad(VT, dl, Chain, Ptr,LD->getSrcValue(),0);
3473     // Canonicalize it to a v4i32 shuffle.
3474     V1 = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v4i32, V1);
3475     return DAG.getNode(ISD::BIT_CONVERT, dl, VT,
3476                        DAG.getVectorShuffle(MVT::v4i32, dl, V1,
3477                                             DAG.getUNDEF(MVT::v4i32), &Mask[0]));
3478   }
3479
3480   return SDValue();
3481 }
3482
3483 SDValue
3484 X86TargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG) {
3485   DebugLoc dl = Op.getDebugLoc();
3486   // All zero's are handled with pxor, all one's are handled with pcmpeqd.
3487   if (ISD::isBuildVectorAllZeros(Op.getNode())
3488       || ISD::isBuildVectorAllOnes(Op.getNode())) {
3489     // Canonicalize this to either <4 x i32> or <2 x i32> (SSE vs MMX) to
3490     // 1) ensure the zero vectors are CSE'd, and 2) ensure that i64 scalars are
3491     // eliminated on x86-32 hosts.
3492     if (Op.getValueType() == MVT::v4i32 || Op.getValueType() == MVT::v2i32)
3493       return Op;
3494
3495     if (ISD::isBuildVectorAllOnes(Op.getNode()))
3496       return getOnesVector(Op.getValueType(), DAG, dl);
3497     return getZeroVector(Op.getValueType(), Subtarget->hasSSE2(), DAG, dl);
3498   }
3499
3500   EVT VT = Op.getValueType();
3501   EVT ExtVT = VT.getVectorElementType();
3502   unsigned EVTBits = ExtVT.getSizeInBits();
3503
3504   unsigned NumElems = Op.getNumOperands();
3505   unsigned NumZero  = 0;
3506   unsigned NumNonZero = 0;
3507   unsigned NonZeros = 0;
3508   bool IsAllConstants = true;
3509   SmallSet<SDValue, 8> Values;
3510   for (unsigned i = 0; i < NumElems; ++i) {
3511     SDValue Elt = Op.getOperand(i);
3512     if (Elt.getOpcode() == ISD::UNDEF)
3513       continue;
3514     Values.insert(Elt);
3515     if (Elt.getOpcode() != ISD::Constant &&
3516         Elt.getOpcode() != ISD::ConstantFP)
3517       IsAllConstants = false;
3518     if (X86::isZeroNode(Elt))
3519       NumZero++;
3520     else {
3521       NonZeros |= (1 << i);
3522       NumNonZero++;
3523     }
3524   }
3525
3526   if (NumNonZero == 0) {
3527     // All undef vector. Return an UNDEF.  All zero vectors were handled above.
3528     return DAG.getUNDEF(VT);
3529   }
3530
3531   // Special case for single non-zero, non-undef, element.
3532   if (NumNonZero == 1) {
3533     unsigned Idx = CountTrailingZeros_32(NonZeros);
3534     SDValue Item = Op.getOperand(Idx);
3535
3536     // If this is an insertion of an i64 value on x86-32, and if the top bits of
3537     // the value are obviously zero, truncate the value to i32 and do the
3538     // insertion that way.  Only do this if the value is non-constant or if the
3539     // value is a constant being inserted into element 0.  It is cheaper to do
3540     // a constant pool load than it is to do a movd + shuffle.
3541     if (ExtVT == MVT::i64 && !Subtarget->is64Bit() &&
3542         (!IsAllConstants || Idx == 0)) {
3543       if (DAG.MaskedValueIsZero(Item, APInt::getBitsSet(64, 32, 64))) {
3544         // Handle MMX and SSE both.
3545         EVT VecVT = VT == MVT::v2i64 ? MVT::v4i32 : MVT::v2i32;
3546         unsigned VecElts = VT == MVT::v2i64 ? 4 : 2;
3547
3548         // Truncate the value (which may itself be a constant) to i32, and
3549         // convert it to a vector with movd (S2V+shuffle to zero extend).
3550         Item = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Item);
3551         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VecVT, Item);
3552         Item = getShuffleVectorZeroOrUndef(Item, 0, true,
3553                                            Subtarget->hasSSE2(), DAG);
3554
3555         // Now we have our 32-bit value zero extended in the low element of
3556         // a vector.  If Idx != 0, swizzle it into place.
3557         if (Idx != 0) {
3558           SmallVector<int, 4> Mask;
3559           Mask.push_back(Idx);
3560           for (unsigned i = 1; i != VecElts; ++i)
3561             Mask.push_back(i);
3562           Item = DAG.getVectorShuffle(VecVT, dl, Item,
3563                                       DAG.getUNDEF(Item.getValueType()),
3564                                       &Mask[0]);
3565         }
3566         return DAG.getNode(ISD::BIT_CONVERT, dl, Op.getValueType(), Item);
3567       }
3568     }
3569
3570     // If we have a constant or non-constant insertion into the low element of
3571     // a vector, we can do this with SCALAR_TO_VECTOR + shuffle of zero into
3572     // the rest of the elements.  This will be matched as movd/movq/movss/movsd
3573     // depending on what the source datatype is.
3574     if (Idx == 0) {
3575       if (NumZero == 0) {
3576         return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
3577       } else if (ExtVT == MVT::i32 || ExtVT == MVT::f32 || ExtVT == MVT::f64 ||
3578           (ExtVT == MVT::i64 && Subtarget->is64Bit())) {
3579         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
3580         // Turn it into a MOVL (i.e. movss, movsd, or movd) to a zero vector.
3581         return getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget->hasSSE2(),
3582                                            DAG);
3583       } else if (ExtVT == MVT::i16 || ExtVT == MVT::i8) {
3584         Item = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, Item);
3585         EVT MiddleVT = VT.getSizeInBits() == 64 ? MVT::v2i32 : MVT::v4i32;
3586         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MiddleVT, Item);
3587         Item = getShuffleVectorZeroOrUndef(Item, 0, true,
3588                                            Subtarget->hasSSE2(), DAG);
3589         return DAG.getNode(ISD::BIT_CONVERT, dl, VT, Item);
3590       }
3591     }
3592
3593     // Is it a vector logical left shift?
3594     if (NumElems == 2 && Idx == 1 &&
3595         X86::isZeroNode(Op.getOperand(0)) &&
3596         !X86::isZeroNode(Op.getOperand(1))) {
3597       unsigned NumBits = VT.getSizeInBits();
3598       return getVShift(true, VT,
3599                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
3600                                    VT, Op.getOperand(1)),
3601                        NumBits/2, DAG, *this, dl);
3602     }
3603
3604     if (IsAllConstants) // Otherwise, it's better to do a constpool load.
3605       return SDValue();
3606
3607     // Otherwise, if this is a vector with i32 or f32 elements, and the element
3608     // is a non-constant being inserted into an element other than the low one,
3609     // we can't use a constant pool load.  Instead, use SCALAR_TO_VECTOR (aka
3610     // movd/movss) to move this into the low element, then shuffle it into
3611     // place.
3612     if (EVTBits == 32) {
3613       Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
3614
3615       // Turn it into a shuffle of zero and zero-extended scalar to vector.
3616       Item = getShuffleVectorZeroOrUndef(Item, 0, NumZero > 0,
3617                                          Subtarget->hasSSE2(), DAG);
3618       SmallVector<int, 8> MaskVec;
3619       for (unsigned i = 0; i < NumElems; i++)
3620         MaskVec.push_back(i == Idx ? 0 : 1);
3621       return DAG.getVectorShuffle(VT, dl, Item, DAG.getUNDEF(VT), &MaskVec[0]);
3622     }
3623   }
3624
3625   // Splat is obviously ok. Let legalizer expand it to a shuffle.
3626   if (Values.size() == 1) {
3627     if (EVTBits == 32) {
3628       // Instead of a shuffle like this:
3629       // shuffle (scalar_to_vector (load (ptr + 4))), undef, <0, 0, 0, 0>
3630       // Check if it's possible to issue this instead.
3631       // shuffle (vload ptr)), undef, <1, 1, 1, 1>
3632       unsigned Idx = CountTrailingZeros_32(NonZeros);
3633       SDValue Item = Op.getOperand(Idx);
3634       if (Op.getNode()->isOnlyUserOf(Item.getNode()))
3635         return LowerAsSplatVectorLoad(Item, VT, dl, DAG);
3636     }
3637     return SDValue();
3638   }
3639
3640   // A vector full of immediates; various special cases are already
3641   // handled, so this is best done with a single constant-pool load.
3642   if (IsAllConstants)
3643     return SDValue();
3644
3645   // Let legalizer expand 2-wide build_vectors.
3646   if (EVTBits == 64) {
3647     if (NumNonZero == 1) {
3648       // One half is zero or undef.
3649       unsigned Idx = CountTrailingZeros_32(NonZeros);
3650       SDValue V2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT,
3651                                  Op.getOperand(Idx));
3652       return getShuffleVectorZeroOrUndef(V2, Idx, true,
3653                                          Subtarget->hasSSE2(), DAG);
3654     }
3655     return SDValue();
3656   }
3657
3658   // If element VT is < 32 bits, convert it to inserts into a zero vector.
3659   if (EVTBits == 8 && NumElems == 16) {
3660     SDValue V = LowerBuildVectorv16i8(Op, NonZeros,NumNonZero,NumZero, DAG,
3661                                         *this);
3662     if (V.getNode()) return V;
3663   }
3664
3665   if (EVTBits == 16 && NumElems == 8) {
3666     SDValue V = LowerBuildVectorv8i16(Op, NonZeros,NumNonZero,NumZero, DAG,
3667                                         *this);
3668     if (V.getNode()) return V;
3669   }
3670
3671   // If element VT is == 32 bits, turn it into a number of shuffles.
3672   SmallVector<SDValue, 8> V;
3673   V.resize(NumElems);
3674   if (NumElems == 4 && NumZero > 0) {
3675     for (unsigned i = 0; i < 4; ++i) {
3676       bool isZero = !(NonZeros & (1 << i));
3677       if (isZero)
3678         V[i] = getZeroVector(VT, Subtarget->hasSSE2(), DAG, dl);
3679       else
3680         V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
3681     }
3682
3683     for (unsigned i = 0; i < 2; ++i) {
3684       switch ((NonZeros & (0x3 << i*2)) >> (i*2)) {
3685         default: break;
3686         case 0:
3687           V[i] = V[i*2];  // Must be a zero vector.
3688           break;
3689         case 1:
3690           V[i] = getMOVL(DAG, dl, VT, V[i*2+1], V[i*2]);
3691           break;
3692         case 2:
3693           V[i] = getMOVL(DAG, dl, VT, V[i*2], V[i*2+1]);
3694           break;
3695         case 3:
3696           V[i] = getUnpackl(DAG, dl, VT, V[i*2], V[i*2+1]);
3697           break;
3698       }
3699     }
3700
3701     SmallVector<int, 8> MaskVec;
3702     bool Reverse = (NonZeros & 0x3) == 2;
3703     for (unsigned i = 0; i < 2; ++i)
3704       MaskVec.push_back(Reverse ? 1-i : i);
3705     Reverse = ((NonZeros & (0x3 << 2)) >> 2) == 2;
3706     for (unsigned i = 0; i < 2; ++i)
3707       MaskVec.push_back(Reverse ? 1-i+NumElems : i+NumElems);
3708     return DAG.getVectorShuffle(VT, dl, V[0], V[1], &MaskVec[0]);
3709   }
3710
3711   if (Values.size() > 2) {
3712     // If we have SSE 4.1, Expand into a number of inserts unless the number of
3713     // values to be inserted is equal to the number of elements, in which case
3714     // use the unpack code below in the hopes of matching the consecutive elts
3715     // load merge pattern for shuffles.
3716     // FIXME: We could probably just check that here directly.
3717     if (Values.size() < NumElems && VT.getSizeInBits() == 128 &&
3718         getSubtarget()->hasSSE41()) {
3719       V[0] = DAG.getUNDEF(VT);
3720       for (unsigned i = 0; i < NumElems; ++i)
3721         if (Op.getOperand(i).getOpcode() != ISD::UNDEF)
3722           V[0] = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, V[0],
3723                              Op.getOperand(i), DAG.getIntPtrConstant(i));
3724       return V[0];
3725     }
3726     // Expand into a number of unpckl*.
3727     // e.g. for v4f32
3728     //   Step 1: unpcklps 0, 2 ==> X: <?, ?, 2, 0>
3729     //         : unpcklps 1, 3 ==> Y: <?, ?, 3, 1>
3730     //   Step 2: unpcklps X, Y ==>    <3, 2, 1, 0>
3731     for (unsigned i = 0; i < NumElems; ++i)
3732       V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
3733     NumElems >>= 1;
3734     while (NumElems != 0) {
3735       for (unsigned i = 0; i < NumElems; ++i)
3736         V[i] = getUnpackl(DAG, dl, VT, V[i], V[i + NumElems]);
3737       NumElems >>= 1;
3738     }
3739     return V[0];
3740   }
3741
3742   return SDValue();
3743 }
3744
3745 SDValue
3746 X86TargetLowering::LowerCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
3747   // We support concatenate two MMX registers and place them in a MMX
3748   // register.  This is better than doing a stack convert.
3749   DebugLoc dl = Op.getDebugLoc();
3750   EVT ResVT = Op.getValueType();
3751   assert(Op.getNumOperands() == 2);
3752   assert(ResVT == MVT::v2i64 || ResVT == MVT::v4i32 ||
3753          ResVT == MVT::v8i16 || ResVT == MVT::v16i8);
3754   int Mask[2];
3755   SDValue InVec = DAG.getNode(ISD::BIT_CONVERT,dl, MVT::v1i64, Op.getOperand(0));
3756   SDValue VecOp = DAG.getNode(X86ISD::MOVQ2DQ, dl, MVT::v2i64, InVec);
3757   InVec = Op.getOperand(1);
3758   if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR) {
3759     unsigned NumElts = ResVT.getVectorNumElements();
3760     VecOp = DAG.getNode(ISD::BIT_CONVERT, dl, ResVT, VecOp);
3761     VecOp = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, ResVT, VecOp,
3762                        InVec.getOperand(0), DAG.getIntPtrConstant(NumElts/2+1));
3763   } else {
3764     InVec = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v1i64, InVec);
3765     SDValue VecOp2 = DAG.getNode(X86ISD::MOVQ2DQ, dl, MVT::v2i64, InVec);
3766     Mask[0] = 0; Mask[1] = 2;
3767     VecOp = DAG.getVectorShuffle(MVT::v2i64, dl, VecOp, VecOp2, Mask);
3768   }
3769   return DAG.getNode(ISD::BIT_CONVERT, dl, ResVT, VecOp);
3770 }
3771
3772 // v8i16 shuffles - Prefer shuffles in the following order:
3773 // 1. [all]   pshuflw, pshufhw, optional move
3774 // 2. [ssse3] 1 x pshufb
3775 // 3. [ssse3] 2 x pshufb + 1 x por
3776 // 4. [all]   mov + pshuflw + pshufhw + N x (pextrw + pinsrw)
3777 static
3778 SDValue LowerVECTOR_SHUFFLEv8i16(ShuffleVectorSDNode *SVOp,
3779                                  SelectionDAG &DAG, X86TargetLowering &TLI) {
3780   SDValue V1 = SVOp->getOperand(0);
3781   SDValue V2 = SVOp->getOperand(1);
3782   DebugLoc dl = SVOp->getDebugLoc();
3783   SmallVector<int, 8> MaskVals;
3784
3785   // Determine if more than 1 of the words in each of the low and high quadwords
3786   // of the result come from the same quadword of one of the two inputs.  Undef
3787   // mask values count as coming from any quadword, for better codegen.
3788   SmallVector<unsigned, 4> LoQuad(4);
3789   SmallVector<unsigned, 4> HiQuad(4);
3790   BitVector InputQuads(4);
3791   for (unsigned i = 0; i < 8; ++i) {
3792     SmallVectorImpl<unsigned> &Quad = i < 4 ? LoQuad : HiQuad;
3793     int EltIdx = SVOp->getMaskElt(i);
3794     MaskVals.push_back(EltIdx);
3795     if (EltIdx < 0) {
3796       ++Quad[0];
3797       ++Quad[1];
3798       ++Quad[2];
3799       ++Quad[3];
3800       continue;
3801     }
3802     ++Quad[EltIdx / 4];
3803     InputQuads.set(EltIdx / 4);
3804   }
3805
3806   int BestLoQuad = -1;
3807   unsigned MaxQuad = 1;
3808   for (unsigned i = 0; i < 4; ++i) {
3809     if (LoQuad[i] > MaxQuad) {
3810       BestLoQuad = i;
3811       MaxQuad = LoQuad[i];
3812     }
3813   }
3814
3815   int BestHiQuad = -1;
3816   MaxQuad = 1;
3817   for (unsigned i = 0; i < 4; ++i) {
3818     if (HiQuad[i] > MaxQuad) {
3819       BestHiQuad = i;
3820       MaxQuad = HiQuad[i];
3821     }
3822   }
3823
3824   // For SSSE3, If all 8 words of the result come from only 1 quadword of each
3825   // of the two input vectors, shuffle them into one input vector so only a
3826   // single pshufb instruction is necessary. If There are more than 2 input
3827   // quads, disable the next transformation since it does not help SSSE3.
3828   bool V1Used = InputQuads[0] || InputQuads[1];
3829   bool V2Used = InputQuads[2] || InputQuads[3];
3830   if (TLI.getSubtarget()->hasSSSE3()) {
3831     if (InputQuads.count() == 2 && V1Used && V2Used) {
3832       BestLoQuad = InputQuads.find_first();
3833       BestHiQuad = InputQuads.find_next(BestLoQuad);
3834     }
3835     if (InputQuads.count() > 2) {
3836       BestLoQuad = -1;
3837       BestHiQuad = -1;
3838     }
3839   }
3840
3841   // If BestLoQuad or BestHiQuad are set, shuffle the quads together and update
3842   // the shuffle mask.  If a quad is scored as -1, that means that it contains
3843   // words from all 4 input quadwords.
3844   SDValue NewV;
3845   if (BestLoQuad >= 0 || BestHiQuad >= 0) {
3846     SmallVector<int, 8> MaskV;
3847     MaskV.push_back(BestLoQuad < 0 ? 0 : BestLoQuad);
3848     MaskV.push_back(BestHiQuad < 0 ? 1 : BestHiQuad);
3849     NewV = DAG.getVectorShuffle(MVT::v2i64, dl,
3850                   DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v2i64, V1),
3851                   DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v2i64, V2), &MaskV[0]);
3852     NewV = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v8i16, NewV);
3853
3854     // Rewrite the MaskVals and assign NewV to V1 if NewV now contains all the
3855     // source words for the shuffle, to aid later transformations.
3856     bool AllWordsInNewV = true;
3857     bool InOrder[2] = { true, true };
3858     for (unsigned i = 0; i != 8; ++i) {
3859       int idx = MaskVals[i];
3860       if (idx != (int)i)
3861         InOrder[i/4] = false;
3862       if (idx < 0 || (idx/4) == BestLoQuad || (idx/4) == BestHiQuad)
3863         continue;
3864       AllWordsInNewV = false;
3865       break;
3866     }
3867
3868     bool pshuflw = AllWordsInNewV, pshufhw = AllWordsInNewV;
3869     if (AllWordsInNewV) {
3870       for (int i = 0; i != 8; ++i) {
3871         int idx = MaskVals[i];
3872         if (idx < 0)
3873           continue;
3874         idx = MaskVals[i] = (idx / 4) == BestLoQuad ? (idx & 3) : (idx & 3) + 4;
3875         if ((idx != i) && idx < 4)
3876           pshufhw = false;
3877         if ((idx != i) && idx > 3)
3878           pshuflw = false;
3879       }
3880       V1 = NewV;
3881       V2Used = false;
3882       BestLoQuad = 0;
3883       BestHiQuad = 1;
3884     }
3885
3886     // If we've eliminated the use of V2, and the new mask is a pshuflw or
3887     // pshufhw, that's as cheap as it gets.  Return the new shuffle.
3888     if ((pshufhw && InOrder[0]) || (pshuflw && InOrder[1])) {
3889       return DAG.getVectorShuffle(MVT::v8i16, dl, NewV,
3890                                   DAG.getUNDEF(MVT::v8i16), &MaskVals[0]);
3891     }
3892   }
3893
3894   // If we have SSSE3, and all words of the result are from 1 input vector,
3895   // case 2 is generated, otherwise case 3 is generated.  If no SSSE3
3896   // is present, fall back to case 4.
3897   if (TLI.getSubtarget()->hasSSSE3()) {
3898     SmallVector<SDValue,16> pshufbMask;
3899
3900     // If we have elements from both input vectors, set the high bit of the
3901     // shuffle mask element to zero out elements that come from V2 in the V1
3902     // mask, and elements that come from V1 in the V2 mask, so that the two
3903     // results can be OR'd together.
3904     bool TwoInputs = V1Used && V2Used;
3905     for (unsigned i = 0; i != 8; ++i) {
3906       int EltIdx = MaskVals[i] * 2;
3907       if (TwoInputs && (EltIdx >= 16)) {
3908         pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
3909         pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
3910         continue;
3911       }
3912       pshufbMask.push_back(DAG.getConstant(EltIdx,   MVT::i8));
3913       pshufbMask.push_back(DAG.getConstant(EltIdx+1, MVT::i8));
3914     }
3915     V1 = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v16i8, V1);
3916     V1 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V1,
3917                      DAG.getNode(ISD::BUILD_VECTOR, dl,
3918                                  MVT::v16i8, &pshufbMask[0], 16));
3919     if (!TwoInputs)
3920       return DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v8i16, V1);
3921
3922     // Calculate the shuffle mask for the second input, shuffle it, and
3923     // OR it with the first shuffled input.
3924     pshufbMask.clear();
3925     for (unsigned i = 0; i != 8; ++i) {
3926       int EltIdx = MaskVals[i] * 2;
3927       if (EltIdx < 16) {
3928         pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
3929         pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
3930         continue;
3931       }
3932       pshufbMask.push_back(DAG.getConstant(EltIdx - 16, MVT::i8));
3933       pshufbMask.push_back(DAG.getConstant(EltIdx - 15, MVT::i8));
3934     }
3935     V2 = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v16i8, V2);
3936     V2 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V2,
3937                      DAG.getNode(ISD::BUILD_VECTOR, dl,
3938                                  MVT::v16i8, &pshufbMask[0], 16));
3939     V1 = DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2);
3940     return DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v8i16, V1);
3941   }
3942
3943   // If BestLoQuad >= 0, generate a pshuflw to put the low elements in order,
3944   // and update MaskVals with new element order.
3945   BitVector InOrder(8);
3946   if (BestLoQuad >= 0) {
3947     SmallVector<int, 8> MaskV;
3948     for (int i = 0; i != 4; ++i) {
3949       int idx = MaskVals[i];
3950       if (idx < 0) {
3951         MaskV.push_back(-1);
3952         InOrder.set(i);
3953       } else if ((idx / 4) == BestLoQuad) {
3954         MaskV.push_back(idx & 3);
3955         InOrder.set(i);
3956       } else {
3957         MaskV.push_back(-1);
3958       }
3959     }
3960     for (unsigned i = 4; i != 8; ++i)
3961       MaskV.push_back(i);
3962     NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::v8i16),
3963                                 &MaskV[0]);
3964   }
3965
3966   // If BestHi >= 0, generate a pshufhw to put the high elements in order,
3967   // and update MaskVals with the new element order.
3968   if (BestHiQuad >= 0) {
3969     SmallVector<int, 8> MaskV;
3970     for (unsigned i = 0; i != 4; ++i)
3971       MaskV.push_back(i);
3972     for (unsigned i = 4; i != 8; ++i) {
3973       int idx = MaskVals[i];
3974       if (idx < 0) {
3975         MaskV.push_back(-1);
3976         InOrder.set(i);
3977       } else if ((idx / 4) == BestHiQuad) {
3978         MaskV.push_back((idx & 3) + 4);
3979         InOrder.set(i);
3980       } else {
3981         MaskV.push_back(-1);
3982       }
3983     }
3984     NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::v8i16),
3985                                 &MaskV[0]);
3986   }
3987
3988   // In case BestHi & BestLo were both -1, which means each quadword has a word
3989   // from each of the four input quadwords, calculate the InOrder bitvector now
3990   // before falling through to the insert/extract cleanup.
3991   if (BestLoQuad == -1 && BestHiQuad == -1) {
3992     NewV = V1;
3993     for (int i = 0; i != 8; ++i)
3994       if (MaskVals[i] < 0 || MaskVals[i] == i)
3995         InOrder.set(i);
3996   }
3997
3998   // The other elements are put in the right place using pextrw and pinsrw.
3999   for (unsigned i = 0; i != 8; ++i) {
4000     if (InOrder[i])
4001       continue;
4002     int EltIdx = MaskVals[i];
4003     if (EltIdx < 0)
4004       continue;
4005     SDValue ExtOp = (EltIdx < 8)
4006     ? DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V1,
4007                   DAG.getIntPtrConstant(EltIdx))
4008     : DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V2,
4009                   DAG.getIntPtrConstant(EltIdx - 8));
4010     NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, ExtOp,
4011                        DAG.getIntPtrConstant(i));
4012   }
4013   return NewV;
4014 }
4015
4016 // v16i8 shuffles - Prefer shuffles in the following order:
4017 // 1. [ssse3] 1 x pshufb
4018 // 2. [ssse3] 2 x pshufb + 1 x por
4019 // 3. [all]   v8i16 shuffle + N x pextrw + rotate + pinsrw
4020 static
4021 SDValue LowerVECTOR_SHUFFLEv16i8(ShuffleVectorSDNode *SVOp,
4022                                  SelectionDAG &DAG, X86TargetLowering &TLI) {
4023   SDValue V1 = SVOp->getOperand(0);
4024   SDValue V2 = SVOp->getOperand(1);
4025   DebugLoc dl = SVOp->getDebugLoc();
4026   SmallVector<int, 16> MaskVals;
4027   SVOp->getMask(MaskVals);
4028
4029   // If we have SSSE3, case 1 is generated when all result bytes come from
4030   // one of  the inputs.  Otherwise, case 2 is generated.  If no SSSE3 is
4031   // present, fall back to case 3.
4032   // FIXME: kill V2Only once shuffles are canonizalized by getNode.
4033   bool V1Only = true;
4034   bool V2Only = true;
4035   for (unsigned i = 0; i < 16; ++i) {
4036     int EltIdx = MaskVals[i];
4037     if (EltIdx < 0)
4038       continue;
4039     if (EltIdx < 16)
4040       V2Only = false;
4041     else
4042       V1Only = false;
4043   }
4044
4045   // If SSSE3, use 1 pshufb instruction per vector with elements in the result.
4046   if (TLI.getSubtarget()->hasSSSE3()) {
4047     SmallVector<SDValue,16> pshufbMask;
4048
4049     // If all result elements are from one input vector, then only translate
4050     // undef mask values to 0x80 (zero out result) in the pshufb mask.
4051     //
4052     // Otherwise, we have elements from both input vectors, and must zero out
4053     // elements that come from V2 in the first mask, and V1 in the second mask
4054     // so that we can OR them together.
4055     bool TwoInputs = !(V1Only || V2Only);
4056     for (unsigned i = 0; i != 16; ++i) {
4057       int EltIdx = MaskVals[i];
4058       if (EltIdx < 0 || (TwoInputs && EltIdx >= 16)) {
4059         pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
4060         continue;
4061       }
4062       pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8));
4063     }
4064     // If all the elements are from V2, assign it to V1 and return after
4065     // building the first pshufb.
4066     if (V2Only)
4067       V1 = V2;
4068     V1 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V1,
4069                      DAG.getNode(ISD::BUILD_VECTOR, dl,
4070                                  MVT::v16i8, &pshufbMask[0], 16));
4071     if (!TwoInputs)
4072       return V1;
4073
4074     // Calculate the shuffle mask for the second input, shuffle it, and
4075     // OR it with the first shuffled input.
4076     pshufbMask.clear();
4077     for (unsigned i = 0; i != 16; ++i) {
4078       int EltIdx = MaskVals[i];
4079       if (EltIdx < 16) {
4080         pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
4081         continue;
4082       }
4083       pshufbMask.push_back(DAG.getConstant(EltIdx - 16, MVT::i8));
4084     }
4085     V2 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V2,
4086                      DAG.getNode(ISD::BUILD_VECTOR, dl,
4087                                  MVT::v16i8, &pshufbMask[0], 16));
4088     return DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2);
4089   }
4090
4091   // No SSSE3 - Calculate in place words and then fix all out of place words
4092   // With 0-16 extracts & inserts.  Worst case is 16 bytes out of order from
4093   // the 16 different words that comprise the two doublequadword input vectors.
4094   V1 = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v8i16, V1);
4095   V2 = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v8i16, V2);
4096   SDValue NewV = V2Only ? V2 : V1;
4097   for (int i = 0; i != 8; ++i) {
4098     int Elt0 = MaskVals[i*2];
4099     int Elt1 = MaskVals[i*2+1];
4100
4101     // This word of the result is all undef, skip it.
4102     if (Elt0 < 0 && Elt1 < 0)
4103       continue;
4104
4105     // This word of the result is already in the correct place, skip it.
4106     if (V1Only && (Elt0 == i*2) && (Elt1 == i*2+1))
4107       continue;
4108     if (V2Only && (Elt0 == i*2+16) && (Elt1 == i*2+17))
4109       continue;
4110
4111     SDValue Elt0Src = Elt0 < 16 ? V1 : V2;
4112     SDValue Elt1Src = Elt1 < 16 ? V1 : V2;
4113     SDValue InsElt;
4114
4115     // If Elt0 and Elt1 are defined, are consecutive, and can be load
4116     // using a single extract together, load it and store it.
4117     if ((Elt0 >= 0) && ((Elt0 + 1) == Elt1) && ((Elt0 & 1) == 0)) {
4118       InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src,
4119                            DAG.getIntPtrConstant(Elt1 / 2));
4120       NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt,
4121                         DAG.getIntPtrConstant(i));
4122       continue;
4123     }
4124
4125     // If Elt1 is defined, extract it from the appropriate source.  If the
4126     // source byte is not also odd, shift the extracted word left 8 bits
4127     // otherwise clear the bottom 8 bits if we need to do an or.
4128     if (Elt1 >= 0) {
4129       InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src,
4130                            DAG.getIntPtrConstant(Elt1 / 2));
4131       if ((Elt1 & 1) == 0)
4132         InsElt = DAG.getNode(ISD::SHL, dl, MVT::i16, InsElt,
4133                              DAG.getConstant(8, TLI.getShiftAmountTy()));
4134       else if (Elt0 >= 0)
4135         InsElt = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt,
4136                              DAG.getConstant(0xFF00, MVT::i16));
4137     }
4138     // If Elt0 is defined, extract it from the appropriate source.  If the
4139     // source byte is not also even, shift the extracted word right 8 bits. If
4140     // Elt1 was also defined, OR the extracted values together before
4141     // inserting them in the result.
4142     if (Elt0 >= 0) {
4143       SDValue InsElt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16,
4144                                     Elt0Src, DAG.getIntPtrConstant(Elt0 / 2));
4145       if ((Elt0 & 1) != 0)
4146         InsElt0 = DAG.getNode(ISD::SRL, dl, MVT::i16, InsElt0,
4147                               DAG.getConstant(8, TLI.getShiftAmountTy()));
4148       else if (Elt1 >= 0)
4149         InsElt0 = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt0,
4150                              DAG.getConstant(0x00FF, MVT::i16));
4151       InsElt = Elt1 >= 0 ? DAG.getNode(ISD::OR, dl, MVT::i16, InsElt, InsElt0)
4152                          : InsElt0;
4153     }
4154     NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt,
4155                        DAG.getIntPtrConstant(i));
4156   }
4157   return DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v16i8, NewV);
4158 }
4159
4160 /// RewriteAsNarrowerShuffle - Try rewriting v8i16 and v16i8 shuffles as 4 wide
4161 /// ones, or rewriting v4i32 / v2f32 as 2 wide ones if possible. This can be
4162 /// done when every pair / quad of shuffle mask elements point to elements in
4163 /// the right sequence. e.g.
4164 /// vector_shuffle <>, <>, < 3, 4, | 10, 11, | 0, 1, | 14, 15>
4165 static
4166 SDValue RewriteAsNarrowerShuffle(ShuffleVectorSDNode *SVOp,
4167                                  SelectionDAG &DAG,
4168                                  TargetLowering &TLI, DebugLoc dl) {
4169   EVT VT = SVOp->getValueType(0);
4170   SDValue V1 = SVOp->getOperand(0);
4171   SDValue V2 = SVOp->getOperand(1);
4172   unsigned NumElems = VT.getVectorNumElements();
4173   unsigned NewWidth = (NumElems == 4) ? 2 : 4;
4174   EVT MaskVT = MVT::getIntVectorWithNumElements(NewWidth);
4175   EVT MaskEltVT = MaskVT.getVectorElementType();
4176   EVT NewVT = MaskVT;
4177   switch (VT.getSimpleVT().SimpleTy) {
4178   default: assert(false && "Unexpected!");
4179   case MVT::v4f32: NewVT = MVT::v2f64; break;
4180   case MVT::v4i32: NewVT = MVT::v2i64; break;
4181   case MVT::v8i16: NewVT = MVT::v4i32; break;
4182   case MVT::v16i8: NewVT = MVT::v4i32; break;
4183   }
4184
4185   if (NewWidth == 2) {
4186     if (VT.isInteger())
4187       NewVT = MVT::v2i64;
4188     else
4189       NewVT = MVT::v2f64;
4190   }
4191   int Scale = NumElems / NewWidth;
4192   SmallVector<int, 8> MaskVec;
4193   for (unsigned i = 0; i < NumElems; i += Scale) {
4194     int StartIdx = -1;
4195     for (int j = 0; j < Scale; ++j) {
4196       int EltIdx = SVOp->getMaskElt(i+j);
4197       if (EltIdx < 0)
4198         continue;
4199       if (StartIdx == -1)
4200         StartIdx = EltIdx - (EltIdx % Scale);
4201       if (EltIdx != StartIdx + j)
4202         return SDValue();
4203     }
4204     if (StartIdx == -1)
4205       MaskVec.push_back(-1);
4206     else
4207       MaskVec.push_back(StartIdx / Scale);
4208   }
4209
4210   V1 = DAG.getNode(ISD::BIT_CONVERT, dl, NewVT, V1);
4211   V2 = DAG.getNode(ISD::BIT_CONVERT, dl, NewVT, V2);
4212   return DAG.getVectorShuffle(NewVT, dl, V1, V2, &MaskVec[0]);
4213 }
4214
4215 /// getVZextMovL - Return a zero-extending vector move low node.
4216 ///
4217 static SDValue getVZextMovL(EVT VT, EVT OpVT,
4218                             SDValue SrcOp, SelectionDAG &DAG,
4219                             const X86Subtarget *Subtarget, DebugLoc dl) {
4220   if (VT == MVT::v2f64 || VT == MVT::v4f32) {
4221     LoadSDNode *LD = NULL;
4222     if (!isScalarLoadToVector(SrcOp.getNode(), &LD))
4223       LD = dyn_cast<LoadSDNode>(SrcOp);
4224     if (!LD) {
4225       // movssrr and movsdrr do not clear top bits. Try to use movd, movq
4226       // instead.
4227       MVT ExtVT = (OpVT == MVT::v2f64) ? MVT::i64 : MVT::i32;
4228       if ((ExtVT.SimpleTy != MVT::i64 || Subtarget->is64Bit()) &&
4229           SrcOp.getOpcode() == ISD::SCALAR_TO_VECTOR &&
4230           SrcOp.getOperand(0).getOpcode() == ISD::BIT_CONVERT &&
4231           SrcOp.getOperand(0).getOperand(0).getValueType() == ExtVT) {
4232         // PR2108
4233         OpVT = (OpVT == MVT::v2f64) ? MVT::v2i64 : MVT::v4i32;
4234         return DAG.getNode(ISD::BIT_CONVERT, dl, VT,
4235                            DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT,
4236                                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
4237                                                    OpVT,
4238                                                    SrcOp.getOperand(0)
4239                                                           .getOperand(0))));
4240       }
4241     }
4242   }
4243
4244   return DAG.getNode(ISD::BIT_CONVERT, dl, VT,
4245                      DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT,
4246                                  DAG.getNode(ISD::BIT_CONVERT, dl,
4247                                              OpVT, SrcOp)));
4248 }
4249
4250 /// LowerVECTOR_SHUFFLE_4wide - Handle all 4 wide cases with a number of
4251 /// shuffles.
4252 static SDValue
4253 LowerVECTOR_SHUFFLE_4wide(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
4254   SDValue V1 = SVOp->getOperand(0);
4255   SDValue V2 = SVOp->getOperand(1);
4256   DebugLoc dl = SVOp->getDebugLoc();
4257   EVT VT = SVOp->getValueType(0);
4258
4259   SmallVector<std::pair<int, int>, 8> Locs;
4260   Locs.resize(4);
4261   SmallVector<int, 8> Mask1(4U, -1);
4262   SmallVector<int, 8> PermMask;
4263   SVOp->getMask(PermMask);
4264
4265   unsigned NumHi = 0;
4266   unsigned NumLo = 0;
4267   for (unsigned i = 0; i != 4; ++i) {
4268     int Idx = PermMask[i];
4269     if (Idx < 0) {
4270       Locs[i] = std::make_pair(-1, -1);
4271     } else {
4272       assert(Idx < 8 && "Invalid VECTOR_SHUFFLE index!");
4273       if (Idx < 4) {
4274         Locs[i] = std::make_pair(0, NumLo);
4275         Mask1[NumLo] = Idx;
4276         NumLo++;
4277       } else {
4278         Locs[i] = std::make_pair(1, NumHi);
4279         if (2+NumHi < 4)
4280           Mask1[2+NumHi] = Idx;
4281         NumHi++;
4282       }
4283     }
4284   }
4285
4286   if (NumLo <= 2 && NumHi <= 2) {
4287     // If no more than two elements come from either vector. This can be
4288     // implemented with two shuffles. First shuffle gather the elements.
4289     // The second shuffle, which takes the first shuffle as both of its
4290     // vector operands, put the elements into the right order.
4291     V1 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
4292
4293     SmallVector<int, 8> Mask2(4U, -1);
4294
4295     for (unsigned i = 0; i != 4; ++i) {
4296       if (Locs[i].first == -1)
4297         continue;
4298       else {
4299         unsigned Idx = (i < 2) ? 0 : 4;
4300         Idx += Locs[i].first * 2 + Locs[i].second;
4301         Mask2[i] = Idx;
4302       }
4303     }
4304
4305     return DAG.getVectorShuffle(VT, dl, V1, V1, &Mask2[0]);
4306   } else if (NumLo == 3 || NumHi == 3) {
4307     // Otherwise, we must have three elements from one vector, call it X, and
4308     // one element from the other, call it Y.  First, use a shufps to build an
4309     // intermediate vector with the one element from Y and the element from X
4310     // that will be in the same half in the final destination (the indexes don't
4311     // matter). Then, use a shufps to build the final vector, taking the half
4312     // containing the element from Y from the intermediate, and the other half
4313     // from X.
4314     if (NumHi == 3) {
4315       // Normalize it so the 3 elements come from V1.
4316       CommuteVectorShuffleMask(PermMask, VT);
4317       std::swap(V1, V2);
4318     }
4319
4320     // Find the element from V2.
4321     unsigned HiIndex;
4322     for (HiIndex = 0; HiIndex < 3; ++HiIndex) {
4323       int Val = PermMask[HiIndex];
4324       if (Val < 0)
4325         continue;
4326       if (Val >= 4)
4327         break;
4328     }
4329
4330     Mask1[0] = PermMask[HiIndex];
4331     Mask1[1] = -1;
4332     Mask1[2] = PermMask[HiIndex^1];
4333     Mask1[3] = -1;
4334     V2 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
4335
4336     if (HiIndex >= 2) {
4337       Mask1[0] = PermMask[0];
4338       Mask1[1] = PermMask[1];
4339       Mask1[2] = HiIndex & 1 ? 6 : 4;
4340       Mask1[3] = HiIndex & 1 ? 4 : 6;
4341       return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
4342     } else {
4343       Mask1[0] = HiIndex & 1 ? 2 : 0;
4344       Mask1[1] = HiIndex & 1 ? 0 : 2;
4345       Mask1[2] = PermMask[2];
4346       Mask1[3] = PermMask[3];
4347       if (Mask1[2] >= 0)
4348         Mask1[2] += 4;
4349       if (Mask1[3] >= 0)
4350         Mask1[3] += 4;
4351       return DAG.getVectorShuffle(VT, dl, V2, V1, &Mask1[0]);
4352     }
4353   }
4354
4355   // Break it into (shuffle shuffle_hi, shuffle_lo).
4356   Locs.clear();
4357   SmallVector<int,8> LoMask(4U, -1);
4358   SmallVector<int,8> HiMask(4U, -1);
4359
4360   SmallVector<int,8> *MaskPtr = &LoMask;
4361   unsigned MaskIdx = 0;
4362   unsigned LoIdx = 0;
4363   unsigned HiIdx = 2;
4364   for (unsigned i = 0; i != 4; ++i) {
4365     if (i == 2) {
4366       MaskPtr = &HiMask;
4367       MaskIdx = 1;
4368       LoIdx = 0;
4369       HiIdx = 2;
4370     }
4371     int Idx = PermMask[i];
4372     if (Idx < 0) {
4373       Locs[i] = std::make_pair(-1, -1);
4374     } else if (Idx < 4) {
4375       Locs[i] = std::make_pair(MaskIdx, LoIdx);
4376       (*MaskPtr)[LoIdx] = Idx;
4377       LoIdx++;
4378     } else {
4379       Locs[i] = std::make_pair(MaskIdx, HiIdx);
4380       (*MaskPtr)[HiIdx] = Idx;
4381       HiIdx++;
4382     }
4383   }
4384
4385   SDValue LoShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &LoMask[0]);
4386   SDValue HiShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &HiMask[0]);
4387   SmallVector<int, 8> MaskOps;
4388   for (unsigned i = 0; i != 4; ++i) {
4389     if (Locs[i].first == -1) {
4390       MaskOps.push_back(-1);
4391     } else {
4392       unsigned Idx = Locs[i].first * 4 + Locs[i].second;
4393       MaskOps.push_back(Idx);
4394     }
4395   }
4396   return DAG.getVectorShuffle(VT, dl, LoShuffle, HiShuffle, &MaskOps[0]);
4397 }
4398
4399 SDValue
4400 X86TargetLowering::LowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG) {
4401   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
4402   SDValue V1 = Op.getOperand(0);
4403   SDValue V2 = Op.getOperand(1);
4404   EVT VT = Op.getValueType();
4405   DebugLoc dl = Op.getDebugLoc();
4406   unsigned NumElems = VT.getVectorNumElements();
4407   bool isMMX = VT.getSizeInBits() == 64;
4408   bool V1IsUndef = V1.getOpcode() == ISD::UNDEF;
4409   bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
4410   bool V1IsSplat = false;
4411   bool V2IsSplat = false;
4412
4413   if (isZeroShuffle(SVOp))
4414     return getZeroVector(VT, Subtarget->hasSSE2(), DAG, dl);
4415
4416   // Promote splats to v4f32.
4417   if (SVOp->isSplat()) {
4418     if (isMMX || NumElems < 4)
4419       return Op;
4420     return PromoteSplat(SVOp, DAG, Subtarget->hasSSE2());
4421   }
4422
4423   // If the shuffle can be profitably rewritten as a narrower shuffle, then
4424   // do it!
4425   if (VT == MVT::v8i16 || VT == MVT::v16i8) {
4426     SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG, *this, dl);
4427     if (NewOp.getNode())
4428       return DAG.getNode(ISD::BIT_CONVERT, dl, VT,
4429                          LowerVECTOR_SHUFFLE(NewOp, DAG));
4430   } else if ((VT == MVT::v4i32 || (VT == MVT::v4f32 && Subtarget->hasSSE2()))) {
4431     // FIXME: Figure out a cleaner way to do this.
4432     // Try to make use of movq to zero out the top part.
4433     if (ISD::isBuildVectorAllZeros(V2.getNode())) {
4434       SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG, *this, dl);
4435       if (NewOp.getNode()) {
4436         if (isCommutedMOVL(cast<ShuffleVectorSDNode>(NewOp), true, false))
4437           return getVZextMovL(VT, NewOp.getValueType(), NewOp.getOperand(0),
4438                               DAG, Subtarget, dl);
4439       }
4440     } else if (ISD::isBuildVectorAllZeros(V1.getNode())) {
4441       SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG, *this, dl);
4442       if (NewOp.getNode() && X86::isMOVLMask(cast<ShuffleVectorSDNode>(NewOp)))
4443         return getVZextMovL(VT, NewOp.getValueType(), NewOp.getOperand(1),
4444                             DAG, Subtarget, dl);
4445     }
4446   }
4447
4448   if (X86::isPSHUFDMask(SVOp))
4449     return Op;
4450
4451   // Check if this can be converted into a logical shift.
4452   bool isLeft = false;
4453   unsigned ShAmt = 0;
4454   SDValue ShVal;
4455   bool isShift = getSubtarget()->hasSSE2() &&
4456     isVectorShift(SVOp, DAG, isLeft, ShVal, ShAmt);
4457   if (isShift && ShVal.hasOneUse()) {
4458     // If the shifted value has multiple uses, it may be cheaper to use
4459     // v_set0 + movlhps or movhlps, etc.
4460     EVT EltVT = VT.getVectorElementType();
4461     ShAmt *= EltVT.getSizeInBits();
4462     return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
4463   }
4464
4465   if (X86::isMOVLMask(SVOp)) {
4466     if (V1IsUndef)
4467       return V2;
4468     if (ISD::isBuildVectorAllZeros(V1.getNode()))
4469       return getVZextMovL(VT, VT, V2, DAG, Subtarget, dl);
4470     if (!isMMX)
4471       return Op;
4472   }
4473
4474   // FIXME: fold these into legal mask.
4475   if (!isMMX && (X86::isMOVSHDUPMask(SVOp) ||
4476                  X86::isMOVSLDUPMask(SVOp) ||
4477                  X86::isMOVHLPSMask(SVOp) ||
4478                  X86::isMOVLHPSMask(SVOp) ||
4479                  X86::isMOVLPMask(SVOp)))
4480     return Op;
4481
4482   if (ShouldXformToMOVHLPS(SVOp) ||
4483       ShouldXformToMOVLP(V1.getNode(), V2.getNode(), SVOp))
4484     return CommuteVectorShuffle(SVOp, DAG);
4485
4486   if (isShift) {
4487     // No better options. Use a vshl / vsrl.
4488     EVT EltVT = VT.getVectorElementType();
4489     ShAmt *= EltVT.getSizeInBits();
4490     return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
4491   }
4492
4493   bool Commuted = false;
4494   // FIXME: This should also accept a bitcast of a splat?  Be careful, not
4495   // 1,1,1,1 -> v8i16 though.
4496   V1IsSplat = isSplatVector(V1.getNode());
4497   V2IsSplat = isSplatVector(V2.getNode());
4498
4499   // Canonicalize the splat or undef, if present, to be on the RHS.
4500   if ((V1IsSplat || V1IsUndef) && !(V2IsSplat || V2IsUndef)) {
4501     Op = CommuteVectorShuffle(SVOp, DAG);
4502     SVOp = cast<ShuffleVectorSDNode>(Op);
4503     V1 = SVOp->getOperand(0);
4504     V2 = SVOp->getOperand(1);
4505     std::swap(V1IsSplat, V2IsSplat);
4506     std::swap(V1IsUndef, V2IsUndef);
4507     Commuted = true;
4508   }
4509
4510   if (isCommutedMOVL(SVOp, V2IsSplat, V2IsUndef)) {
4511     // Shuffling low element of v1 into undef, just return v1.
4512     if (V2IsUndef)
4513       return V1;
4514     // If V2 is a splat, the mask may be malformed such as <4,3,3,3>, which
4515     // the instruction selector will not match, so get a canonical MOVL with
4516     // swapped operands to undo the commute.
4517     return getMOVL(DAG, dl, VT, V2, V1);
4518   }
4519
4520   if (X86::isUNPCKL_v_undef_Mask(SVOp) ||
4521       X86::isUNPCKH_v_undef_Mask(SVOp) ||
4522       X86::isUNPCKLMask(SVOp) ||
4523       X86::isUNPCKHMask(SVOp))
4524     return Op;
4525
4526   if (V2IsSplat) {
4527     // Normalize mask so all entries that point to V2 points to its first
4528     // element then try to match unpck{h|l} again. If match, return a
4529     // new vector_shuffle with the corrected mask.
4530     SDValue NewMask = NormalizeMask(SVOp, DAG);
4531     ShuffleVectorSDNode *NSVOp = cast<ShuffleVectorSDNode>(NewMask);
4532     if (NSVOp != SVOp) {
4533       if (X86::isUNPCKLMask(NSVOp, true)) {
4534         return NewMask;
4535       } else if (X86::isUNPCKHMask(NSVOp, true)) {
4536         return NewMask;
4537       }
4538     }
4539   }
4540
4541   if (Commuted) {
4542     // Commute is back and try unpck* again.
4543     // FIXME: this seems wrong.
4544     SDValue NewOp = CommuteVectorShuffle(SVOp, DAG);
4545     ShuffleVectorSDNode *NewSVOp = cast<ShuffleVectorSDNode>(NewOp);
4546     if (X86::isUNPCKL_v_undef_Mask(NewSVOp) ||
4547         X86::isUNPCKH_v_undef_Mask(NewSVOp) ||
4548         X86::isUNPCKLMask(NewSVOp) ||
4549         X86::isUNPCKHMask(NewSVOp))
4550       return NewOp;
4551   }
4552
4553   // FIXME: for mmx, bitcast v2i32 to v4i16 for shuffle.
4554
4555   // Normalize the node to match x86 shuffle ops if needed
4556   if (!isMMX && V2.getOpcode() != ISD::UNDEF && isCommutedSHUFP(SVOp))
4557     return CommuteVectorShuffle(SVOp, DAG);
4558
4559   // Check for legal shuffle and return?
4560   SmallVector<int, 16> PermMask;
4561   SVOp->getMask(PermMask);
4562   if (isShuffleMaskLegal(PermMask, VT))
4563     return Op;
4564
4565   // Handle v8i16 specifically since SSE can do byte extraction and insertion.
4566   if (VT == MVT::v8i16) {
4567     SDValue NewOp = LowerVECTOR_SHUFFLEv8i16(SVOp, DAG, *this);
4568     if (NewOp.getNode())
4569       return NewOp;
4570   }
4571
4572   if (VT == MVT::v16i8) {
4573     SDValue NewOp = LowerVECTOR_SHUFFLEv16i8(SVOp, DAG, *this);
4574     if (NewOp.getNode())
4575       return NewOp;
4576   }
4577
4578   // Handle all 4 wide cases with a number of shuffles except for MMX.
4579   if (NumElems == 4 && !isMMX)
4580     return LowerVECTOR_SHUFFLE_4wide(SVOp, DAG);
4581
4582   return SDValue();
4583 }
4584
4585 SDValue
4586 X86TargetLowering::LowerEXTRACT_VECTOR_ELT_SSE4(SDValue Op,
4587                                                 SelectionDAG &DAG) {
4588   EVT VT = Op.getValueType();
4589   DebugLoc dl = Op.getDebugLoc();
4590   if (VT.getSizeInBits() == 8) {
4591     SDValue Extract = DAG.getNode(X86ISD::PEXTRB, dl, MVT::i32,
4592                                     Op.getOperand(0), Op.getOperand(1));
4593     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
4594                                     DAG.getValueType(VT));
4595     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
4596   } else if (VT.getSizeInBits() == 16) {
4597     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
4598     // If Idx is 0, it's cheaper to do a move instead of a pextrw.
4599     if (Idx == 0)
4600       return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
4601                          DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
4602                                      DAG.getNode(ISD::BIT_CONVERT, dl,
4603                                                  MVT::v4i32,
4604                                                  Op.getOperand(0)),
4605                                      Op.getOperand(1)));
4606     SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, MVT::i32,
4607                                     Op.getOperand(0), Op.getOperand(1));
4608     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
4609                                     DAG.getValueType(VT));
4610     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
4611   } else if (VT == MVT::f32) {
4612     // EXTRACTPS outputs to a GPR32 register which will require a movd to copy
4613     // the result back to FR32 register. It's only worth matching if the
4614     // result has a single use which is a store or a bitcast to i32.  And in
4615     // the case of a store, it's not worth it if the index is a constant 0,
4616     // because a MOVSSmr can be used instead, which is smaller and faster.
4617     if (!Op.hasOneUse())
4618       return SDValue();
4619     SDNode *User = *Op.getNode()->use_begin();
4620     if ((User->getOpcode() != ISD::STORE ||
4621          (isa<ConstantSDNode>(Op.getOperand(1)) &&
4622           cast<ConstantSDNode>(Op.getOperand(1))->isNullValue())) &&
4623         (User->getOpcode() != ISD::BIT_CONVERT ||
4624          User->getValueType(0) != MVT::i32))
4625       return SDValue();
4626     SDValue Extract = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
4627                                   DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v4i32,
4628                                               Op.getOperand(0)),
4629                                               Op.getOperand(1));
4630     return DAG.getNode(ISD::BIT_CONVERT, dl, MVT::f32, Extract);
4631   } else if (VT == MVT::i32) {
4632     // ExtractPS works with constant index.
4633     if (isa<ConstantSDNode>(Op.getOperand(1)))
4634       return Op;
4635   }
4636   return SDValue();
4637 }
4638
4639
4640 SDValue
4641 X86TargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) {
4642   if (!isa<ConstantSDNode>(Op.getOperand(1)))
4643     return SDValue();
4644
4645   if (Subtarget->hasSSE41()) {
4646     SDValue Res = LowerEXTRACT_VECTOR_ELT_SSE4(Op, DAG);
4647     if (Res.getNode())
4648       return Res;
4649   }
4650
4651   EVT VT = Op.getValueType();
4652   DebugLoc dl = Op.getDebugLoc();
4653   // TODO: handle v16i8.
4654   if (VT.getSizeInBits() == 16) {
4655     SDValue Vec = Op.getOperand(0);
4656     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
4657     if (Idx == 0)
4658       return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
4659                          DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
4660                                      DAG.getNode(ISD::BIT_CONVERT, dl,
4661                                                  MVT::v4i32, Vec),
4662                                      Op.getOperand(1)));
4663     // Transform it so it match pextrw which produces a 32-bit result.
4664     EVT EltVT = MVT::i32;
4665     SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, EltVT,
4666                                     Op.getOperand(0), Op.getOperand(1));
4667     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, EltVT, Extract,
4668                                     DAG.getValueType(VT));
4669     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
4670   } else if (VT.getSizeInBits() == 32) {
4671     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
4672     if (Idx == 0)
4673       return Op;
4674
4675     // SHUFPS the element to the lowest double word, then movss.
4676     int Mask[4] = { Idx, -1, -1, -1 };
4677     EVT VVT = Op.getOperand(0).getValueType();
4678     SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
4679                                        DAG.getUNDEF(VVT), Mask);
4680     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
4681                        DAG.getIntPtrConstant(0));
4682   } else if (VT.getSizeInBits() == 64) {
4683     // FIXME: .td only matches this for <2 x f64>, not <2 x i64> on 32b
4684     // FIXME: seems like this should be unnecessary if mov{h,l}pd were taught
4685     //        to match extract_elt for f64.
4686     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
4687     if (Idx == 0)
4688       return Op;
4689
4690     // UNPCKHPD the element to the lowest double word, then movsd.
4691     // Note if the lower 64 bits of the result of the UNPCKHPD is then stored
4692     // to a f64mem, the whole operation is folded into a single MOVHPDmr.
4693     int Mask[2] = { 1, -1 };
4694     EVT VVT = Op.getOperand(0).getValueType();
4695     SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
4696                                        DAG.getUNDEF(VVT), Mask);
4697     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
4698                        DAG.getIntPtrConstant(0));
4699   }
4700
4701   return SDValue();
4702 }
4703
4704 SDValue
4705 X86TargetLowering::LowerINSERT_VECTOR_ELT_SSE4(SDValue Op, SelectionDAG &DAG){
4706   EVT VT = Op.getValueType();
4707   EVT EltVT = VT.getVectorElementType();
4708   DebugLoc dl = Op.getDebugLoc();
4709
4710   SDValue N0 = Op.getOperand(0);
4711   SDValue N1 = Op.getOperand(1);
4712   SDValue N2 = Op.getOperand(2);
4713
4714   if ((EltVT.getSizeInBits() == 8 || EltVT.getSizeInBits() == 16) &&
4715       isa<ConstantSDNode>(N2)) {
4716     unsigned Opc = (EltVT.getSizeInBits() == 8) ? X86ISD::PINSRB
4717                                                 : X86ISD::PINSRW;
4718     // Transform it so it match pinsr{b,w} which expects a GR32 as its second
4719     // argument.
4720     if (N1.getValueType() != MVT::i32)
4721       N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
4722     if (N2.getValueType() != MVT::i32)
4723       N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue());
4724     return DAG.getNode(Opc, dl, VT, N0, N1, N2);
4725   } else if (EltVT == MVT::f32 && isa<ConstantSDNode>(N2)) {
4726     // Bits [7:6] of the constant are the source select.  This will always be
4727     //  zero here.  The DAG Combiner may combine an extract_elt index into these
4728     //  bits.  For example (insert (extract, 3), 2) could be matched by putting
4729     //  the '3' into bits [7:6] of X86ISD::INSERTPS.
4730     // Bits [5:4] of the constant are the destination select.  This is the
4731     //  value of the incoming immediate.
4732     // Bits [3:0] of the constant are the zero mask.  The DAG Combiner may
4733     //   combine either bitwise AND or insert of float 0.0 to set these bits.
4734     N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue() << 4);
4735     // Create this as a scalar to vector..
4736     N1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4f32, N1);
4737     return DAG.getNode(X86ISD::INSERTPS, dl, VT, N0, N1, N2);
4738   } else if (EltVT == MVT::i32 && isa<ConstantSDNode>(N2)) {
4739     // PINSR* works with constant index.
4740     return Op;
4741   }
4742   return SDValue();
4743 }
4744
4745 SDValue
4746 X86TargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) {
4747   EVT VT = Op.getValueType();
4748   EVT EltVT = VT.getVectorElementType();
4749
4750   if (Subtarget->hasSSE41())
4751     return LowerINSERT_VECTOR_ELT_SSE4(Op, DAG);
4752
4753   if (EltVT == MVT::i8)
4754     return SDValue();
4755
4756   DebugLoc dl = Op.getDebugLoc();
4757   SDValue N0 = Op.getOperand(0);
4758   SDValue N1 = Op.getOperand(1);
4759   SDValue N2 = Op.getOperand(2);
4760
4761   if (EltVT.getSizeInBits() == 16 && isa<ConstantSDNode>(N2)) {
4762     // Transform it so it match pinsrw which expects a 16-bit value in a GR32
4763     // as its second argument.
4764     if (N1.getValueType() != MVT::i32)
4765       N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
4766     if (N2.getValueType() != MVT::i32)
4767       N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue());
4768     return DAG.getNode(X86ISD::PINSRW, dl, VT, N0, N1, N2);
4769   }
4770   return SDValue();
4771 }
4772
4773 SDValue
4774 X86TargetLowering::LowerSCALAR_TO_VECTOR(SDValue Op, SelectionDAG &DAG) {
4775   DebugLoc dl = Op.getDebugLoc();
4776   if (Op.getValueType() == MVT::v2f32)
4777     return DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v2f32,
4778                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i32,
4779                                    DAG.getNode(ISD::BIT_CONVERT, dl, MVT::i32,
4780                                                Op.getOperand(0))));
4781
4782   if (Op.getValueType() == MVT::v1i64 && Op.getOperand(0).getValueType() == MVT::i64)
4783     return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v1i64, Op.getOperand(0));
4784
4785   SDValue AnyExt = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, Op.getOperand(0));
4786   EVT VT = MVT::v2i32;
4787   switch (Op.getValueType().getSimpleVT().SimpleTy) {
4788   default: break;
4789   case MVT::v16i8:
4790   case MVT::v8i16:
4791     VT = MVT::v4i32;
4792     break;
4793   }
4794   return DAG.getNode(ISD::BIT_CONVERT, dl, Op.getValueType(),
4795                      DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, AnyExt));
4796 }
4797
4798 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
4799 // their target countpart wrapped in the X86ISD::Wrapper node. Suppose N is
4800 // one of the above mentioned nodes. It has to be wrapped because otherwise
4801 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
4802 // be used to form addressing mode. These wrapped nodes will be selected
4803 // into MOV32ri.
4804 SDValue
4805 X86TargetLowering::LowerConstantPool(SDValue Op, SelectionDAG &DAG) {
4806   ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
4807
4808   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
4809   // global base reg.
4810   unsigned char OpFlag = 0;
4811   unsigned WrapperKind = X86ISD::Wrapper;
4812   CodeModel::Model M = getTargetMachine().getCodeModel();
4813
4814   if (Subtarget->isPICStyleRIPRel() &&
4815       (M == CodeModel::Small || M == CodeModel::Kernel))
4816     WrapperKind = X86ISD::WrapperRIP;
4817   else if (Subtarget->isPICStyleGOT())
4818     OpFlag = X86II::MO_GOTOFF;
4819   else if (Subtarget->isPICStyleStubPIC())
4820     OpFlag = X86II::MO_PIC_BASE_OFFSET;
4821
4822   SDValue Result = DAG.getTargetConstantPool(CP->getConstVal(), getPointerTy(),
4823                                              CP->getAlignment(),
4824                                              CP->getOffset(), OpFlag);
4825   DebugLoc DL = CP->getDebugLoc();
4826   Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
4827   // With PIC, the address is actually $g + Offset.
4828   if (OpFlag) {
4829     Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
4830                          DAG.getNode(X86ISD::GlobalBaseReg,
4831                                      DebugLoc::getUnknownLoc(), getPointerTy()),
4832                          Result);
4833   }
4834
4835   return Result;
4836 }
4837
4838 SDValue X86TargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) {
4839   JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
4840
4841   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
4842   // global base reg.
4843   unsigned char OpFlag = 0;
4844   unsigned WrapperKind = X86ISD::Wrapper;
4845   CodeModel::Model M = getTargetMachine().getCodeModel();
4846
4847   if (Subtarget->isPICStyleRIPRel() &&
4848       (M == CodeModel::Small || M == CodeModel::Kernel))
4849     WrapperKind = X86ISD::WrapperRIP;
4850   else if (Subtarget->isPICStyleGOT())
4851     OpFlag = X86II::MO_GOTOFF;
4852   else if (Subtarget->isPICStyleStubPIC())
4853     OpFlag = X86II::MO_PIC_BASE_OFFSET;
4854
4855   SDValue Result = DAG.getTargetJumpTable(JT->getIndex(), getPointerTy(),
4856                                           OpFlag);
4857   DebugLoc DL = JT->getDebugLoc();
4858   Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
4859
4860   // With PIC, the address is actually $g + Offset.
4861   if (OpFlag) {
4862     Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
4863                          DAG.getNode(X86ISD::GlobalBaseReg,
4864                                      DebugLoc::getUnknownLoc(), getPointerTy()),
4865                          Result);
4866   }
4867
4868   return Result;
4869 }
4870
4871 SDValue
4872 X86TargetLowering::LowerExternalSymbol(SDValue Op, SelectionDAG &DAG) {
4873   const char *Sym = cast<ExternalSymbolSDNode>(Op)->getSymbol();
4874
4875   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
4876   // global base reg.
4877   unsigned char OpFlag = 0;
4878   unsigned WrapperKind = X86ISD::Wrapper;
4879   CodeModel::Model M = getTargetMachine().getCodeModel();
4880
4881   if (Subtarget->isPICStyleRIPRel() &&
4882       (M == CodeModel::Small || M == CodeModel::Kernel))
4883     WrapperKind = X86ISD::WrapperRIP;
4884   else if (Subtarget->isPICStyleGOT())
4885     OpFlag = X86II::MO_GOTOFF;
4886   else if (Subtarget->isPICStyleStubPIC())
4887     OpFlag = X86II::MO_PIC_BASE_OFFSET;
4888
4889   SDValue Result = DAG.getTargetExternalSymbol(Sym, getPointerTy(), OpFlag);
4890
4891   DebugLoc DL = Op.getDebugLoc();
4892   Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
4893
4894
4895   // With PIC, the address is actually $g + Offset.
4896   if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
4897       !Subtarget->is64Bit()) {
4898     Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
4899                          DAG.getNode(X86ISD::GlobalBaseReg,
4900                                      DebugLoc::getUnknownLoc(),
4901                                      getPointerTy()),
4902                          Result);
4903   }
4904
4905   return Result;
4906 }
4907
4908 SDValue
4909 X86TargetLowering::LowerBlockAddress(SDValue Op, SelectionDAG &DAG) {
4910   // Create the TargetBlockAddressAddress node.
4911   unsigned char OpFlags =
4912     Subtarget->ClassifyBlockAddressReference();
4913   CodeModel::Model M = getTargetMachine().getCodeModel();
4914   BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
4915   DebugLoc dl = Op.getDebugLoc();
4916   SDValue Result = DAG.getBlockAddress(BA, getPointerTy(),
4917                                        /*isTarget=*/true, OpFlags);
4918
4919   if (Subtarget->isPICStyleRIPRel() &&
4920       (M == CodeModel::Small || M == CodeModel::Kernel))
4921     Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
4922   else
4923     Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
4924
4925   // With PIC, the address is actually $g + Offset.
4926   if (isGlobalRelativeToPICBase(OpFlags)) {
4927     Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
4928                          DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
4929                          Result);
4930   }
4931
4932   return Result;
4933 }
4934
4935 SDValue
4936 X86TargetLowering::LowerGlobalAddress(const GlobalValue *GV, DebugLoc dl,
4937                                       int64_t Offset,
4938                                       SelectionDAG &DAG) const {
4939   // Create the TargetGlobalAddress node, folding in the constant
4940   // offset if it is legal.
4941   unsigned char OpFlags =
4942     Subtarget->ClassifyGlobalReference(GV, getTargetMachine());
4943   CodeModel::Model M = getTargetMachine().getCodeModel();
4944   SDValue Result;
4945   if (OpFlags == X86II::MO_NO_FLAG &&
4946       X86::isOffsetSuitableForCodeModel(Offset, M)) {
4947     // A direct static reference to a global.
4948     Result = DAG.getTargetGlobalAddress(GV, getPointerTy(), Offset);
4949     Offset = 0;
4950   } else {
4951     Result = DAG.getTargetGlobalAddress(GV, getPointerTy(), 0, OpFlags);
4952   }
4953
4954   if (Subtarget->isPICStyleRIPRel() &&
4955       (M == CodeModel::Small || M == CodeModel::Kernel))
4956     Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
4957   else
4958     Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
4959
4960   // With PIC, the address is actually $g + Offset.
4961   if (isGlobalRelativeToPICBase(OpFlags)) {
4962     Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
4963                          DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
4964                          Result);
4965   }
4966
4967   // For globals that require a load from a stub to get the address, emit the
4968   // load.
4969   if (isGlobalStubReference(OpFlags))
4970     Result = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Result,
4971                          PseudoSourceValue::getGOT(), 0);
4972
4973   // If there was a non-zero offset that we didn't fold, create an explicit
4974   // addition for it.
4975   if (Offset != 0)
4976     Result = DAG.getNode(ISD::ADD, dl, getPointerTy(), Result,
4977                          DAG.getConstant(Offset, getPointerTy()));
4978
4979   return Result;
4980 }
4981
4982 SDValue
4983 X86TargetLowering::LowerGlobalAddress(SDValue Op, SelectionDAG &DAG) {
4984   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
4985   int64_t Offset = cast<GlobalAddressSDNode>(Op)->getOffset();
4986   return LowerGlobalAddress(GV, Op.getDebugLoc(), Offset, DAG);
4987 }
4988
4989 static SDValue
4990 GetTLSADDR(SelectionDAG &DAG, SDValue Chain, GlobalAddressSDNode *GA,
4991            SDValue *InFlag, const EVT PtrVT, unsigned ReturnReg,
4992            unsigned char OperandFlags) {
4993   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
4994   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Flag);
4995   DebugLoc dl = GA->getDebugLoc();
4996   SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(),
4997                                            GA->getValueType(0),
4998                                            GA->getOffset(),
4999                                            OperandFlags);
5000   if (InFlag) {
5001     SDValue Ops[] = { Chain,  TGA, *InFlag };
5002     Chain = DAG.getNode(X86ISD::TLSADDR, dl, NodeTys, Ops, 3);
5003   } else {
5004     SDValue Ops[]  = { Chain, TGA };
5005     Chain = DAG.getNode(X86ISD::TLSADDR, dl, NodeTys, Ops, 2);
5006   }
5007
5008   // TLSADDR will be codegen'ed as call. Inform MFI that function has calls.
5009   MFI->setHasCalls(true);
5010
5011   SDValue Flag = Chain.getValue(1);
5012   return DAG.getCopyFromReg(Chain, dl, ReturnReg, PtrVT, Flag);
5013 }
5014
5015 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 32 bit
5016 static SDValue
5017 LowerToTLSGeneralDynamicModel32(GlobalAddressSDNode *GA, SelectionDAG &DAG,
5018                                 const EVT PtrVT) {
5019   SDValue InFlag;
5020   DebugLoc dl = GA->getDebugLoc();  // ? function entry point might be better
5021   SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
5022                                      DAG.getNode(X86ISD::GlobalBaseReg,
5023                                                  DebugLoc::getUnknownLoc(),
5024                                                  PtrVT), InFlag);
5025   InFlag = Chain.getValue(1);
5026
5027   return GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX, X86II::MO_TLSGD);
5028 }
5029
5030 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 64 bit
5031 static SDValue
5032 LowerToTLSGeneralDynamicModel64(GlobalAddressSDNode *GA, SelectionDAG &DAG,
5033                                 const EVT PtrVT) {
5034   return GetTLSADDR(DAG, DAG.getEntryNode(), GA, NULL, PtrVT,
5035                     X86::RAX, X86II::MO_TLSGD);
5036 }
5037
5038 // Lower ISD::GlobalTLSAddress using the "initial exec" (for no-pic) or
5039 // "local exec" model.
5040 static SDValue LowerToTLSExecModel(GlobalAddressSDNode *GA, SelectionDAG &DAG,
5041                                    const EVT PtrVT, TLSModel::Model model,
5042                                    bool is64Bit) {
5043   DebugLoc dl = GA->getDebugLoc();
5044   // Get the Thread Pointer
5045   SDValue Base = DAG.getNode(X86ISD::SegmentBaseAddress,
5046                              DebugLoc::getUnknownLoc(), PtrVT,
5047                              DAG.getRegister(is64Bit? X86::FS : X86::GS,
5048                                              MVT::i32));
5049
5050   SDValue ThreadPointer = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Base,
5051                                       NULL, 0);
5052
5053   unsigned char OperandFlags = 0;
5054   // Most TLS accesses are not RIP relative, even on x86-64.  One exception is
5055   // initialexec.
5056   unsigned WrapperKind = X86ISD::Wrapper;
5057   if (model == TLSModel::LocalExec) {
5058     OperandFlags = is64Bit ? X86II::MO_TPOFF : X86II::MO_NTPOFF;
5059   } else if (is64Bit) {
5060     assert(model == TLSModel::InitialExec);
5061     OperandFlags = X86II::MO_GOTTPOFF;
5062     WrapperKind = X86ISD::WrapperRIP;
5063   } else {
5064     assert(model == TLSModel::InitialExec);
5065     OperandFlags = X86II::MO_INDNTPOFF;
5066   }
5067
5068   // emit "addl x@ntpoff,%eax" (local exec) or "addl x@indntpoff,%eax" (initial
5069   // exec)
5070   SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), GA->getValueType(0),
5071                                            GA->getOffset(), OperandFlags);
5072   SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
5073
5074   if (model == TLSModel::InitialExec)
5075     Offset = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Offset,
5076                          PseudoSourceValue::getGOT(), 0);
5077
5078   // The address of the thread local variable is the add of the thread
5079   // pointer with the offset of the variable.
5080   return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
5081 }
5082
5083 SDValue
5084 X86TargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) {
5085   // TODO: implement the "local dynamic" model
5086   // TODO: implement the "initial exec"model for pic executables
5087   assert(Subtarget->isTargetELF() &&
5088          "TLS not implemented for non-ELF targets");
5089   GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
5090   const GlobalValue *GV = GA->getGlobal();
5091
5092   // If GV is an alias then use the aliasee for determining
5093   // thread-localness.
5094   if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(GV))
5095     GV = GA->resolveAliasedGlobal(false);
5096
5097   TLSModel::Model model = getTLSModel(GV,
5098                                       getTargetMachine().getRelocationModel());
5099
5100   switch (model) {
5101   case TLSModel::GeneralDynamic:
5102   case TLSModel::LocalDynamic: // not implemented
5103     if (Subtarget->is64Bit())
5104       return LowerToTLSGeneralDynamicModel64(GA, DAG, getPointerTy());
5105     return LowerToTLSGeneralDynamicModel32(GA, DAG, getPointerTy());
5106
5107   case TLSModel::InitialExec:
5108   case TLSModel::LocalExec:
5109     return LowerToTLSExecModel(GA, DAG, getPointerTy(), model,
5110                                Subtarget->is64Bit());
5111   }
5112
5113   llvm_unreachable("Unreachable");
5114   return SDValue();
5115 }
5116
5117
5118 /// LowerShift - Lower SRA_PARTS and friends, which return two i32 values and
5119 /// take a 2 x i32 value to shift plus a shift amount.
5120 SDValue X86TargetLowering::LowerShift(SDValue Op, SelectionDAG &DAG) {
5121   assert(Op.getNumOperands() == 3 && "Not a double-shift!");
5122   EVT VT = Op.getValueType();
5123   unsigned VTBits = VT.getSizeInBits();
5124   DebugLoc dl = Op.getDebugLoc();
5125   bool isSRA = Op.getOpcode() == ISD::SRA_PARTS;
5126   SDValue ShOpLo = Op.getOperand(0);
5127   SDValue ShOpHi = Op.getOperand(1);
5128   SDValue ShAmt  = Op.getOperand(2);
5129   SDValue Tmp1 = isSRA ? DAG.getNode(ISD::SRA, dl, VT, ShOpHi,
5130                                      DAG.getConstant(VTBits - 1, MVT::i8))
5131                        : DAG.getConstant(0, VT);
5132
5133   SDValue Tmp2, Tmp3;
5134   if (Op.getOpcode() == ISD::SHL_PARTS) {
5135     Tmp2 = DAG.getNode(X86ISD::SHLD, dl, VT, ShOpHi, ShOpLo, ShAmt);
5136     Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ShAmt);
5137   } else {
5138     Tmp2 = DAG.getNode(X86ISD::SHRD, dl, VT, ShOpLo, ShOpHi, ShAmt);
5139     Tmp3 = DAG.getNode(isSRA ? ISD::SRA : ISD::SRL, dl, VT, ShOpHi, ShAmt);
5140   }
5141
5142   SDValue AndNode = DAG.getNode(ISD::AND, dl, MVT::i8, ShAmt,
5143                                 DAG.getConstant(VTBits, MVT::i8));
5144   SDValue Cond = DAG.getNode(X86ISD::CMP, dl, VT,
5145                              AndNode, DAG.getConstant(0, MVT::i8));
5146
5147   SDValue Hi, Lo;
5148   SDValue CC = DAG.getConstant(X86::COND_NE, MVT::i8);
5149   SDValue Ops0[4] = { Tmp2, Tmp3, CC, Cond };
5150   SDValue Ops1[4] = { Tmp3, Tmp1, CC, Cond };
5151
5152   if (Op.getOpcode() == ISD::SHL_PARTS) {
5153     Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0, 4);
5154     Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1, 4);
5155   } else {
5156     Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0, 4);
5157     Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1, 4);
5158   }
5159
5160   SDValue Ops[2] = { Lo, Hi };
5161   return DAG.getMergeValues(Ops, 2, dl);
5162 }
5163
5164 SDValue X86TargetLowering::LowerSINT_TO_FP(SDValue Op, SelectionDAG &DAG) {
5165   EVT SrcVT = Op.getOperand(0).getValueType();
5166
5167   if (SrcVT.isVector()) {
5168     if (SrcVT == MVT::v2i32 && Op.getValueType() == MVT::v2f64) {
5169       return Op;
5170     }
5171     return SDValue();
5172   }
5173
5174   assert(SrcVT.getSimpleVT() <= MVT::i64 && SrcVT.getSimpleVT() >= MVT::i16 &&
5175          "Unknown SINT_TO_FP to lower!");
5176
5177   // These are really Legal; return the operand so the caller accepts it as
5178   // Legal.
5179   if (SrcVT == MVT::i32 && isScalarFPTypeInSSEReg(Op.getValueType()))
5180     return Op;
5181   if (SrcVT == MVT::i64 && isScalarFPTypeInSSEReg(Op.getValueType()) &&
5182       Subtarget->is64Bit()) {
5183     return Op;
5184   }
5185
5186   DebugLoc dl = Op.getDebugLoc();
5187   unsigned Size = SrcVT.getSizeInBits()/8;
5188   MachineFunction &MF = DAG.getMachineFunction();
5189   int SSFI = MF.getFrameInfo()->CreateStackObject(Size, Size, false);
5190   SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
5191   SDValue Chain = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
5192                                StackSlot,
5193                                PseudoSourceValue::getFixedStack(SSFI), 0);
5194   return BuildFILD(Op, SrcVT, Chain, StackSlot, DAG);
5195 }
5196
5197 SDValue X86TargetLowering::BuildFILD(SDValue Op, EVT SrcVT, SDValue Chain,
5198                                      SDValue StackSlot,
5199                                      SelectionDAG &DAG) {
5200   // Build the FILD
5201   DebugLoc dl = Op.getDebugLoc();
5202   SDVTList Tys;
5203   bool useSSE = isScalarFPTypeInSSEReg(Op.getValueType());
5204   if (useSSE)
5205     Tys = DAG.getVTList(MVT::f64, MVT::Other, MVT::Flag);
5206   else
5207     Tys = DAG.getVTList(Op.getValueType(), MVT::Other);
5208   SDValue Ops[] = { Chain, StackSlot, DAG.getValueType(SrcVT) };
5209   SDValue Result = DAG.getNode(useSSE ? X86ISD::FILD_FLAG : X86ISD::FILD, dl,
5210                                Tys, Ops, array_lengthof(Ops));
5211
5212   if (useSSE) {
5213     Chain = Result.getValue(1);
5214     SDValue InFlag = Result.getValue(2);
5215
5216     // FIXME: Currently the FST is flagged to the FILD_FLAG. This
5217     // shouldn't be necessary except that RFP cannot be live across
5218     // multiple blocks. When stackifier is fixed, they can be uncoupled.
5219     MachineFunction &MF = DAG.getMachineFunction();
5220     int SSFI = MF.getFrameInfo()->CreateStackObject(8, 8, false);
5221     SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
5222     Tys = DAG.getVTList(MVT::Other);
5223     SDValue Ops[] = {
5224       Chain, Result, StackSlot, DAG.getValueType(Op.getValueType()), InFlag
5225     };
5226     Chain = DAG.getNode(X86ISD::FST, dl, Tys, Ops, array_lengthof(Ops));
5227     Result = DAG.getLoad(Op.getValueType(), dl, Chain, StackSlot,
5228                          PseudoSourceValue::getFixedStack(SSFI), 0);
5229   }
5230
5231   return Result;
5232 }
5233
5234 // LowerUINT_TO_FP_i64 - 64-bit unsigned integer to double expansion.
5235 SDValue X86TargetLowering::LowerUINT_TO_FP_i64(SDValue Op, SelectionDAG &DAG) {
5236   // This algorithm is not obvious. Here it is in C code, more or less:
5237   /*
5238     double uint64_to_double( uint32_t hi, uint32_t lo ) {
5239       static const __m128i exp = { 0x4330000045300000ULL, 0 };
5240       static const __m128d bias = { 0x1.0p84, 0x1.0p52 };
5241
5242       // Copy ints to xmm registers.
5243       __m128i xh = _mm_cvtsi32_si128( hi );
5244       __m128i xl = _mm_cvtsi32_si128( lo );
5245
5246       // Combine into low half of a single xmm register.
5247       __m128i x = _mm_unpacklo_epi32( xh, xl );
5248       __m128d d;
5249       double sd;
5250
5251       // Merge in appropriate exponents to give the integer bits the right
5252       // magnitude.
5253       x = _mm_unpacklo_epi32( x, exp );
5254
5255       // Subtract away the biases to deal with the IEEE-754 double precision
5256       // implicit 1.
5257       d = _mm_sub_pd( (__m128d) x, bias );
5258
5259       // All conversions up to here are exact. The correctly rounded result is
5260       // calculated using the current rounding mode using the following
5261       // horizontal add.
5262       d = _mm_add_sd( d, _mm_unpackhi_pd( d, d ) );
5263       _mm_store_sd( &sd, d );   // Because we are returning doubles in XMM, this
5264                                 // store doesn't really need to be here (except
5265                                 // maybe to zero the other double)
5266       return sd;
5267     }
5268   */
5269
5270   DebugLoc dl = Op.getDebugLoc();
5271   LLVMContext *Context = DAG.getContext();
5272
5273   // Build some magic constants.
5274   std::vector<Constant*> CV0;
5275   CV0.push_back(ConstantInt::get(*Context, APInt(32, 0x45300000)));
5276   CV0.push_back(ConstantInt::get(*Context, APInt(32, 0x43300000)));
5277   CV0.push_back(ConstantInt::get(*Context, APInt(32, 0)));
5278   CV0.push_back(ConstantInt::get(*Context, APInt(32, 0)));
5279   Constant *C0 = ConstantVector::get(CV0);
5280   SDValue CPIdx0 = DAG.getConstantPool(C0, getPointerTy(), 16);
5281
5282   std::vector<Constant*> CV1;
5283   CV1.push_back(
5284     ConstantFP::get(*Context, APFloat(APInt(64, 0x4530000000000000ULL))));
5285   CV1.push_back(
5286     ConstantFP::get(*Context, APFloat(APInt(64, 0x4330000000000000ULL))));
5287   Constant *C1 = ConstantVector::get(CV1);
5288   SDValue CPIdx1 = DAG.getConstantPool(C1, getPointerTy(), 16);
5289
5290   SDValue XR1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
5291                             DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
5292                                         Op.getOperand(0),
5293                                         DAG.getIntPtrConstant(1)));
5294   SDValue XR2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
5295                             DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
5296                                         Op.getOperand(0),
5297                                         DAG.getIntPtrConstant(0)));
5298   SDValue Unpck1 = getUnpackl(DAG, dl, MVT::v4i32, XR1, XR2);
5299   SDValue CLod0 = DAG.getLoad(MVT::v4i32, dl, DAG.getEntryNode(), CPIdx0,
5300                               PseudoSourceValue::getConstantPool(), 0,
5301                               false, 16);
5302   SDValue Unpck2 = getUnpackl(DAG, dl, MVT::v4i32, Unpck1, CLod0);
5303   SDValue XR2F = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v2f64, Unpck2);
5304   SDValue CLod1 = DAG.getLoad(MVT::v2f64, dl, CLod0.getValue(1), CPIdx1,
5305                               PseudoSourceValue::getConstantPool(), 0,
5306                               false, 16);
5307   SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, XR2F, CLod1);
5308
5309   // Add the halves; easiest way is to swap them into another reg first.
5310   int ShufMask[2] = { 1, -1 };
5311   SDValue Shuf = DAG.getVectorShuffle(MVT::v2f64, dl, Sub,
5312                                       DAG.getUNDEF(MVT::v2f64), ShufMask);
5313   SDValue Add = DAG.getNode(ISD::FADD, dl, MVT::v2f64, Shuf, Sub);
5314   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Add,
5315                      DAG.getIntPtrConstant(0));
5316 }
5317
5318 // LowerUINT_TO_FP_i32 - 32-bit unsigned integer to float expansion.
5319 SDValue X86TargetLowering::LowerUINT_TO_FP_i32(SDValue Op, SelectionDAG &DAG) {
5320   DebugLoc dl = Op.getDebugLoc();
5321   // FP constant to bias correct the final result.
5322   SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL),
5323                                    MVT::f64);
5324
5325   // Load the 32-bit value into an XMM register.
5326   SDValue Load = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
5327                              DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
5328                                          Op.getOperand(0),
5329                                          DAG.getIntPtrConstant(0)));
5330
5331   Load = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
5332                      DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v2f64, Load),
5333                      DAG.getIntPtrConstant(0));
5334
5335   // Or the load with the bias.
5336   SDValue Or = DAG.getNode(ISD::OR, dl, MVT::v2i64,
5337                            DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v2i64,
5338                                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
5339                                                    MVT::v2f64, Load)),
5340                            DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v2i64,
5341                                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
5342                                                    MVT::v2f64, Bias)));
5343   Or = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
5344                    DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v2f64, Or),
5345                    DAG.getIntPtrConstant(0));
5346
5347   // Subtract the bias.
5348   SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::f64, Or, Bias);
5349
5350   // Handle final rounding.
5351   EVT DestVT = Op.getValueType();
5352
5353   if (DestVT.bitsLT(MVT::f64)) {
5354     return DAG.getNode(ISD::FP_ROUND, dl, DestVT, Sub,
5355                        DAG.getIntPtrConstant(0));
5356   } else if (DestVT.bitsGT(MVT::f64)) {
5357     return DAG.getNode(ISD::FP_EXTEND, dl, DestVT, Sub);
5358   }
5359
5360   // Handle final rounding.
5361   return Sub;
5362 }
5363
5364 SDValue X86TargetLowering::LowerUINT_TO_FP(SDValue Op, SelectionDAG &DAG) {
5365   SDValue N0 = Op.getOperand(0);
5366   DebugLoc dl = Op.getDebugLoc();
5367
5368   // Now not UINT_TO_FP is legal (it's marked custom), dag combiner won't
5369   // optimize it to a SINT_TO_FP when the sign bit is known zero. Perform
5370   // the optimization here.
5371   if (DAG.SignBitIsZero(N0))
5372     return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(), N0);
5373
5374   EVT SrcVT = N0.getValueType();
5375   if (SrcVT == MVT::i64) {
5376     // We only handle SSE2 f64 target here; caller can expand the rest.
5377     if (Op.getValueType() != MVT::f64 || !X86ScalarSSEf64)
5378       return SDValue();
5379
5380     return LowerUINT_TO_FP_i64(Op, DAG);
5381   } else if (SrcVT == MVT::i32 && X86ScalarSSEf64) {
5382     return LowerUINT_TO_FP_i32(Op, DAG);
5383   }
5384
5385   assert(SrcVT == MVT::i32 && "Unknown UINT_TO_FP to lower!");
5386
5387   // Make a 64-bit buffer, and use it to build an FILD.
5388   SDValue StackSlot = DAG.CreateStackTemporary(MVT::i64);
5389   SDValue WordOff = DAG.getConstant(4, getPointerTy());
5390   SDValue OffsetSlot = DAG.getNode(ISD::ADD, dl,
5391                                    getPointerTy(), StackSlot, WordOff);
5392   SDValue Store1 = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
5393                                 StackSlot, NULL, 0);
5394   SDValue Store2 = DAG.getStore(Store1, dl, DAG.getConstant(0, MVT::i32),
5395                                 OffsetSlot, NULL, 0);
5396   return BuildFILD(Op, MVT::i64, Store2, StackSlot, DAG);
5397 }
5398
5399 std::pair<SDValue,SDValue> X86TargetLowering::
5400 FP_TO_INTHelper(SDValue Op, SelectionDAG &DAG, bool IsSigned) {
5401   DebugLoc dl = Op.getDebugLoc();
5402
5403   EVT DstTy = Op.getValueType();
5404
5405   if (!IsSigned) {
5406     assert(DstTy == MVT::i32 && "Unexpected FP_TO_UINT");
5407     DstTy = MVT::i64;
5408   }
5409
5410   assert(DstTy.getSimpleVT() <= MVT::i64 &&
5411          DstTy.getSimpleVT() >= MVT::i16 &&
5412          "Unknown FP_TO_SINT to lower!");
5413
5414   // These are really Legal.
5415   if (DstTy == MVT::i32 &&
5416       isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
5417     return std::make_pair(SDValue(), SDValue());
5418   if (Subtarget->is64Bit() &&
5419       DstTy == MVT::i64 &&
5420       isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
5421     return std::make_pair(SDValue(), SDValue());
5422
5423   // We lower FP->sint64 into FISTP64, followed by a load, all to a temporary
5424   // stack slot.
5425   MachineFunction &MF = DAG.getMachineFunction();
5426   unsigned MemSize = DstTy.getSizeInBits()/8;
5427   int SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
5428   SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
5429
5430   unsigned Opc;
5431   switch (DstTy.getSimpleVT().SimpleTy) {
5432   default: llvm_unreachable("Invalid FP_TO_SINT to lower!");
5433   case MVT::i16: Opc = X86ISD::FP_TO_INT16_IN_MEM; break;
5434   case MVT::i32: Opc = X86ISD::FP_TO_INT32_IN_MEM; break;
5435   case MVT::i64: Opc = X86ISD::FP_TO_INT64_IN_MEM; break;
5436   }
5437
5438   SDValue Chain = DAG.getEntryNode();
5439   SDValue Value = Op.getOperand(0);
5440   if (isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType())) {
5441     assert(DstTy == MVT::i64 && "Invalid FP_TO_SINT to lower!");
5442     Chain = DAG.getStore(Chain, dl, Value, StackSlot,
5443                          PseudoSourceValue::getFixedStack(SSFI), 0);
5444     SDVTList Tys = DAG.getVTList(Op.getOperand(0).getValueType(), MVT::Other);
5445     SDValue Ops[] = {
5446       Chain, StackSlot, DAG.getValueType(Op.getOperand(0).getValueType())
5447     };
5448     Value = DAG.getNode(X86ISD::FLD, dl, Tys, Ops, 3);
5449     Chain = Value.getValue(1);
5450     SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
5451     StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
5452   }
5453
5454   // Build the FP_TO_INT*_IN_MEM
5455   SDValue Ops[] = { Chain, Value, StackSlot };
5456   SDValue FIST = DAG.getNode(Opc, dl, MVT::Other, Ops, 3);
5457
5458   return std::make_pair(FIST, StackSlot);
5459 }
5460
5461 SDValue X86TargetLowering::LowerFP_TO_SINT(SDValue Op, SelectionDAG &DAG) {
5462   if (Op.getValueType().isVector()) {
5463     if (Op.getValueType() == MVT::v2i32 &&
5464         Op.getOperand(0).getValueType() == MVT::v2f64) {
5465       return Op;
5466     }
5467     return SDValue();
5468   }
5469
5470   std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG, true);
5471   SDValue FIST = Vals.first, StackSlot = Vals.second;
5472   // If FP_TO_INTHelper failed, the node is actually supposed to be Legal.
5473   if (FIST.getNode() == 0) return Op;
5474
5475   // Load the result.
5476   return DAG.getLoad(Op.getValueType(), Op.getDebugLoc(),
5477                      FIST, StackSlot, NULL, 0);
5478 }
5479
5480 SDValue X86TargetLowering::LowerFP_TO_UINT(SDValue Op, SelectionDAG &DAG) {
5481   std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG, false);
5482   SDValue FIST = Vals.first, StackSlot = Vals.second;
5483   assert(FIST.getNode() && "Unexpected failure");
5484
5485   // Load the result.
5486   return DAG.getLoad(Op.getValueType(), Op.getDebugLoc(),
5487                      FIST, StackSlot, NULL, 0);
5488 }
5489
5490 SDValue X86TargetLowering::LowerFABS(SDValue Op, SelectionDAG &DAG) {
5491   LLVMContext *Context = DAG.getContext();
5492   DebugLoc dl = Op.getDebugLoc();
5493   EVT VT = Op.getValueType();
5494   EVT EltVT = VT;
5495   if (VT.isVector())
5496     EltVT = VT.getVectorElementType();
5497   std::vector<Constant*> CV;
5498   if (EltVT == MVT::f64) {
5499     Constant *C = ConstantFP::get(*Context, APFloat(APInt(64, ~(1ULL << 63))));
5500     CV.push_back(C);
5501     CV.push_back(C);
5502   } else {
5503     Constant *C = ConstantFP::get(*Context, APFloat(APInt(32, ~(1U << 31))));
5504     CV.push_back(C);
5505     CV.push_back(C);
5506     CV.push_back(C);
5507     CV.push_back(C);
5508   }
5509   Constant *C = ConstantVector::get(CV);
5510   SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
5511   SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
5512                                PseudoSourceValue::getConstantPool(), 0,
5513                                false, 16);
5514   return DAG.getNode(X86ISD::FAND, dl, VT, Op.getOperand(0), Mask);
5515 }
5516
5517 SDValue X86TargetLowering::LowerFNEG(SDValue Op, SelectionDAG &DAG) {
5518   LLVMContext *Context = DAG.getContext();
5519   DebugLoc dl = Op.getDebugLoc();
5520   EVT VT = Op.getValueType();
5521   EVT EltVT = VT;
5522   if (VT.isVector())
5523     EltVT = VT.getVectorElementType();
5524   std::vector<Constant*> CV;
5525   if (EltVT == MVT::f64) {
5526     Constant *C = ConstantFP::get(*Context, APFloat(APInt(64, 1ULL << 63)));
5527     CV.push_back(C);
5528     CV.push_back(C);
5529   } else {
5530     Constant *C = ConstantFP::get(*Context, APFloat(APInt(32, 1U << 31)));
5531     CV.push_back(C);
5532     CV.push_back(C);
5533     CV.push_back(C);
5534     CV.push_back(C);
5535   }
5536   Constant *C = ConstantVector::get(CV);
5537   SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
5538   SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
5539                                PseudoSourceValue::getConstantPool(), 0,
5540                                false, 16);
5541   if (VT.isVector()) {
5542     return DAG.getNode(ISD::BIT_CONVERT, dl, VT,
5543                        DAG.getNode(ISD::XOR, dl, MVT::v2i64,
5544                     DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v2i64,
5545                                 Op.getOperand(0)),
5546                     DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v2i64, Mask)));
5547   } else {
5548     return DAG.getNode(X86ISD::FXOR, dl, VT, Op.getOperand(0), Mask);
5549   }
5550 }
5551
5552 SDValue X86TargetLowering::LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) {
5553   LLVMContext *Context = DAG.getContext();
5554   SDValue Op0 = Op.getOperand(0);
5555   SDValue Op1 = Op.getOperand(1);
5556   DebugLoc dl = Op.getDebugLoc();
5557   EVT VT = Op.getValueType();
5558   EVT SrcVT = Op1.getValueType();
5559
5560   // If second operand is smaller, extend it first.
5561   if (SrcVT.bitsLT(VT)) {
5562     Op1 = DAG.getNode(ISD::FP_EXTEND, dl, VT, Op1);
5563     SrcVT = VT;
5564   }
5565   // And if it is bigger, shrink it first.
5566   if (SrcVT.bitsGT(VT)) {
5567     Op1 = DAG.getNode(ISD::FP_ROUND, dl, VT, Op1, DAG.getIntPtrConstant(1));
5568     SrcVT = VT;
5569   }
5570
5571   // At this point the operands and the result should have the same
5572   // type, and that won't be f80 since that is not custom lowered.
5573
5574   // First get the sign bit of second operand.
5575   std::vector<Constant*> CV;
5576   if (SrcVT == MVT::f64) {
5577     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, 1ULL << 63))));
5578     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, 0))));
5579   } else {
5580     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 1U << 31))));
5581     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
5582     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
5583     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
5584   }
5585   Constant *C = ConstantVector::get(CV);
5586   SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
5587   SDValue Mask1 = DAG.getLoad(SrcVT, dl, DAG.getEntryNode(), CPIdx,
5588                                 PseudoSourceValue::getConstantPool(), 0,
5589                                 false, 16);
5590   SDValue SignBit = DAG.getNode(X86ISD::FAND, dl, SrcVT, Op1, Mask1);
5591
5592   // Shift sign bit right or left if the two operands have different types.
5593   if (SrcVT.bitsGT(VT)) {
5594     // Op0 is MVT::f32, Op1 is MVT::f64.
5595     SignBit = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f64, SignBit);
5596     SignBit = DAG.getNode(X86ISD::FSRL, dl, MVT::v2f64, SignBit,
5597                           DAG.getConstant(32, MVT::i32));
5598     SignBit = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v4f32, SignBit);
5599     SignBit = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f32, SignBit,
5600                           DAG.getIntPtrConstant(0));
5601   }
5602
5603   // Clear first operand sign bit.
5604   CV.clear();
5605   if (VT == MVT::f64) {
5606     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, ~(1ULL << 63)))));
5607     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, 0))));
5608   } else {
5609     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, ~(1U << 31)))));
5610     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
5611     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
5612     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
5613   }
5614   C = ConstantVector::get(CV);
5615   CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
5616   SDValue Mask2 = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
5617                                 PseudoSourceValue::getConstantPool(), 0,
5618                                 false, 16);
5619   SDValue Val = DAG.getNode(X86ISD::FAND, dl, VT, Op0, Mask2);
5620
5621   // Or the value with the sign bit.
5622   return DAG.getNode(X86ISD::FOR, dl, VT, Val, SignBit);
5623 }
5624
5625 /// Emit nodes that will be selected as "test Op0,Op0", or something
5626 /// equivalent.
5627 SDValue X86TargetLowering::EmitTest(SDValue Op, unsigned X86CC,
5628                                     SelectionDAG &DAG) {
5629   DebugLoc dl = Op.getDebugLoc();
5630
5631   // CF and OF aren't always set the way we want. Determine which
5632   // of these we need.
5633   bool NeedCF = false;
5634   bool NeedOF = false;
5635   switch (X86CC) {
5636   case X86::COND_A: case X86::COND_AE:
5637   case X86::COND_B: case X86::COND_BE:
5638     NeedCF = true;
5639     break;
5640   case X86::COND_G: case X86::COND_GE:
5641   case X86::COND_L: case X86::COND_LE:
5642   case X86::COND_O: case X86::COND_NO:
5643     NeedOF = true;
5644     break;
5645   default: break;
5646   }
5647
5648   // See if we can use the EFLAGS value from the operand instead of
5649   // doing a separate TEST. TEST always sets OF and CF to 0, so unless
5650   // we prove that the arithmetic won't overflow, we can't use OF or CF.
5651   if (Op.getResNo() == 0 && !NeedOF && !NeedCF) {
5652     unsigned Opcode = 0;
5653     unsigned NumOperands = 0;
5654     switch (Op.getNode()->getOpcode()) {
5655     case ISD::ADD:
5656       // Due to an isel shortcoming, be conservative if this add is likely to
5657       // be selected as part of a load-modify-store instruction. When the root
5658       // node in a match is a store, isel doesn't know how to remap non-chain
5659       // non-flag uses of other nodes in the match, such as the ADD in this
5660       // case. This leads to the ADD being left around and reselected, with
5661       // the result being two adds in the output.
5662       for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
5663            UE = Op.getNode()->use_end(); UI != UE; ++UI)
5664         if (UI->getOpcode() == ISD::STORE)
5665           goto default_case;
5666       if (ConstantSDNode *C =
5667             dyn_cast<ConstantSDNode>(Op.getNode()->getOperand(1))) {
5668         // An add of one will be selected as an INC.
5669         if (C->getAPIntValue() == 1) {
5670           Opcode = X86ISD::INC;
5671           NumOperands = 1;
5672           break;
5673         }
5674         // An add of negative one (subtract of one) will be selected as a DEC.
5675         if (C->getAPIntValue().isAllOnesValue()) {
5676           Opcode = X86ISD::DEC;
5677           NumOperands = 1;
5678           break;
5679         }
5680       }
5681       // Otherwise use a regular EFLAGS-setting add.
5682       Opcode = X86ISD::ADD;
5683       NumOperands = 2;
5684       break;
5685     case ISD::AND: {
5686       // If the primary and result isn't used, don't bother using X86ISD::AND,
5687       // because a TEST instruction will be better.
5688       bool NonFlagUse = false;
5689       for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
5690              UE = Op.getNode()->use_end(); UI != UE; ++UI) {
5691         SDNode *User = *UI;
5692         unsigned UOpNo = UI.getOperandNo();
5693         if (User->getOpcode() == ISD::TRUNCATE && User->hasOneUse()) {
5694           // Look pass truncate.
5695           UOpNo = User->use_begin().getOperandNo();
5696           User = *User->use_begin();
5697         }
5698         if (User->getOpcode() != ISD::BRCOND &&
5699             User->getOpcode() != ISD::SETCC &&
5700             (User->getOpcode() != ISD::SELECT || UOpNo != 0)) {
5701           NonFlagUse = true;
5702           break;
5703         }
5704       }
5705       if (!NonFlagUse)
5706         break;
5707     }
5708     // FALL THROUGH
5709     case ISD::SUB:
5710     case ISD::OR:
5711     case ISD::XOR:
5712       // Due to the ISEL shortcoming noted above, be conservative if this op is
5713       // likely to be selected as part of a load-modify-store instruction.
5714       for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
5715            UE = Op.getNode()->use_end(); UI != UE; ++UI)
5716         if (UI->getOpcode() == ISD::STORE)
5717           goto default_case;
5718       // Otherwise use a regular EFLAGS-setting instruction.
5719       switch (Op.getNode()->getOpcode()) {
5720       case ISD::SUB: Opcode = X86ISD::SUB; break;
5721       case ISD::OR:  Opcode = X86ISD::OR;  break;
5722       case ISD::XOR: Opcode = X86ISD::XOR; break;
5723       case ISD::AND: Opcode = X86ISD::AND; break;
5724       default: llvm_unreachable("unexpected operator!");
5725       }
5726       NumOperands = 2;
5727       break;
5728     case X86ISD::ADD:
5729     case X86ISD::SUB:
5730     case X86ISD::INC:
5731     case X86ISD::DEC:
5732     case X86ISD::OR:
5733     case X86ISD::XOR:
5734     case X86ISD::AND:
5735       return SDValue(Op.getNode(), 1);
5736     default:
5737     default_case:
5738       break;
5739     }
5740     if (Opcode != 0) {
5741       SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
5742       SmallVector<SDValue, 4> Ops;
5743       for (unsigned i = 0; i != NumOperands; ++i)
5744         Ops.push_back(Op.getOperand(i));
5745       SDValue New = DAG.getNode(Opcode, dl, VTs, &Ops[0], NumOperands);
5746       DAG.ReplaceAllUsesWith(Op, New);
5747       return SDValue(New.getNode(), 1);
5748     }
5749   }
5750
5751   // Otherwise just emit a CMP with 0, which is the TEST pattern.
5752   return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
5753                      DAG.getConstant(0, Op.getValueType()));
5754 }
5755
5756 /// Emit nodes that will be selected as "cmp Op0,Op1", or something
5757 /// equivalent.
5758 SDValue X86TargetLowering::EmitCmp(SDValue Op0, SDValue Op1, unsigned X86CC,
5759                                    SelectionDAG &DAG) {
5760   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op1))
5761     if (C->getAPIntValue() == 0)
5762       return EmitTest(Op0, X86CC, DAG);
5763
5764   DebugLoc dl = Op0.getDebugLoc();
5765   return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op0, Op1);
5766 }
5767
5768 /// LowerToBT - Result of 'and' is compared against zero. Turn it into a BT node
5769 /// if it's possible.
5770 static SDValue LowerToBT(SDValue Op0, ISD::CondCode CC,
5771                          DebugLoc dl, SelectionDAG &DAG) {
5772   SDValue LHS, RHS;
5773   if (Op0.getOperand(1).getOpcode() == ISD::SHL) {
5774     if (ConstantSDNode *Op010C =
5775         dyn_cast<ConstantSDNode>(Op0.getOperand(1).getOperand(0)))
5776       if (Op010C->getZExtValue() == 1) {
5777         LHS = Op0.getOperand(0);
5778         RHS = Op0.getOperand(1).getOperand(1);
5779       }
5780   } else if (Op0.getOperand(0).getOpcode() == ISD::SHL) {
5781     if (ConstantSDNode *Op000C =
5782         dyn_cast<ConstantSDNode>(Op0.getOperand(0).getOperand(0)))
5783       if (Op000C->getZExtValue() == 1) {
5784         LHS = Op0.getOperand(1);
5785         RHS = Op0.getOperand(0).getOperand(1);
5786       }
5787   } else if (Op0.getOperand(1).getOpcode() == ISD::Constant) {
5788     ConstantSDNode *AndRHS = cast<ConstantSDNode>(Op0.getOperand(1));
5789     SDValue AndLHS = Op0.getOperand(0);
5790     if (AndRHS->getZExtValue() == 1 && AndLHS.getOpcode() == ISD::SRL) {
5791       LHS = AndLHS.getOperand(0);
5792       RHS = AndLHS.getOperand(1);
5793     }
5794   }
5795
5796   if (LHS.getNode()) {
5797     // If LHS is i8, promote it to i16 with any_extend.  There is no i8 BT
5798     // instruction.  Since the shift amount is in-range-or-undefined, we know
5799     // that doing a bittest on the i16 value is ok.  We extend to i32 because
5800     // the encoding for the i16 version is larger than the i32 version.
5801     if (LHS.getValueType() == MVT::i8)
5802       LHS = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, LHS);
5803
5804     // If the operand types disagree, extend the shift amount to match.  Since
5805     // BT ignores high bits (like shifts) we can use anyextend.
5806     if (LHS.getValueType() != RHS.getValueType())
5807       RHS = DAG.getNode(ISD::ANY_EXTEND, dl, LHS.getValueType(), RHS);
5808
5809     SDValue BT = DAG.getNode(X86ISD::BT, dl, MVT::i32, LHS, RHS);
5810     unsigned Cond = CC == ISD::SETEQ ? X86::COND_AE : X86::COND_B;
5811     return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
5812                        DAG.getConstant(Cond, MVT::i8), BT);
5813   }
5814
5815   return SDValue();
5816 }
5817
5818 SDValue X86TargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) {
5819   assert(Op.getValueType() == MVT::i8 && "SetCC type must be 8-bit integer");
5820   SDValue Op0 = Op.getOperand(0);
5821   SDValue Op1 = Op.getOperand(1);
5822   DebugLoc dl = Op.getDebugLoc();
5823   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
5824
5825   // Optimize to BT if possible.
5826   // Lower (X & (1 << N)) == 0 to BT(X, N).
5827   // Lower ((X >>u N) & 1) != 0 to BT(X, N).
5828   // Lower ((X >>s N) & 1) != 0 to BT(X, N).
5829   if (Op0.getOpcode() == ISD::AND &&
5830       Op0.hasOneUse() &&
5831       Op1.getOpcode() == ISD::Constant &&
5832       cast<ConstantSDNode>(Op1)->getZExtValue() == 0 &&
5833       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
5834     SDValue NewSetCC = LowerToBT(Op0, CC, dl, DAG);
5835     if (NewSetCC.getNode())
5836       return NewSetCC;
5837   }
5838
5839   bool isFP = Op.getOperand(1).getValueType().isFloatingPoint();
5840   unsigned X86CC = TranslateX86CC(CC, isFP, Op0, Op1, DAG);
5841   if (X86CC == X86::COND_INVALID)
5842     return SDValue();
5843
5844   SDValue Cond = EmitCmp(Op0, Op1, X86CC, DAG);
5845
5846   // Use sbb x, x to materialize carry bit into a GPR.
5847   if (X86CC == X86::COND_B)
5848     return DAG.getNode(ISD::AND, dl, MVT::i8,
5849                        DAG.getNode(X86ISD::SETCC_CARRY, dl, MVT::i8,
5850                                    DAG.getConstant(X86CC, MVT::i8), Cond),
5851                        DAG.getConstant(1, MVT::i8));
5852
5853   return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
5854                      DAG.getConstant(X86CC, MVT::i8), Cond);
5855 }
5856
5857 SDValue X86TargetLowering::LowerVSETCC(SDValue Op, SelectionDAG &DAG) {
5858   SDValue Cond;
5859   SDValue Op0 = Op.getOperand(0);
5860   SDValue Op1 = Op.getOperand(1);
5861   SDValue CC = Op.getOperand(2);
5862   EVT VT = Op.getValueType();
5863   ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
5864   bool isFP = Op.getOperand(1).getValueType().isFloatingPoint();
5865   DebugLoc dl = Op.getDebugLoc();
5866
5867   if (isFP) {
5868     unsigned SSECC = 8;
5869     EVT VT0 = Op0.getValueType();
5870     assert(VT0 == MVT::v4f32 || VT0 == MVT::v2f64);
5871     unsigned Opc = VT0 == MVT::v4f32 ? X86ISD::CMPPS : X86ISD::CMPPD;
5872     bool Swap = false;
5873
5874     switch (SetCCOpcode) {
5875     default: break;
5876     case ISD::SETOEQ:
5877     case ISD::SETEQ:  SSECC = 0; break;
5878     case ISD::SETOGT:
5879     case ISD::SETGT: Swap = true; // Fallthrough
5880     case ISD::SETLT:
5881     case ISD::SETOLT: SSECC = 1; break;
5882     case ISD::SETOGE:
5883     case ISD::SETGE: Swap = true; // Fallthrough
5884     case ISD::SETLE:
5885     case ISD::SETOLE: SSECC = 2; break;
5886     case ISD::SETUO:  SSECC = 3; break;
5887     case ISD::SETUNE:
5888     case ISD::SETNE:  SSECC = 4; break;
5889     case ISD::SETULE: Swap = true;
5890     case ISD::SETUGE: SSECC = 5; break;
5891     case ISD::SETULT: Swap = true;
5892     case ISD::SETUGT: SSECC = 6; break;
5893     case ISD::SETO:   SSECC = 7; break;
5894     }
5895     if (Swap)
5896       std::swap(Op0, Op1);
5897
5898     // In the two special cases we can't handle, emit two comparisons.
5899     if (SSECC == 8) {
5900       if (SetCCOpcode == ISD::SETUEQ) {
5901         SDValue UNORD, EQ;
5902         UNORD = DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(3, MVT::i8));
5903         EQ = DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(0, MVT::i8));
5904         return DAG.getNode(ISD::OR, dl, VT, UNORD, EQ);
5905       }
5906       else if (SetCCOpcode == ISD::SETONE) {
5907         SDValue ORD, NEQ;
5908         ORD = DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(7, MVT::i8));
5909         NEQ = DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(4, MVT::i8));
5910         return DAG.getNode(ISD::AND, dl, VT, ORD, NEQ);
5911       }
5912       llvm_unreachable("Illegal FP comparison");
5913     }
5914     // Handle all other FP comparisons here.
5915     return DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(SSECC, MVT::i8));
5916   }
5917
5918   // We are handling one of the integer comparisons here.  Since SSE only has
5919   // GT and EQ comparisons for integer, swapping operands and multiple
5920   // operations may be required for some comparisons.
5921   unsigned Opc = 0, EQOpc = 0, GTOpc = 0;
5922   bool Swap = false, Invert = false, FlipSigns = false;
5923
5924   switch (VT.getSimpleVT().SimpleTy) {
5925   default: break;
5926   case MVT::v8i8:
5927   case MVT::v16i8: EQOpc = X86ISD::PCMPEQB; GTOpc = X86ISD::PCMPGTB; break;
5928   case MVT::v4i16:
5929   case MVT::v8i16: EQOpc = X86ISD::PCMPEQW; GTOpc = X86ISD::PCMPGTW; break;
5930   case MVT::v2i32:
5931   case MVT::v4i32: EQOpc = X86ISD::PCMPEQD; GTOpc = X86ISD::PCMPGTD; break;
5932   case MVT::v2i64: EQOpc = X86ISD::PCMPEQQ; GTOpc = X86ISD::PCMPGTQ; break;
5933   }
5934
5935   switch (SetCCOpcode) {
5936   default: break;
5937   case ISD::SETNE:  Invert = true;
5938   case ISD::SETEQ:  Opc = EQOpc; break;
5939   case ISD::SETLT:  Swap = true;
5940   case ISD::SETGT:  Opc = GTOpc; break;
5941   case ISD::SETGE:  Swap = true;
5942   case ISD::SETLE:  Opc = GTOpc; Invert = true; break;
5943   case ISD::SETULT: Swap = true;
5944   case ISD::SETUGT: Opc = GTOpc; FlipSigns = true; break;
5945   case ISD::SETUGE: Swap = true;
5946   case ISD::SETULE: Opc = GTOpc; FlipSigns = true; Invert = true; break;
5947   }
5948   if (Swap)
5949     std::swap(Op0, Op1);
5950
5951   // Since SSE has no unsigned integer comparisons, we need to flip  the sign
5952   // bits of the inputs before performing those operations.
5953   if (FlipSigns) {
5954     EVT EltVT = VT.getVectorElementType();
5955     SDValue SignBit = DAG.getConstant(APInt::getSignBit(EltVT.getSizeInBits()),
5956                                       EltVT);
5957     std::vector<SDValue> SignBits(VT.getVectorNumElements(), SignBit);
5958     SDValue SignVec = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &SignBits[0],
5959                                     SignBits.size());
5960     Op0 = DAG.getNode(ISD::XOR, dl, VT, Op0, SignVec);
5961     Op1 = DAG.getNode(ISD::XOR, dl, VT, Op1, SignVec);
5962   }
5963
5964   SDValue Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
5965
5966   // If the logical-not of the result is required, perform that now.
5967   if (Invert)
5968     Result = DAG.getNOT(dl, Result, VT);
5969
5970   return Result;
5971 }
5972
5973 // isX86LogicalCmp - Return true if opcode is a X86 logical comparison.
5974 static bool isX86LogicalCmp(SDValue Op) {
5975   unsigned Opc = Op.getNode()->getOpcode();
5976   if (Opc == X86ISD::CMP || Opc == X86ISD::COMI || Opc == X86ISD::UCOMI)
5977     return true;
5978   if (Op.getResNo() == 1 &&
5979       (Opc == X86ISD::ADD ||
5980        Opc == X86ISD::SUB ||
5981        Opc == X86ISD::SMUL ||
5982        Opc == X86ISD::UMUL ||
5983        Opc == X86ISD::INC ||
5984        Opc == X86ISD::DEC ||
5985        Opc == X86ISD::OR ||
5986        Opc == X86ISD::XOR ||
5987        Opc == X86ISD::AND))
5988     return true;
5989
5990   return false;
5991 }
5992
5993 SDValue X86TargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) {
5994   bool addTest = true;
5995   SDValue Cond  = Op.getOperand(0);
5996   DebugLoc dl = Op.getDebugLoc();
5997   SDValue CC;
5998
5999   if (Cond.getOpcode() == ISD::SETCC) {
6000     SDValue NewCond = LowerSETCC(Cond, DAG);
6001     if (NewCond.getNode())
6002       Cond = NewCond;
6003   }
6004
6005   // (select (x == 0), -1, 0) -> (sign_bit (x - 1))
6006   SDValue Op1 = Op.getOperand(1);
6007   SDValue Op2 = Op.getOperand(2);
6008   if (Cond.getOpcode() == X86ISD::SETCC &&
6009       cast<ConstantSDNode>(Cond.getOperand(0))->getZExtValue() == X86::COND_E) {
6010     SDValue Cmp = Cond.getOperand(1);
6011     if (Cmp.getOpcode() == X86ISD::CMP) {
6012       ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(Op1);
6013       ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(Op2);
6014       ConstantSDNode *RHSC =
6015         dyn_cast<ConstantSDNode>(Cmp.getOperand(1).getNode());
6016       if (N1C && N1C->isAllOnesValue() &&
6017           N2C && N2C->isNullValue() &&
6018           RHSC && RHSC->isNullValue()) {
6019         SDValue CmpOp0 = Cmp.getOperand(0);
6020         Cmp = DAG.getNode(X86ISD::CMP, dl, Op.getValueType(),
6021                           CmpOp0, DAG.getConstant(1, CmpOp0.getValueType()));
6022         return DAG.getNode(X86ISD::SETCC_CARRY, dl, Op.getValueType(),
6023                            DAG.getConstant(X86::COND_B, MVT::i8), Cmp);
6024       }
6025     }
6026   }
6027
6028   // Look pass (and (setcc_carry (cmp ...)), 1).
6029   if (Cond.getOpcode() == ISD::AND &&
6030       Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
6031     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
6032     if (C && C->getAPIntValue() == 1) 
6033       Cond = Cond.getOperand(0);
6034   }
6035
6036   // If condition flag is set by a X86ISD::CMP, then use it as the condition
6037   // setting operand in place of the X86ISD::SETCC.
6038   if (Cond.getOpcode() == X86ISD::SETCC ||
6039       Cond.getOpcode() == X86ISD::SETCC_CARRY) {
6040     CC = Cond.getOperand(0);
6041
6042     SDValue Cmp = Cond.getOperand(1);
6043     unsigned Opc = Cmp.getOpcode();
6044     EVT VT = Op.getValueType();
6045
6046     bool IllegalFPCMov = false;
6047     if (VT.isFloatingPoint() && !VT.isVector() &&
6048         !isScalarFPTypeInSSEReg(VT))  // FPStack?
6049       IllegalFPCMov = !hasFPCMov(cast<ConstantSDNode>(CC)->getSExtValue());
6050
6051     if ((isX86LogicalCmp(Cmp) && !IllegalFPCMov) ||
6052         Opc == X86ISD::BT) { // FIXME
6053       Cond = Cmp;
6054       addTest = false;
6055     }
6056   }
6057
6058   if (addTest) {
6059     // Look pass the truncate.
6060     if (Cond.getOpcode() == ISD::TRUNCATE)
6061       Cond = Cond.getOperand(0);
6062
6063     // We know the result of AND is compared against zero. Try to match
6064     // it to BT.
6065     if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) { 
6066       SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, dl, DAG);
6067       if (NewSetCC.getNode()) {
6068         CC = NewSetCC.getOperand(0);
6069         Cond = NewSetCC.getOperand(1);
6070         addTest = false;
6071       }
6072     }
6073   }
6074
6075   if (addTest) {
6076     CC = DAG.getConstant(X86::COND_NE, MVT::i8);
6077     Cond = EmitTest(Cond, X86::COND_NE, DAG);
6078   }
6079
6080   // X86ISD::CMOV means set the result (which is operand 1) to the RHS if
6081   // condition is true.
6082   SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::Flag);
6083   SDValue Ops[] = { Op2, Op1, CC, Cond };
6084   return DAG.getNode(X86ISD::CMOV, dl, VTs, Ops, array_lengthof(Ops));
6085 }
6086
6087 // isAndOrOfSingleUseSetCCs - Return true if node is an ISD::AND or
6088 // ISD::OR of two X86ISD::SETCC nodes each of which has no other use apart
6089 // from the AND / OR.
6090 static bool isAndOrOfSetCCs(SDValue Op, unsigned &Opc) {
6091   Opc = Op.getOpcode();
6092   if (Opc != ISD::OR && Opc != ISD::AND)
6093     return false;
6094   return (Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
6095           Op.getOperand(0).hasOneUse() &&
6096           Op.getOperand(1).getOpcode() == X86ISD::SETCC &&
6097           Op.getOperand(1).hasOneUse());
6098 }
6099
6100 // isXor1OfSetCC - Return true if node is an ISD::XOR of a X86ISD::SETCC and
6101 // 1 and that the SETCC node has a single use.
6102 static bool isXor1OfSetCC(SDValue Op) {
6103   if (Op.getOpcode() != ISD::XOR)
6104     return false;
6105   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
6106   if (N1C && N1C->getAPIntValue() == 1) {
6107     return Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
6108       Op.getOperand(0).hasOneUse();
6109   }
6110   return false;
6111 }
6112
6113 SDValue X86TargetLowering::LowerBRCOND(SDValue Op, SelectionDAG &DAG) {
6114   bool addTest = true;
6115   SDValue Chain = Op.getOperand(0);
6116   SDValue Cond  = Op.getOperand(1);
6117   SDValue Dest  = Op.getOperand(2);
6118   DebugLoc dl = Op.getDebugLoc();
6119   SDValue CC;
6120
6121   if (Cond.getOpcode() == ISD::SETCC) {
6122     SDValue NewCond = LowerSETCC(Cond, DAG);
6123     if (NewCond.getNode())
6124       Cond = NewCond;
6125   }
6126 #if 0
6127   // FIXME: LowerXALUO doesn't handle these!!
6128   else if (Cond.getOpcode() == X86ISD::ADD  ||
6129            Cond.getOpcode() == X86ISD::SUB  ||
6130            Cond.getOpcode() == X86ISD::SMUL ||
6131            Cond.getOpcode() == X86ISD::UMUL)
6132     Cond = LowerXALUO(Cond, DAG);
6133 #endif
6134
6135   // Look pass (and (setcc_carry (cmp ...)), 1).
6136   if (Cond.getOpcode() == ISD::AND &&
6137       Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
6138     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
6139     if (C && C->getAPIntValue() == 1) 
6140       Cond = Cond.getOperand(0);
6141   }
6142
6143   // If condition flag is set by a X86ISD::CMP, then use it as the condition
6144   // setting operand in place of the X86ISD::SETCC.
6145   if (Cond.getOpcode() == X86ISD::SETCC ||
6146       Cond.getOpcode() == X86ISD::SETCC_CARRY) {
6147     CC = Cond.getOperand(0);
6148
6149     SDValue Cmp = Cond.getOperand(1);
6150     unsigned Opc = Cmp.getOpcode();
6151     // FIXME: WHY THE SPECIAL CASING OF LogicalCmp??
6152     if (isX86LogicalCmp(Cmp) || Opc == X86ISD::BT) {
6153       Cond = Cmp;
6154       addTest = false;
6155     } else {
6156       switch (cast<ConstantSDNode>(CC)->getZExtValue()) {
6157       default: break;
6158       case X86::COND_O:
6159       case X86::COND_B:
6160         // These can only come from an arithmetic instruction with overflow,
6161         // e.g. SADDO, UADDO.
6162         Cond = Cond.getNode()->getOperand(1);
6163         addTest = false;
6164         break;
6165       }
6166     }
6167   } else {
6168     unsigned CondOpc;
6169     if (Cond.hasOneUse() && isAndOrOfSetCCs(Cond, CondOpc)) {
6170       SDValue Cmp = Cond.getOperand(0).getOperand(1);
6171       if (CondOpc == ISD::OR) {
6172         // Also, recognize the pattern generated by an FCMP_UNE. We can emit
6173         // two branches instead of an explicit OR instruction with a
6174         // separate test.
6175         if (Cmp == Cond.getOperand(1).getOperand(1) &&
6176             isX86LogicalCmp(Cmp)) {
6177           CC = Cond.getOperand(0).getOperand(0);
6178           Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
6179                               Chain, Dest, CC, Cmp);
6180           CC = Cond.getOperand(1).getOperand(0);
6181           Cond = Cmp;
6182           addTest = false;
6183         }
6184       } else { // ISD::AND
6185         // Also, recognize the pattern generated by an FCMP_OEQ. We can emit
6186         // two branches instead of an explicit AND instruction with a
6187         // separate test. However, we only do this if this block doesn't
6188         // have a fall-through edge, because this requires an explicit
6189         // jmp when the condition is false.
6190         if (Cmp == Cond.getOperand(1).getOperand(1) &&
6191             isX86LogicalCmp(Cmp) &&
6192             Op.getNode()->hasOneUse()) {
6193           X86::CondCode CCode =
6194             (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
6195           CCode = X86::GetOppositeBranchCondition(CCode);
6196           CC = DAG.getConstant(CCode, MVT::i8);
6197           SDValue User = SDValue(*Op.getNode()->use_begin(), 0);
6198           // Look for an unconditional branch following this conditional branch.
6199           // We need this because we need to reverse the successors in order
6200           // to implement FCMP_OEQ.
6201           if (User.getOpcode() == ISD::BR) {
6202             SDValue FalseBB = User.getOperand(1);
6203             SDValue NewBR =
6204               DAG.UpdateNodeOperands(User, User.getOperand(0), Dest);
6205             assert(NewBR == User);
6206             Dest = FalseBB;
6207
6208             Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
6209                                 Chain, Dest, CC, Cmp);
6210             X86::CondCode CCode =
6211               (X86::CondCode)Cond.getOperand(1).getConstantOperandVal(0);
6212             CCode = X86::GetOppositeBranchCondition(CCode);
6213             CC = DAG.getConstant(CCode, MVT::i8);
6214             Cond = Cmp;
6215             addTest = false;
6216           }
6217         }
6218       }
6219     } else if (Cond.hasOneUse() && isXor1OfSetCC(Cond)) {
6220       // Recognize for xorb (setcc), 1 patterns. The xor inverts the condition.
6221       // It should be transformed during dag combiner except when the condition
6222       // is set by a arithmetics with overflow node.
6223       X86::CondCode CCode =
6224         (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
6225       CCode = X86::GetOppositeBranchCondition(CCode);
6226       CC = DAG.getConstant(CCode, MVT::i8);
6227       Cond = Cond.getOperand(0).getOperand(1);
6228       addTest = false;
6229     }
6230   }
6231
6232   if (addTest) {
6233     // Look pass the truncate.
6234     if (Cond.getOpcode() == ISD::TRUNCATE)
6235       Cond = Cond.getOperand(0);
6236
6237     // We know the result of AND is compared against zero. Try to match
6238     // it to BT.
6239     if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) { 
6240       SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, dl, DAG);
6241       if (NewSetCC.getNode()) {
6242         CC = NewSetCC.getOperand(0);
6243         Cond = NewSetCC.getOperand(1);
6244         addTest = false;
6245       }
6246     }
6247   }
6248
6249   if (addTest) {
6250     CC = DAG.getConstant(X86::COND_NE, MVT::i8);
6251     Cond = EmitTest(Cond, X86::COND_NE, DAG);
6252   }
6253   return DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
6254                      Chain, Dest, CC, Cond);
6255 }
6256
6257
6258 // Lower dynamic stack allocation to _alloca call for Cygwin/Mingw targets.
6259 // Calls to _alloca is needed to probe the stack when allocating more than 4k
6260 // bytes in one go. Touching the stack at 4K increments is necessary to ensure
6261 // that the guard pages used by the OS virtual memory manager are allocated in
6262 // correct sequence.
6263 SDValue
6264 X86TargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
6265                                            SelectionDAG &DAG) {
6266   assert(Subtarget->isTargetCygMing() &&
6267          "This should be used only on Cygwin/Mingw targets");
6268   DebugLoc dl = Op.getDebugLoc();
6269
6270   // Get the inputs.
6271   SDValue Chain = Op.getOperand(0);
6272   SDValue Size  = Op.getOperand(1);
6273   // FIXME: Ensure alignment here
6274
6275   SDValue Flag;
6276
6277   EVT IntPtr = getPointerTy();
6278   EVT SPTy = Subtarget->is64Bit() ? MVT::i64 : MVT::i32;
6279
6280   Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(0, true));
6281
6282   Chain = DAG.getCopyToReg(Chain, dl, X86::EAX, Size, Flag);
6283   Flag = Chain.getValue(1);
6284
6285   SDVTList  NodeTys = DAG.getVTList(MVT::Other, MVT::Flag);
6286   SDValue Ops[] = { Chain,
6287                       DAG.getTargetExternalSymbol("_alloca", IntPtr),
6288                       DAG.getRegister(X86::EAX, IntPtr),
6289                       DAG.getRegister(X86StackPtr, SPTy),
6290                       Flag };
6291   Chain = DAG.getNode(X86ISD::CALL, dl, NodeTys, Ops, 5);
6292   Flag = Chain.getValue(1);
6293
6294   Chain = DAG.getCALLSEQ_END(Chain,
6295                              DAG.getIntPtrConstant(0, true),
6296                              DAG.getIntPtrConstant(0, true),
6297                              Flag);
6298
6299   Chain = DAG.getCopyFromReg(Chain, dl, X86StackPtr, SPTy).getValue(1);
6300
6301   SDValue Ops1[2] = { Chain.getValue(0), Chain };
6302   return DAG.getMergeValues(Ops1, 2, dl);
6303 }
6304
6305 SDValue
6306 X86TargetLowering::EmitTargetCodeForMemset(SelectionDAG &DAG, DebugLoc dl,
6307                                            SDValue Chain,
6308                                            SDValue Dst, SDValue Src,
6309                                            SDValue Size, unsigned Align,
6310                                            const Value *DstSV,
6311                                            uint64_t DstSVOff) {
6312   ConstantSDNode *ConstantSize = dyn_cast<ConstantSDNode>(Size);
6313
6314   // If not DWORD aligned or size is more than the threshold, call the library.
6315   // The libc version is likely to be faster for these cases. It can use the
6316   // address value and run time information about the CPU.
6317   if ((Align & 3) != 0 ||
6318       !ConstantSize ||
6319       ConstantSize->getZExtValue() >
6320         getSubtarget()->getMaxInlineSizeThreshold()) {
6321     SDValue InFlag(0, 0);
6322
6323     // Check to see if there is a specialized entry-point for memory zeroing.
6324     ConstantSDNode *V = dyn_cast<ConstantSDNode>(Src);
6325
6326     if (const char *bzeroEntry =  V &&
6327         V->isNullValue() ? Subtarget->getBZeroEntry() : 0) {
6328       EVT IntPtr = getPointerTy();
6329       const Type *IntPtrTy = TD->getIntPtrType(*DAG.getContext());
6330       TargetLowering::ArgListTy Args;
6331       TargetLowering::ArgListEntry Entry;
6332       Entry.Node = Dst;
6333       Entry.Ty = IntPtrTy;
6334       Args.push_back(Entry);
6335       Entry.Node = Size;
6336       Args.push_back(Entry);
6337       std::pair<SDValue,SDValue> CallResult =
6338         LowerCallTo(Chain, Type::getVoidTy(*DAG.getContext()),
6339                     false, false, false, false,
6340                     0, CallingConv::C, false, /*isReturnValueUsed=*/false,
6341                     DAG.getExternalSymbol(bzeroEntry, IntPtr), Args, DAG, dl,
6342                     DAG.GetOrdering(Chain.getNode()));
6343       return CallResult.second;
6344     }
6345
6346     // Otherwise have the target-independent code call memset.
6347     return SDValue();
6348   }
6349
6350   uint64_t SizeVal = ConstantSize->getZExtValue();
6351   SDValue InFlag(0, 0);
6352   EVT AVT;
6353   SDValue Count;
6354   ConstantSDNode *ValC = dyn_cast<ConstantSDNode>(Src);
6355   unsigned BytesLeft = 0;
6356   bool TwoRepStos = false;
6357   if (ValC) {
6358     unsigned ValReg;
6359     uint64_t Val = ValC->getZExtValue() & 255;
6360
6361     // If the value is a constant, then we can potentially use larger sets.
6362     switch (Align & 3) {
6363     case 2:   // WORD aligned
6364       AVT = MVT::i16;
6365       ValReg = X86::AX;
6366       Val = (Val << 8) | Val;
6367       break;
6368     case 0:  // DWORD aligned
6369       AVT = MVT::i32;
6370       ValReg = X86::EAX;
6371       Val = (Val << 8)  | Val;
6372       Val = (Val << 16) | Val;
6373       if (Subtarget->is64Bit() && ((Align & 0x7) == 0)) {  // QWORD aligned
6374         AVT = MVT::i64;
6375         ValReg = X86::RAX;
6376         Val = (Val << 32) | Val;
6377       }
6378       break;
6379     default:  // Byte aligned
6380       AVT = MVT::i8;
6381       ValReg = X86::AL;
6382       Count = DAG.getIntPtrConstant(SizeVal);
6383       break;
6384     }
6385
6386     if (AVT.bitsGT(MVT::i8)) {
6387       unsigned UBytes = AVT.getSizeInBits() / 8;
6388       Count = DAG.getIntPtrConstant(SizeVal / UBytes);
6389       BytesLeft = SizeVal % UBytes;
6390     }
6391
6392     Chain  = DAG.getCopyToReg(Chain, dl, ValReg, DAG.getConstant(Val, AVT),
6393                               InFlag);
6394     InFlag = Chain.getValue(1);
6395   } else {
6396     AVT = MVT::i8;
6397     Count  = DAG.getIntPtrConstant(SizeVal);
6398     Chain  = DAG.getCopyToReg(Chain, dl, X86::AL, Src, InFlag);
6399     InFlag = Chain.getValue(1);
6400   }
6401
6402   Chain  = DAG.getCopyToReg(Chain, dl, Subtarget->is64Bit() ? X86::RCX :
6403                                                               X86::ECX,
6404                             Count, InFlag);
6405   InFlag = Chain.getValue(1);
6406   Chain  = DAG.getCopyToReg(Chain, dl, Subtarget->is64Bit() ? X86::RDI :
6407                                                               X86::EDI,
6408                             Dst, InFlag);
6409   InFlag = Chain.getValue(1);
6410
6411   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Flag);
6412   SDValue Ops[] = { Chain, DAG.getValueType(AVT), InFlag };
6413   Chain = DAG.getNode(X86ISD::REP_STOS, dl, Tys, Ops, array_lengthof(Ops));
6414
6415   if (TwoRepStos) {
6416     InFlag = Chain.getValue(1);
6417     Count  = Size;
6418     EVT CVT = Count.getValueType();
6419     SDValue Left = DAG.getNode(ISD::AND, dl, CVT, Count,
6420                                DAG.getConstant((AVT == MVT::i64) ? 7 : 3, CVT));
6421     Chain  = DAG.getCopyToReg(Chain, dl, (CVT == MVT::i64) ? X86::RCX :
6422                                                              X86::ECX,
6423                               Left, InFlag);
6424     InFlag = Chain.getValue(1);
6425     Tys = DAG.getVTList(MVT::Other, MVT::Flag);
6426     SDValue Ops[] = { Chain, DAG.getValueType(MVT::i8), InFlag };
6427     Chain = DAG.getNode(X86ISD::REP_STOS, dl, Tys, Ops, array_lengthof(Ops));
6428   } else if (BytesLeft) {
6429     // Handle the last 1 - 7 bytes.
6430     unsigned Offset = SizeVal - BytesLeft;
6431     EVT AddrVT = Dst.getValueType();
6432     EVT SizeVT = Size.getValueType();
6433
6434     Chain = DAG.getMemset(Chain, dl,
6435                           DAG.getNode(ISD::ADD, dl, AddrVT, Dst,
6436                                       DAG.getConstant(Offset, AddrVT)),
6437                           Src,
6438                           DAG.getConstant(BytesLeft, SizeVT),
6439                           Align, DstSV, DstSVOff + Offset);
6440   }
6441
6442   // TODO: Use a Tokenfactor, as in memcpy, instead of a single chain.
6443   return Chain;
6444 }
6445
6446 SDValue
6447 X86TargetLowering::EmitTargetCodeForMemcpy(SelectionDAG &DAG, DebugLoc dl,
6448                                       SDValue Chain, SDValue Dst, SDValue Src,
6449                                       SDValue Size, unsigned Align,
6450                                       bool AlwaysInline,
6451                                       const Value *DstSV, uint64_t DstSVOff,
6452                                       const Value *SrcSV, uint64_t SrcSVOff) {
6453   // This requires the copy size to be a constant, preferrably
6454   // within a subtarget-specific limit.
6455   ConstantSDNode *ConstantSize = dyn_cast<ConstantSDNode>(Size);
6456   if (!ConstantSize)
6457     return SDValue();
6458   uint64_t SizeVal = ConstantSize->getZExtValue();
6459   if (!AlwaysInline && SizeVal > getSubtarget()->getMaxInlineSizeThreshold())
6460     return SDValue();
6461
6462   /// If not DWORD aligned, call the library.
6463   if ((Align & 3) != 0)
6464     return SDValue();
6465
6466   // DWORD aligned
6467   EVT AVT = MVT::i32;
6468   if (Subtarget->is64Bit() && ((Align & 0x7) == 0))  // QWORD aligned
6469     AVT = MVT::i64;
6470
6471   unsigned UBytes = AVT.getSizeInBits() / 8;
6472   unsigned CountVal = SizeVal / UBytes;
6473   SDValue Count = DAG.getIntPtrConstant(CountVal);
6474   unsigned BytesLeft = SizeVal % UBytes;
6475
6476   SDValue InFlag(0, 0);
6477   Chain  = DAG.getCopyToReg(Chain, dl, Subtarget->is64Bit() ? X86::RCX :
6478                                                               X86::ECX,
6479                             Count, InFlag);
6480   InFlag = Chain.getValue(1);
6481   Chain  = DAG.getCopyToReg(Chain, dl, Subtarget->is64Bit() ? X86::RDI :
6482                                                              X86::EDI,
6483                             Dst, InFlag);
6484   InFlag = Chain.getValue(1);
6485   Chain  = DAG.getCopyToReg(Chain, dl, Subtarget->is64Bit() ? X86::RSI :
6486                                                               X86::ESI,
6487                             Src, InFlag);
6488   InFlag = Chain.getValue(1);
6489
6490   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Flag);
6491   SDValue Ops[] = { Chain, DAG.getValueType(AVT), InFlag };
6492   SDValue RepMovs = DAG.getNode(X86ISD::REP_MOVS, dl, Tys, Ops,
6493                                 array_lengthof(Ops));
6494
6495   SmallVector<SDValue, 4> Results;
6496   Results.push_back(RepMovs);
6497   if (BytesLeft) {
6498     // Handle the last 1 - 7 bytes.
6499     unsigned Offset = SizeVal - BytesLeft;
6500     EVT DstVT = Dst.getValueType();
6501     EVT SrcVT = Src.getValueType();
6502     EVT SizeVT = Size.getValueType();
6503     Results.push_back(DAG.getMemcpy(Chain, dl,
6504                                     DAG.getNode(ISD::ADD, dl, DstVT, Dst,
6505                                                 DAG.getConstant(Offset, DstVT)),
6506                                     DAG.getNode(ISD::ADD, dl, SrcVT, Src,
6507                                                 DAG.getConstant(Offset, SrcVT)),
6508                                     DAG.getConstant(BytesLeft, SizeVT),
6509                                     Align, AlwaysInline,
6510                                     DstSV, DstSVOff + Offset,
6511                                     SrcSV, SrcSVOff + Offset));
6512   }
6513
6514   return DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
6515                      &Results[0], Results.size());
6516 }
6517
6518 SDValue X86TargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) {
6519   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
6520   DebugLoc dl = Op.getDebugLoc();
6521
6522   if (!Subtarget->is64Bit()) {
6523     // vastart just stores the address of the VarArgsFrameIndex slot into the
6524     // memory location argument.
6525     SDValue FR = DAG.getFrameIndex(VarArgsFrameIndex, getPointerTy());
6526     return DAG.getStore(Op.getOperand(0), dl, FR, Op.getOperand(1), SV, 0);
6527   }
6528
6529   // __va_list_tag:
6530   //   gp_offset         (0 - 6 * 8)
6531   //   fp_offset         (48 - 48 + 8 * 16)
6532   //   overflow_arg_area (point to parameters coming in memory).
6533   //   reg_save_area
6534   SmallVector<SDValue, 8> MemOps;
6535   SDValue FIN = Op.getOperand(1);
6536   // Store gp_offset
6537   SDValue Store = DAG.getStore(Op.getOperand(0), dl,
6538                                  DAG.getConstant(VarArgsGPOffset, MVT::i32),
6539                                  FIN, SV, 0);
6540   MemOps.push_back(Store);
6541
6542   // Store fp_offset
6543   FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(),
6544                     FIN, DAG.getIntPtrConstant(4));
6545   Store = DAG.getStore(Op.getOperand(0), dl,
6546                        DAG.getConstant(VarArgsFPOffset, MVT::i32),
6547                        FIN, SV, 0);
6548   MemOps.push_back(Store);
6549
6550   // Store ptr to overflow_arg_area
6551   FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(),
6552                     FIN, DAG.getIntPtrConstant(4));
6553   SDValue OVFIN = DAG.getFrameIndex(VarArgsFrameIndex, getPointerTy());
6554   Store = DAG.getStore(Op.getOperand(0), dl, OVFIN, FIN, SV, 0);
6555   MemOps.push_back(Store);
6556
6557   // Store ptr to reg_save_area.
6558   FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(),
6559                     FIN, DAG.getIntPtrConstant(8));
6560   SDValue RSFIN = DAG.getFrameIndex(RegSaveFrameIndex, getPointerTy());
6561   Store = DAG.getStore(Op.getOperand(0), dl, RSFIN, FIN, SV, 0);
6562   MemOps.push_back(Store);
6563   return DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
6564                      &MemOps[0], MemOps.size());
6565 }
6566
6567 SDValue X86TargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) {
6568   // X86-64 va_list is a struct { i32, i32, i8*, i8* }.
6569   assert(Subtarget->is64Bit() && "This code only handles 64-bit va_arg!");
6570   SDValue Chain = Op.getOperand(0);
6571   SDValue SrcPtr = Op.getOperand(1);
6572   SDValue SrcSV = Op.getOperand(2);
6573
6574   llvm_report_error("VAArgInst is not yet implemented for x86-64!");
6575   return SDValue();
6576 }
6577
6578 SDValue X86TargetLowering::LowerVACOPY(SDValue Op, SelectionDAG &DAG) {
6579   // X86-64 va_list is a struct { i32, i32, i8*, i8* }.
6580   assert(Subtarget->is64Bit() && "This code only handles 64-bit va_copy!");
6581   SDValue Chain = Op.getOperand(0);
6582   SDValue DstPtr = Op.getOperand(1);
6583   SDValue SrcPtr = Op.getOperand(2);
6584   const Value *DstSV = cast<SrcValueSDNode>(Op.getOperand(3))->getValue();
6585   const Value *SrcSV = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
6586   DebugLoc dl = Op.getDebugLoc();
6587
6588   return DAG.getMemcpy(Chain, dl, DstPtr, SrcPtr,
6589                        DAG.getIntPtrConstant(24), 8, false,
6590                        DstSV, 0, SrcSV, 0);
6591 }
6592
6593 SDValue
6594 X86TargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op, SelectionDAG &DAG) {
6595   DebugLoc dl = Op.getDebugLoc();
6596   unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
6597   switch (IntNo) {
6598   default: return SDValue();    // Don't custom lower most intrinsics.
6599   // Comparison intrinsics.
6600   case Intrinsic::x86_sse_comieq_ss:
6601   case Intrinsic::x86_sse_comilt_ss:
6602   case Intrinsic::x86_sse_comile_ss:
6603   case Intrinsic::x86_sse_comigt_ss:
6604   case Intrinsic::x86_sse_comige_ss:
6605   case Intrinsic::x86_sse_comineq_ss:
6606   case Intrinsic::x86_sse_ucomieq_ss:
6607   case Intrinsic::x86_sse_ucomilt_ss:
6608   case Intrinsic::x86_sse_ucomile_ss:
6609   case Intrinsic::x86_sse_ucomigt_ss:
6610   case Intrinsic::x86_sse_ucomige_ss:
6611   case Intrinsic::x86_sse_ucomineq_ss:
6612   case Intrinsic::x86_sse2_comieq_sd:
6613   case Intrinsic::x86_sse2_comilt_sd:
6614   case Intrinsic::x86_sse2_comile_sd:
6615   case Intrinsic::x86_sse2_comigt_sd:
6616   case Intrinsic::x86_sse2_comige_sd:
6617   case Intrinsic::x86_sse2_comineq_sd:
6618   case Intrinsic::x86_sse2_ucomieq_sd:
6619   case Intrinsic::x86_sse2_ucomilt_sd:
6620   case Intrinsic::x86_sse2_ucomile_sd:
6621   case Intrinsic::x86_sse2_ucomigt_sd:
6622   case Intrinsic::x86_sse2_ucomige_sd:
6623   case Intrinsic::x86_sse2_ucomineq_sd: {
6624     unsigned Opc = 0;
6625     ISD::CondCode CC = ISD::SETCC_INVALID;
6626     switch (IntNo) {
6627     default: break;
6628     case Intrinsic::x86_sse_comieq_ss:
6629     case Intrinsic::x86_sse2_comieq_sd:
6630       Opc = X86ISD::COMI;
6631       CC = ISD::SETEQ;
6632       break;
6633     case Intrinsic::x86_sse_comilt_ss:
6634     case Intrinsic::x86_sse2_comilt_sd:
6635       Opc = X86ISD::COMI;
6636       CC = ISD::SETLT;
6637       break;
6638     case Intrinsic::x86_sse_comile_ss:
6639     case Intrinsic::x86_sse2_comile_sd:
6640       Opc = X86ISD::COMI;
6641       CC = ISD::SETLE;
6642       break;
6643     case Intrinsic::x86_sse_comigt_ss:
6644     case Intrinsic::x86_sse2_comigt_sd:
6645       Opc = X86ISD::COMI;
6646       CC = ISD::SETGT;
6647       break;
6648     case Intrinsic::x86_sse_comige_ss:
6649     case Intrinsic::x86_sse2_comige_sd:
6650       Opc = X86ISD::COMI;
6651       CC = ISD::SETGE;
6652       break;
6653     case Intrinsic::x86_sse_comineq_ss:
6654     case Intrinsic::x86_sse2_comineq_sd:
6655       Opc = X86ISD::COMI;
6656       CC = ISD::SETNE;
6657       break;
6658     case Intrinsic::x86_sse_ucomieq_ss:
6659     case Intrinsic::x86_sse2_ucomieq_sd:
6660       Opc = X86ISD::UCOMI;
6661       CC = ISD::SETEQ;
6662       break;
6663     case Intrinsic::x86_sse_ucomilt_ss:
6664     case Intrinsic::x86_sse2_ucomilt_sd:
6665       Opc = X86ISD::UCOMI;
6666       CC = ISD::SETLT;
6667       break;
6668     case Intrinsic::x86_sse_ucomile_ss:
6669     case Intrinsic::x86_sse2_ucomile_sd:
6670       Opc = X86ISD::UCOMI;
6671       CC = ISD::SETLE;
6672       break;
6673     case Intrinsic::x86_sse_ucomigt_ss:
6674     case Intrinsic::x86_sse2_ucomigt_sd:
6675       Opc = X86ISD::UCOMI;
6676       CC = ISD::SETGT;
6677       break;
6678     case Intrinsic::x86_sse_ucomige_ss:
6679     case Intrinsic::x86_sse2_ucomige_sd:
6680       Opc = X86ISD::UCOMI;
6681       CC = ISD::SETGE;
6682       break;
6683     case Intrinsic::x86_sse_ucomineq_ss:
6684     case Intrinsic::x86_sse2_ucomineq_sd:
6685       Opc = X86ISD::UCOMI;
6686       CC = ISD::SETNE;
6687       break;
6688     }
6689
6690     SDValue LHS = Op.getOperand(1);
6691     SDValue RHS = Op.getOperand(2);
6692     unsigned X86CC = TranslateX86CC(CC, true, LHS, RHS, DAG);
6693     assert(X86CC != X86::COND_INVALID && "Unexpected illegal condition!");
6694     SDValue Cond = DAG.getNode(Opc, dl, MVT::i32, LHS, RHS);
6695     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
6696                                 DAG.getConstant(X86CC, MVT::i8), Cond);
6697     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
6698   }
6699   // ptest intrinsics. The intrinsic these come from are designed to return
6700   // an integer value, not just an instruction so lower it to the ptest
6701   // pattern and a setcc for the result.
6702   case Intrinsic::x86_sse41_ptestz:
6703   case Intrinsic::x86_sse41_ptestc:
6704   case Intrinsic::x86_sse41_ptestnzc:{
6705     unsigned X86CC = 0;
6706     switch (IntNo) {
6707     default: llvm_unreachable("Bad fallthrough in Intrinsic lowering.");
6708     case Intrinsic::x86_sse41_ptestz:
6709       // ZF = 1
6710       X86CC = X86::COND_E;
6711       break;
6712     case Intrinsic::x86_sse41_ptestc:
6713       // CF = 1
6714       X86CC = X86::COND_B;
6715       break;
6716     case Intrinsic::x86_sse41_ptestnzc:
6717       // ZF and CF = 0
6718       X86CC = X86::COND_A;
6719       break;
6720     }
6721
6722     SDValue LHS = Op.getOperand(1);
6723     SDValue RHS = Op.getOperand(2);
6724     SDValue Test = DAG.getNode(X86ISD::PTEST, dl, MVT::i32, LHS, RHS);
6725     SDValue CC = DAG.getConstant(X86CC, MVT::i8);
6726     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8, CC, Test);
6727     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
6728   }
6729
6730   // Fix vector shift instructions where the last operand is a non-immediate
6731   // i32 value.
6732   case Intrinsic::x86_sse2_pslli_w:
6733   case Intrinsic::x86_sse2_pslli_d:
6734   case Intrinsic::x86_sse2_pslli_q:
6735   case Intrinsic::x86_sse2_psrli_w:
6736   case Intrinsic::x86_sse2_psrli_d:
6737   case Intrinsic::x86_sse2_psrli_q:
6738   case Intrinsic::x86_sse2_psrai_w:
6739   case Intrinsic::x86_sse2_psrai_d:
6740   case Intrinsic::x86_mmx_pslli_w:
6741   case Intrinsic::x86_mmx_pslli_d:
6742   case Intrinsic::x86_mmx_pslli_q:
6743   case Intrinsic::x86_mmx_psrli_w:
6744   case Intrinsic::x86_mmx_psrli_d:
6745   case Intrinsic::x86_mmx_psrli_q:
6746   case Intrinsic::x86_mmx_psrai_w:
6747   case Intrinsic::x86_mmx_psrai_d: {
6748     SDValue ShAmt = Op.getOperand(2);
6749     if (isa<ConstantSDNode>(ShAmt))
6750       return SDValue();
6751
6752     unsigned NewIntNo = 0;
6753     EVT ShAmtVT = MVT::v4i32;
6754     switch (IntNo) {
6755     case Intrinsic::x86_sse2_pslli_w:
6756       NewIntNo = Intrinsic::x86_sse2_psll_w;
6757       break;
6758     case Intrinsic::x86_sse2_pslli_d:
6759       NewIntNo = Intrinsic::x86_sse2_psll_d;
6760       break;
6761     case Intrinsic::x86_sse2_pslli_q:
6762       NewIntNo = Intrinsic::x86_sse2_psll_q;
6763       break;
6764     case Intrinsic::x86_sse2_psrli_w:
6765       NewIntNo = Intrinsic::x86_sse2_psrl_w;
6766       break;
6767     case Intrinsic::x86_sse2_psrli_d:
6768       NewIntNo = Intrinsic::x86_sse2_psrl_d;
6769       break;
6770     case Intrinsic::x86_sse2_psrli_q:
6771       NewIntNo = Intrinsic::x86_sse2_psrl_q;
6772       break;
6773     case Intrinsic::x86_sse2_psrai_w:
6774       NewIntNo = Intrinsic::x86_sse2_psra_w;
6775       break;
6776     case Intrinsic::x86_sse2_psrai_d:
6777       NewIntNo = Intrinsic::x86_sse2_psra_d;
6778       break;
6779     default: {
6780       ShAmtVT = MVT::v2i32;
6781       switch (IntNo) {
6782       case Intrinsic::x86_mmx_pslli_w:
6783         NewIntNo = Intrinsic::x86_mmx_psll_w;
6784         break;
6785       case Intrinsic::x86_mmx_pslli_d:
6786         NewIntNo = Intrinsic::x86_mmx_psll_d;
6787         break;
6788       case Intrinsic::x86_mmx_pslli_q:
6789         NewIntNo = Intrinsic::x86_mmx_psll_q;
6790         break;
6791       case Intrinsic::x86_mmx_psrli_w:
6792         NewIntNo = Intrinsic::x86_mmx_psrl_w;
6793         break;
6794       case Intrinsic::x86_mmx_psrli_d:
6795         NewIntNo = Intrinsic::x86_mmx_psrl_d;
6796         break;
6797       case Intrinsic::x86_mmx_psrli_q:
6798         NewIntNo = Intrinsic::x86_mmx_psrl_q;
6799         break;
6800       case Intrinsic::x86_mmx_psrai_w:
6801         NewIntNo = Intrinsic::x86_mmx_psra_w;
6802         break;
6803       case Intrinsic::x86_mmx_psrai_d:
6804         NewIntNo = Intrinsic::x86_mmx_psra_d;
6805         break;
6806       default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
6807       }
6808       break;
6809     }
6810     }
6811
6812     // The vector shift intrinsics with scalars uses 32b shift amounts but
6813     // the sse2/mmx shift instructions reads 64 bits. Set the upper 32 bits
6814     // to be zero.
6815     SDValue ShOps[4];
6816     ShOps[0] = ShAmt;
6817     ShOps[1] = DAG.getConstant(0, MVT::i32);
6818     if (ShAmtVT == MVT::v4i32) {
6819       ShOps[2] = DAG.getUNDEF(MVT::i32);
6820       ShOps[3] = DAG.getUNDEF(MVT::i32);
6821       ShAmt =  DAG.getNode(ISD::BUILD_VECTOR, dl, ShAmtVT, &ShOps[0], 4);
6822     } else {
6823       ShAmt =  DAG.getNode(ISD::BUILD_VECTOR, dl, ShAmtVT, &ShOps[0], 2);
6824     }
6825
6826     EVT VT = Op.getValueType();
6827     ShAmt = DAG.getNode(ISD::BIT_CONVERT, dl, VT, ShAmt);
6828     return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
6829                        DAG.getConstant(NewIntNo, MVT::i32),
6830                        Op.getOperand(1), ShAmt);
6831   }
6832   }
6833 }
6834
6835 SDValue X86TargetLowering::LowerRETURNADDR(SDValue Op, SelectionDAG &DAG) {
6836   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
6837   DebugLoc dl = Op.getDebugLoc();
6838
6839   if (Depth > 0) {
6840     SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
6841     SDValue Offset =
6842       DAG.getConstant(TD->getPointerSize(),
6843                       Subtarget->is64Bit() ? MVT::i64 : MVT::i32);
6844     return DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(),
6845                        DAG.getNode(ISD::ADD, dl, getPointerTy(),
6846                                    FrameAddr, Offset),
6847                        NULL, 0);
6848   }
6849
6850   // Just load the return address.
6851   SDValue RetAddrFI = getReturnAddressFrameIndex(DAG);
6852   return DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(),
6853                      RetAddrFI, NULL, 0);
6854 }
6855
6856 SDValue X86TargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) {
6857   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
6858   MFI->setFrameAddressIsTaken(true);
6859   EVT VT = Op.getValueType();
6860   DebugLoc dl = Op.getDebugLoc();  // FIXME probably not meaningful
6861   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
6862   unsigned FrameReg = Subtarget->is64Bit() ? X86::RBP : X86::EBP;
6863   SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
6864   while (Depth--)
6865     FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr, NULL, 0);
6866   return FrameAddr;
6867 }
6868
6869 SDValue X86TargetLowering::LowerFRAME_TO_ARGS_OFFSET(SDValue Op,
6870                                                      SelectionDAG &DAG) {
6871   return DAG.getIntPtrConstant(2*TD->getPointerSize());
6872 }
6873
6874 SDValue X86TargetLowering::LowerEH_RETURN(SDValue Op, SelectionDAG &DAG)
6875 {
6876   MachineFunction &MF = DAG.getMachineFunction();
6877   SDValue Chain     = Op.getOperand(0);
6878   SDValue Offset    = Op.getOperand(1);
6879   SDValue Handler   = Op.getOperand(2);
6880   DebugLoc dl       = Op.getDebugLoc();
6881
6882   SDValue Frame = DAG.getRegister(Subtarget->is64Bit() ? X86::RBP : X86::EBP,
6883                                   getPointerTy());
6884   unsigned StoreAddrReg = (Subtarget->is64Bit() ? X86::RCX : X86::ECX);
6885
6886   SDValue StoreAddr = DAG.getNode(ISD::SUB, dl, getPointerTy(), Frame,
6887                                   DAG.getIntPtrConstant(-TD->getPointerSize()));
6888   StoreAddr = DAG.getNode(ISD::ADD, dl, getPointerTy(), StoreAddr, Offset);
6889   Chain = DAG.getStore(Chain, dl, Handler, StoreAddr, NULL, 0);
6890   Chain = DAG.getCopyToReg(Chain, dl, StoreAddrReg, StoreAddr);
6891   MF.getRegInfo().addLiveOut(StoreAddrReg);
6892
6893   return DAG.getNode(X86ISD::EH_RETURN, dl,
6894                      MVT::Other,
6895                      Chain, DAG.getRegister(StoreAddrReg, getPointerTy()));
6896 }
6897
6898 SDValue X86TargetLowering::LowerTRAMPOLINE(SDValue Op,
6899                                              SelectionDAG &DAG) {
6900   SDValue Root = Op.getOperand(0);
6901   SDValue Trmp = Op.getOperand(1); // trampoline
6902   SDValue FPtr = Op.getOperand(2); // nested function
6903   SDValue Nest = Op.getOperand(3); // 'nest' parameter value
6904   DebugLoc dl  = Op.getDebugLoc();
6905
6906   const Value *TrmpAddr = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
6907
6908   const X86InstrInfo *TII =
6909     ((X86TargetMachine&)getTargetMachine()).getInstrInfo();
6910
6911   if (Subtarget->is64Bit()) {
6912     SDValue OutChains[6];
6913
6914     // Large code-model.
6915
6916     const unsigned char JMP64r  = TII->getBaseOpcodeFor(X86::JMP64r);
6917     const unsigned char MOV64ri = TII->getBaseOpcodeFor(X86::MOV64ri);
6918
6919     const unsigned char N86R10 = RegInfo->getX86RegNum(X86::R10);
6920     const unsigned char N86R11 = RegInfo->getX86RegNum(X86::R11);
6921
6922     const unsigned char REX_WB = 0x40 | 0x08 | 0x01; // REX prefix
6923
6924     // Load the pointer to the nested function into R11.
6925     unsigned OpCode = ((MOV64ri | N86R11) << 8) | REX_WB; // movabsq r11
6926     SDValue Addr = Trmp;
6927     OutChains[0] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
6928                                 Addr, TrmpAddr, 0);
6929
6930     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
6931                        DAG.getConstant(2, MVT::i64));
6932     OutChains[1] = DAG.getStore(Root, dl, FPtr, Addr, TrmpAddr, 2, false, 2);
6933
6934     // Load the 'nest' parameter value into R10.
6935     // R10 is specified in X86CallingConv.td
6936     OpCode = ((MOV64ri | N86R10) << 8) | REX_WB; // movabsq r10
6937     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
6938                        DAG.getConstant(10, MVT::i64));
6939     OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
6940                                 Addr, TrmpAddr, 10);
6941
6942     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
6943                        DAG.getConstant(12, MVT::i64));
6944     OutChains[3] = DAG.getStore(Root, dl, Nest, Addr, TrmpAddr, 12, false, 2);
6945
6946     // Jump to the nested function.
6947     OpCode = (JMP64r << 8) | REX_WB; // jmpq *...
6948     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
6949                        DAG.getConstant(20, MVT::i64));
6950     OutChains[4] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
6951                                 Addr, TrmpAddr, 20);
6952
6953     unsigned char ModRM = N86R11 | (4 << 3) | (3 << 6); // ...r11
6954     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
6955                        DAG.getConstant(22, MVT::i64));
6956     OutChains[5] = DAG.getStore(Root, dl, DAG.getConstant(ModRM, MVT::i8), Addr,
6957                                 TrmpAddr, 22);
6958
6959     SDValue Ops[] =
6960       { Trmp, DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains, 6) };
6961     return DAG.getMergeValues(Ops, 2, dl);
6962   } else {
6963     const Function *Func =
6964       cast<Function>(cast<SrcValueSDNode>(Op.getOperand(5))->getValue());
6965     CallingConv::ID CC = Func->getCallingConv();
6966     unsigned NestReg;
6967
6968     switch (CC) {
6969     default:
6970       llvm_unreachable("Unsupported calling convention");
6971     case CallingConv::C:
6972     case CallingConv::X86_StdCall: {
6973       // Pass 'nest' parameter in ECX.
6974       // Must be kept in sync with X86CallingConv.td
6975       NestReg = X86::ECX;
6976
6977       // Check that ECX wasn't needed by an 'inreg' parameter.
6978       const FunctionType *FTy = Func->getFunctionType();
6979       const AttrListPtr &Attrs = Func->getAttributes();
6980
6981       if (!Attrs.isEmpty() && !Func->isVarArg()) {
6982         unsigned InRegCount = 0;
6983         unsigned Idx = 1;
6984
6985         for (FunctionType::param_iterator I = FTy->param_begin(),
6986              E = FTy->param_end(); I != E; ++I, ++Idx)
6987           if (Attrs.paramHasAttr(Idx, Attribute::InReg))
6988             // FIXME: should only count parameters that are lowered to integers.
6989             InRegCount += (TD->getTypeSizeInBits(*I) + 31) / 32;
6990
6991         if (InRegCount > 2) {
6992           llvm_report_error("Nest register in use - reduce number of inreg parameters!");
6993         }
6994       }
6995       break;
6996     }
6997     case CallingConv::X86_FastCall:
6998     case CallingConv::Fast:
6999       // Pass 'nest' parameter in EAX.
7000       // Must be kept in sync with X86CallingConv.td
7001       NestReg = X86::EAX;
7002       break;
7003     }
7004
7005     SDValue OutChains[4];
7006     SDValue Addr, Disp;
7007
7008     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
7009                        DAG.getConstant(10, MVT::i32));
7010     Disp = DAG.getNode(ISD::SUB, dl, MVT::i32, FPtr, Addr);
7011
7012     const unsigned char MOV32ri = TII->getBaseOpcodeFor(X86::MOV32ri);
7013     const unsigned char N86Reg = RegInfo->getX86RegNum(NestReg);
7014     OutChains[0] = DAG.getStore(Root, dl,
7015                                 DAG.getConstant(MOV32ri|N86Reg, MVT::i8),
7016                                 Trmp, TrmpAddr, 0);
7017
7018     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
7019                        DAG.getConstant(1, MVT::i32));
7020     OutChains[1] = DAG.getStore(Root, dl, Nest, Addr, TrmpAddr, 1, false, 1);
7021
7022     const unsigned char JMP = TII->getBaseOpcodeFor(X86::JMP);
7023     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
7024                        DAG.getConstant(5, MVT::i32));
7025     OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(JMP, MVT::i8), Addr,
7026                                 TrmpAddr, 5, false, 1);
7027
7028     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
7029                        DAG.getConstant(6, MVT::i32));
7030     OutChains[3] = DAG.getStore(Root, dl, Disp, Addr, TrmpAddr, 6, false, 1);
7031
7032     SDValue Ops[] =
7033       { Trmp, DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains, 4) };
7034     return DAG.getMergeValues(Ops, 2, dl);
7035   }
7036 }
7037
7038 SDValue X86TargetLowering::LowerFLT_ROUNDS_(SDValue Op, SelectionDAG &DAG) {
7039   /*
7040    The rounding mode is in bits 11:10 of FPSR, and has the following
7041    settings:
7042      00 Round to nearest
7043      01 Round to -inf
7044      10 Round to +inf
7045      11 Round to 0
7046
7047   FLT_ROUNDS, on the other hand, expects the following:
7048     -1 Undefined
7049      0 Round to 0
7050      1 Round to nearest
7051      2 Round to +inf
7052      3 Round to -inf
7053
7054   To perform the conversion, we do:
7055     (((((FPSR & 0x800) >> 11) | ((FPSR & 0x400) >> 9)) + 1) & 3)
7056   */
7057
7058   MachineFunction &MF = DAG.getMachineFunction();
7059   const TargetMachine &TM = MF.getTarget();
7060   const TargetFrameInfo &TFI = *TM.getFrameInfo();
7061   unsigned StackAlignment = TFI.getStackAlignment();
7062   EVT VT = Op.getValueType();
7063   DebugLoc dl = Op.getDebugLoc();
7064
7065   // Save FP Control Word to stack slot
7066   int SSFI = MF.getFrameInfo()->CreateStackObject(2, StackAlignment, false);
7067   SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
7068
7069   SDValue Chain = DAG.getNode(X86ISD::FNSTCW16m, dl, MVT::Other,
7070                               DAG.getEntryNode(), StackSlot);
7071
7072   // Load FP Control Word from stack slot
7073   SDValue CWD = DAG.getLoad(MVT::i16, dl, Chain, StackSlot, NULL, 0);
7074
7075   // Transform as necessary
7076   SDValue CWD1 =
7077     DAG.getNode(ISD::SRL, dl, MVT::i16,
7078                 DAG.getNode(ISD::AND, dl, MVT::i16,
7079                             CWD, DAG.getConstant(0x800, MVT::i16)),
7080                 DAG.getConstant(11, MVT::i8));
7081   SDValue CWD2 =
7082     DAG.getNode(ISD::SRL, dl, MVT::i16,
7083                 DAG.getNode(ISD::AND, dl, MVT::i16,
7084                             CWD, DAG.getConstant(0x400, MVT::i16)),
7085                 DAG.getConstant(9, MVT::i8));
7086
7087   SDValue RetVal =
7088     DAG.getNode(ISD::AND, dl, MVT::i16,
7089                 DAG.getNode(ISD::ADD, dl, MVT::i16,
7090                             DAG.getNode(ISD::OR, dl, MVT::i16, CWD1, CWD2),
7091                             DAG.getConstant(1, MVT::i16)),
7092                 DAG.getConstant(3, MVT::i16));
7093
7094
7095   return DAG.getNode((VT.getSizeInBits() < 16 ?
7096                       ISD::TRUNCATE : ISD::ZERO_EXTEND), dl, VT, RetVal);
7097 }
7098
7099 SDValue X86TargetLowering::LowerCTLZ(SDValue Op, SelectionDAG &DAG) {
7100   EVT VT = Op.getValueType();
7101   EVT OpVT = VT;
7102   unsigned NumBits = VT.getSizeInBits();
7103   DebugLoc dl = Op.getDebugLoc();
7104
7105   Op = Op.getOperand(0);
7106   if (VT == MVT::i8) {
7107     // Zero extend to i32 since there is not an i8 bsr.
7108     OpVT = MVT::i32;
7109     Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
7110   }
7111
7112   // Issue a bsr (scan bits in reverse) which also sets EFLAGS.
7113   SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
7114   Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
7115
7116   // If src is zero (i.e. bsr sets ZF), returns NumBits.
7117   SDValue Ops[] = {
7118     Op,
7119     DAG.getConstant(NumBits+NumBits-1, OpVT),
7120     DAG.getConstant(X86::COND_E, MVT::i8),
7121     Op.getValue(1)
7122   };
7123   Op = DAG.getNode(X86ISD::CMOV, dl, OpVT, Ops, array_lengthof(Ops));
7124
7125   // Finally xor with NumBits-1.
7126   Op = DAG.getNode(ISD::XOR, dl, OpVT, Op, DAG.getConstant(NumBits-1, OpVT));
7127
7128   if (VT == MVT::i8)
7129     Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
7130   return Op;
7131 }
7132
7133 SDValue X86TargetLowering::LowerCTTZ(SDValue Op, SelectionDAG &DAG) {
7134   EVT VT = Op.getValueType();
7135   EVT OpVT = VT;
7136   unsigned NumBits = VT.getSizeInBits();
7137   DebugLoc dl = Op.getDebugLoc();
7138
7139   Op = Op.getOperand(0);
7140   if (VT == MVT::i8) {
7141     OpVT = MVT::i32;
7142     Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
7143   }
7144
7145   // Issue a bsf (scan bits forward) which also sets EFLAGS.
7146   SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
7147   Op = DAG.getNode(X86ISD::BSF, dl, VTs, Op);
7148
7149   // If src is zero (i.e. bsf sets ZF), returns NumBits.
7150   SDValue Ops[] = {
7151     Op,
7152     DAG.getConstant(NumBits, OpVT),
7153     DAG.getConstant(X86::COND_E, MVT::i8),
7154     Op.getValue(1)
7155   };
7156   Op = DAG.getNode(X86ISD::CMOV, dl, OpVT, Ops, array_lengthof(Ops));
7157
7158   if (VT == MVT::i8)
7159     Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
7160   return Op;
7161 }
7162
7163 SDValue X86TargetLowering::LowerMUL_V2I64(SDValue Op, SelectionDAG &DAG) {
7164   EVT VT = Op.getValueType();
7165   assert(VT == MVT::v2i64 && "Only know how to lower V2I64 multiply");
7166   DebugLoc dl = Op.getDebugLoc();
7167
7168   //  ulong2 Ahi = __builtin_ia32_psrlqi128( a, 32);
7169   //  ulong2 Bhi = __builtin_ia32_psrlqi128( b, 32);
7170   //  ulong2 AloBlo = __builtin_ia32_pmuludq128( a, b );
7171   //  ulong2 AloBhi = __builtin_ia32_pmuludq128( a, Bhi );
7172   //  ulong2 AhiBlo = __builtin_ia32_pmuludq128( Ahi, b );
7173   //
7174   //  AloBhi = __builtin_ia32_psllqi128( AloBhi, 32 );
7175   //  AhiBlo = __builtin_ia32_psllqi128( AhiBlo, 32 );
7176   //  return AloBlo + AloBhi + AhiBlo;
7177
7178   SDValue A = Op.getOperand(0);
7179   SDValue B = Op.getOperand(1);
7180
7181   SDValue Ahi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
7182                        DAG.getConstant(Intrinsic::x86_sse2_psrli_q, MVT::i32),
7183                        A, DAG.getConstant(32, MVT::i32));
7184   SDValue Bhi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
7185                        DAG.getConstant(Intrinsic::x86_sse2_psrli_q, MVT::i32),
7186                        B, DAG.getConstant(32, MVT::i32));
7187   SDValue AloBlo = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
7188                        DAG.getConstant(Intrinsic::x86_sse2_pmulu_dq, MVT::i32),
7189                        A, B);
7190   SDValue AloBhi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
7191                        DAG.getConstant(Intrinsic::x86_sse2_pmulu_dq, MVT::i32),
7192                        A, Bhi);
7193   SDValue AhiBlo = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
7194                        DAG.getConstant(Intrinsic::x86_sse2_pmulu_dq, MVT::i32),
7195                        Ahi, B);
7196   AloBhi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
7197                        DAG.getConstant(Intrinsic::x86_sse2_pslli_q, MVT::i32),
7198                        AloBhi, DAG.getConstant(32, MVT::i32));
7199   AhiBlo = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
7200                        DAG.getConstant(Intrinsic::x86_sse2_pslli_q, MVT::i32),
7201                        AhiBlo, DAG.getConstant(32, MVT::i32));
7202   SDValue Res = DAG.getNode(ISD::ADD, dl, VT, AloBlo, AloBhi);
7203   Res = DAG.getNode(ISD::ADD, dl, VT, Res, AhiBlo);
7204   return Res;
7205 }
7206
7207
7208 SDValue X86TargetLowering::LowerXALUO(SDValue Op, SelectionDAG &DAG) {
7209   // Lower the "add/sub/mul with overflow" instruction into a regular ins plus
7210   // a "setcc" instruction that checks the overflow flag. The "brcond" lowering
7211   // looks for this combo and may remove the "setcc" instruction if the "setcc"
7212   // has only one use.
7213   SDNode *N = Op.getNode();
7214   SDValue LHS = N->getOperand(0);
7215   SDValue RHS = N->getOperand(1);
7216   unsigned BaseOp = 0;
7217   unsigned Cond = 0;
7218   DebugLoc dl = Op.getDebugLoc();
7219
7220   switch (Op.getOpcode()) {
7221   default: llvm_unreachable("Unknown ovf instruction!");
7222   case ISD::SADDO:
7223     // A subtract of one will be selected as a INC. Note that INC doesn't
7224     // set CF, so we can't do this for UADDO.
7225     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op))
7226       if (C->getAPIntValue() == 1) {
7227         BaseOp = X86ISD::INC;
7228         Cond = X86::COND_O;
7229         break;
7230       }
7231     BaseOp = X86ISD::ADD;
7232     Cond = X86::COND_O;
7233     break;
7234   case ISD::UADDO:
7235     BaseOp = X86ISD::ADD;
7236     Cond = X86::COND_B;
7237     break;
7238   case ISD::SSUBO:
7239     // A subtract of one will be selected as a DEC. Note that DEC doesn't
7240     // set CF, so we can't do this for USUBO.
7241     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op))
7242       if (C->getAPIntValue() == 1) {
7243         BaseOp = X86ISD::DEC;
7244         Cond = X86::COND_O;
7245         break;
7246       }
7247     BaseOp = X86ISD::SUB;
7248     Cond = X86::COND_O;
7249     break;
7250   case ISD::USUBO:
7251     BaseOp = X86ISD::SUB;
7252     Cond = X86::COND_B;
7253     break;
7254   case ISD::SMULO:
7255     BaseOp = X86ISD::SMUL;
7256     Cond = X86::COND_O;
7257     break;
7258   case ISD::UMULO:
7259     BaseOp = X86ISD::UMUL;
7260     Cond = X86::COND_B;
7261     break;
7262   }
7263
7264   // Also sets EFLAGS.
7265   SDVTList VTs = DAG.getVTList(N->getValueType(0), MVT::i32);
7266   SDValue Sum = DAG.getNode(BaseOp, dl, VTs, LHS, RHS);
7267
7268   SDValue SetCC =
7269     DAG.getNode(X86ISD::SETCC, dl, N->getValueType(1),
7270                 DAG.getConstant(Cond, MVT::i32), SDValue(Sum.getNode(), 1));
7271
7272   DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), SetCC);
7273   return Sum;
7274 }
7275
7276 SDValue X86TargetLowering::LowerCMP_SWAP(SDValue Op, SelectionDAG &DAG) {
7277   EVT T = Op.getValueType();
7278   DebugLoc dl = Op.getDebugLoc();
7279   unsigned Reg = 0;
7280   unsigned size = 0;
7281   switch(T.getSimpleVT().SimpleTy) {
7282   default:
7283     assert(false && "Invalid value type!");
7284   case MVT::i8:  Reg = X86::AL;  size = 1; break;
7285   case MVT::i16: Reg = X86::AX;  size = 2; break;
7286   case MVT::i32: Reg = X86::EAX; size = 4; break;
7287   case MVT::i64:
7288     assert(Subtarget->is64Bit() && "Node not type legal!");
7289     Reg = X86::RAX; size = 8;
7290     break;
7291   }
7292   SDValue cpIn = DAG.getCopyToReg(Op.getOperand(0), dl, Reg,
7293                                     Op.getOperand(2), SDValue());
7294   SDValue Ops[] = { cpIn.getValue(0),
7295                     Op.getOperand(1),
7296                     Op.getOperand(3),
7297                     DAG.getTargetConstant(size, MVT::i8),
7298                     cpIn.getValue(1) };
7299   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Flag);
7300   SDValue Result = DAG.getNode(X86ISD::LCMPXCHG_DAG, dl, Tys, Ops, 5);
7301   SDValue cpOut =
7302     DAG.getCopyFromReg(Result.getValue(0), dl, Reg, T, Result.getValue(1));
7303   return cpOut;
7304 }
7305
7306 SDValue X86TargetLowering::LowerREADCYCLECOUNTER(SDValue Op,
7307                                                  SelectionDAG &DAG) {
7308   assert(Subtarget->is64Bit() && "Result not type legalized?");
7309   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Flag);
7310   SDValue TheChain = Op.getOperand(0);
7311   DebugLoc dl = Op.getDebugLoc();
7312   SDValue rd = DAG.getNode(X86ISD::RDTSC_DAG, dl, Tys, &TheChain, 1);
7313   SDValue rax = DAG.getCopyFromReg(rd, dl, X86::RAX, MVT::i64, rd.getValue(1));
7314   SDValue rdx = DAG.getCopyFromReg(rax.getValue(1), dl, X86::RDX, MVT::i64,
7315                                    rax.getValue(2));
7316   SDValue Tmp = DAG.getNode(ISD::SHL, dl, MVT::i64, rdx,
7317                             DAG.getConstant(32, MVT::i8));
7318   SDValue Ops[] = {
7319     DAG.getNode(ISD::OR, dl, MVT::i64, rax, Tmp),
7320     rdx.getValue(1)
7321   };
7322   return DAG.getMergeValues(Ops, 2, dl);
7323 }
7324
7325 SDValue X86TargetLowering::LowerLOAD_SUB(SDValue Op, SelectionDAG &DAG) {
7326   SDNode *Node = Op.getNode();
7327   DebugLoc dl = Node->getDebugLoc();
7328   EVT T = Node->getValueType(0);
7329   SDValue negOp = DAG.getNode(ISD::SUB, dl, T,
7330                               DAG.getConstant(0, T), Node->getOperand(2));
7331   return DAG.getAtomic(ISD::ATOMIC_LOAD_ADD, dl,
7332                        cast<AtomicSDNode>(Node)->getMemoryVT(),
7333                        Node->getOperand(0),
7334                        Node->getOperand(1), negOp,
7335                        cast<AtomicSDNode>(Node)->getSrcValue(),
7336                        cast<AtomicSDNode>(Node)->getAlignment());
7337 }
7338
7339 /// LowerOperation - Provide custom lowering hooks for some operations.
7340 ///
7341 SDValue X86TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) {
7342   switch (Op.getOpcode()) {
7343   default: llvm_unreachable("Should not custom lower this!");
7344   case ISD::ATOMIC_CMP_SWAP:    return LowerCMP_SWAP(Op,DAG);
7345   case ISD::ATOMIC_LOAD_SUB:    return LowerLOAD_SUB(Op,DAG);
7346   case ISD::BUILD_VECTOR:       return LowerBUILD_VECTOR(Op, DAG);
7347   case ISD::CONCAT_VECTORS:     return LowerCONCAT_VECTORS(Op, DAG);
7348   case ISD::VECTOR_SHUFFLE:     return LowerVECTOR_SHUFFLE(Op, DAG);
7349   case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
7350   case ISD::INSERT_VECTOR_ELT:  return LowerINSERT_VECTOR_ELT(Op, DAG);
7351   case ISD::SCALAR_TO_VECTOR:   return LowerSCALAR_TO_VECTOR(Op, DAG);
7352   case ISD::ConstantPool:       return LowerConstantPool(Op, DAG);
7353   case ISD::GlobalAddress:      return LowerGlobalAddress(Op, DAG);
7354   case ISD::GlobalTLSAddress:   return LowerGlobalTLSAddress(Op, DAG);
7355   case ISD::ExternalSymbol:     return LowerExternalSymbol(Op, DAG);
7356   case ISD::BlockAddress:       return LowerBlockAddress(Op, DAG);
7357   case ISD::SHL_PARTS:
7358   case ISD::SRA_PARTS:
7359   case ISD::SRL_PARTS:          return LowerShift(Op, DAG);
7360   case ISD::SINT_TO_FP:         return LowerSINT_TO_FP(Op, DAG);
7361   case ISD::UINT_TO_FP:         return LowerUINT_TO_FP(Op, DAG);
7362   case ISD::FP_TO_SINT:         return LowerFP_TO_SINT(Op, DAG);
7363   case ISD::FP_TO_UINT:         return LowerFP_TO_UINT(Op, DAG);
7364   case ISD::FABS:               return LowerFABS(Op, DAG);
7365   case ISD::FNEG:               return LowerFNEG(Op, DAG);
7366   case ISD::FCOPYSIGN:          return LowerFCOPYSIGN(Op, DAG);
7367   case ISD::SETCC:              return LowerSETCC(Op, DAG);
7368   case ISD::VSETCC:             return LowerVSETCC(Op, DAG);
7369   case ISD::SELECT:             return LowerSELECT(Op, DAG);
7370   case ISD::BRCOND:             return LowerBRCOND(Op, DAG);
7371   case ISD::JumpTable:          return LowerJumpTable(Op, DAG);
7372   case ISD::VASTART:            return LowerVASTART(Op, DAG);
7373   case ISD::VAARG:              return LowerVAARG(Op, DAG);
7374   case ISD::VACOPY:             return LowerVACOPY(Op, DAG);
7375   case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
7376   case ISD::RETURNADDR:         return LowerRETURNADDR(Op, DAG);
7377   case ISD::FRAMEADDR:          return LowerFRAMEADDR(Op, DAG);
7378   case ISD::FRAME_TO_ARGS_OFFSET:
7379                                 return LowerFRAME_TO_ARGS_OFFSET(Op, DAG);
7380   case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG);
7381   case ISD::EH_RETURN:          return LowerEH_RETURN(Op, DAG);
7382   case ISD::TRAMPOLINE:         return LowerTRAMPOLINE(Op, DAG);
7383   case ISD::FLT_ROUNDS_:        return LowerFLT_ROUNDS_(Op, DAG);
7384   case ISD::CTLZ:               return LowerCTLZ(Op, DAG);
7385   case ISD::CTTZ:               return LowerCTTZ(Op, DAG);
7386   case ISD::MUL:                return LowerMUL_V2I64(Op, DAG);
7387   case ISD::SADDO:
7388   case ISD::UADDO:
7389   case ISD::SSUBO:
7390   case ISD::USUBO:
7391   case ISD::SMULO:
7392   case ISD::UMULO:              return LowerXALUO(Op, DAG);
7393   case ISD::READCYCLECOUNTER:   return LowerREADCYCLECOUNTER(Op, DAG);
7394   }
7395 }
7396
7397 void X86TargetLowering::
7398 ReplaceATOMIC_BINARY_64(SDNode *Node, SmallVectorImpl<SDValue>&Results,
7399                         SelectionDAG &DAG, unsigned NewOp) {
7400   EVT T = Node->getValueType(0);
7401   DebugLoc dl = Node->getDebugLoc();
7402   assert (T == MVT::i64 && "Only know how to expand i64 atomics");
7403
7404   SDValue Chain = Node->getOperand(0);
7405   SDValue In1 = Node->getOperand(1);
7406   SDValue In2L = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
7407                              Node->getOperand(2), DAG.getIntPtrConstant(0));
7408   SDValue In2H = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
7409                              Node->getOperand(2), DAG.getIntPtrConstant(1));
7410   SDValue Ops[] = { Chain, In1, In2L, In2H };
7411   SDVTList Tys = DAG.getVTList(MVT::i32, MVT::i32, MVT::Other);
7412   SDValue Result =
7413     DAG.getMemIntrinsicNode(NewOp, dl, Tys, Ops, 4, MVT::i64,
7414                             cast<MemSDNode>(Node)->getMemOperand());
7415   SDValue OpsF[] = { Result.getValue(0), Result.getValue(1)};
7416   Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, OpsF, 2));
7417   Results.push_back(Result.getValue(2));
7418 }
7419
7420 /// ReplaceNodeResults - Replace a node with an illegal result type
7421 /// with a new node built out of custom code.
7422 void X86TargetLowering::ReplaceNodeResults(SDNode *N,
7423                                            SmallVectorImpl<SDValue>&Results,
7424                                            SelectionDAG &DAG) {
7425   DebugLoc dl = N->getDebugLoc();
7426   switch (N->getOpcode()) {
7427   default:
7428     assert(false && "Do not know how to custom type legalize this operation!");
7429     return;
7430   case ISD::FP_TO_SINT: {
7431     std::pair<SDValue,SDValue> Vals =
7432         FP_TO_INTHelper(SDValue(N, 0), DAG, true);
7433     SDValue FIST = Vals.first, StackSlot = Vals.second;
7434     if (FIST.getNode() != 0) {
7435       EVT VT = N->getValueType(0);
7436       // Return a load from the stack slot.
7437       Results.push_back(DAG.getLoad(VT, dl, FIST, StackSlot, NULL, 0));
7438     }
7439     return;
7440   }
7441   case ISD::READCYCLECOUNTER: {
7442     SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Flag);
7443     SDValue TheChain = N->getOperand(0);
7444     SDValue rd = DAG.getNode(X86ISD::RDTSC_DAG, dl, Tys, &TheChain, 1);
7445     SDValue eax = DAG.getCopyFromReg(rd, dl, X86::EAX, MVT::i32,
7446                                      rd.getValue(1));
7447     SDValue edx = DAG.getCopyFromReg(eax.getValue(1), dl, X86::EDX, MVT::i32,
7448                                      eax.getValue(2));
7449     // Use a buildpair to merge the two 32-bit values into a 64-bit one.
7450     SDValue Ops[] = { eax, edx };
7451     Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Ops, 2));
7452     Results.push_back(edx.getValue(1));
7453     return;
7454   }
7455   case ISD::SDIV:
7456   case ISD::UDIV:
7457   case ISD::SREM:
7458   case ISD::UREM: {
7459     EVT WidenVT = getTypeToTransformTo(*DAG.getContext(), N->getValueType(0));
7460     Results.push_back(DAG.UnrollVectorOp(N, WidenVT.getVectorNumElements()));
7461     return;
7462   }
7463   case ISD::ATOMIC_CMP_SWAP: {
7464     EVT T = N->getValueType(0);
7465     assert (T == MVT::i64 && "Only know how to expand i64 Cmp and Swap");
7466     SDValue cpInL, cpInH;
7467     cpInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(2),
7468                         DAG.getConstant(0, MVT::i32));
7469     cpInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(2),
7470                         DAG.getConstant(1, MVT::i32));
7471     cpInL = DAG.getCopyToReg(N->getOperand(0), dl, X86::EAX, cpInL, SDValue());
7472     cpInH = DAG.getCopyToReg(cpInL.getValue(0), dl, X86::EDX, cpInH,
7473                              cpInL.getValue(1));
7474     SDValue swapInL, swapInH;
7475     swapInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(3),
7476                           DAG.getConstant(0, MVT::i32));
7477     swapInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(3),
7478                           DAG.getConstant(1, MVT::i32));
7479     swapInL = DAG.getCopyToReg(cpInH.getValue(0), dl, X86::EBX, swapInL,
7480                                cpInH.getValue(1));
7481     swapInH = DAG.getCopyToReg(swapInL.getValue(0), dl, X86::ECX, swapInH,
7482                                swapInL.getValue(1));
7483     SDValue Ops[] = { swapInH.getValue(0),
7484                       N->getOperand(1),
7485                       swapInH.getValue(1) };
7486     SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Flag);
7487     SDValue Result = DAG.getNode(X86ISD::LCMPXCHG8_DAG, dl, Tys, Ops, 3);
7488     SDValue cpOutL = DAG.getCopyFromReg(Result.getValue(0), dl, X86::EAX,
7489                                         MVT::i32, Result.getValue(1));
7490     SDValue cpOutH = DAG.getCopyFromReg(cpOutL.getValue(1), dl, X86::EDX,
7491                                         MVT::i32, cpOutL.getValue(2));
7492     SDValue OpsF[] = { cpOutL.getValue(0), cpOutH.getValue(0)};
7493     Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, OpsF, 2));
7494     Results.push_back(cpOutH.getValue(1));
7495     return;
7496   }
7497   case ISD::ATOMIC_LOAD_ADD:
7498     ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMADD64_DAG);
7499     return;
7500   case ISD::ATOMIC_LOAD_AND:
7501     ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMAND64_DAG);
7502     return;
7503   case ISD::ATOMIC_LOAD_NAND:
7504     ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMNAND64_DAG);
7505     return;
7506   case ISD::ATOMIC_LOAD_OR:
7507     ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMOR64_DAG);
7508     return;
7509   case ISD::ATOMIC_LOAD_SUB:
7510     ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMSUB64_DAG);
7511     return;
7512   case ISD::ATOMIC_LOAD_XOR:
7513     ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMXOR64_DAG);
7514     return;
7515   case ISD::ATOMIC_SWAP:
7516     ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMSWAP64_DAG);
7517     return;
7518   }
7519 }
7520
7521 const char *X86TargetLowering::getTargetNodeName(unsigned Opcode) const {
7522   switch (Opcode) {
7523   default: return NULL;
7524   case X86ISD::BSF:                return "X86ISD::BSF";
7525   case X86ISD::BSR:                return "X86ISD::BSR";
7526   case X86ISD::SHLD:               return "X86ISD::SHLD";
7527   case X86ISD::SHRD:               return "X86ISD::SHRD";
7528   case X86ISD::FAND:               return "X86ISD::FAND";
7529   case X86ISD::FOR:                return "X86ISD::FOR";
7530   case X86ISD::FXOR:               return "X86ISD::FXOR";
7531   case X86ISD::FSRL:               return "X86ISD::FSRL";
7532   case X86ISD::FILD:               return "X86ISD::FILD";
7533   case X86ISD::FILD_FLAG:          return "X86ISD::FILD_FLAG";
7534   case X86ISD::FP_TO_INT16_IN_MEM: return "X86ISD::FP_TO_INT16_IN_MEM";
7535   case X86ISD::FP_TO_INT32_IN_MEM: return "X86ISD::FP_TO_INT32_IN_MEM";
7536   case X86ISD::FP_TO_INT64_IN_MEM: return "X86ISD::FP_TO_INT64_IN_MEM";
7537   case X86ISD::FLD:                return "X86ISD::FLD";
7538   case X86ISD::FST:                return "X86ISD::FST";
7539   case X86ISD::CALL:               return "X86ISD::CALL";
7540   case X86ISD::RDTSC_DAG:          return "X86ISD::RDTSC_DAG";
7541   case X86ISD::BT:                 return "X86ISD::BT";
7542   case X86ISD::CMP:                return "X86ISD::CMP";
7543   case X86ISD::COMI:               return "X86ISD::COMI";
7544   case X86ISD::UCOMI:              return "X86ISD::UCOMI";
7545   case X86ISD::SETCC:              return "X86ISD::SETCC";
7546   case X86ISD::SETCC_CARRY:        return "X86ISD::SETCC_CARRY";
7547   case X86ISD::CMOV:               return "X86ISD::CMOV";
7548   case X86ISD::BRCOND:             return "X86ISD::BRCOND";
7549   case X86ISD::RET_FLAG:           return "X86ISD::RET_FLAG";
7550   case X86ISD::REP_STOS:           return "X86ISD::REP_STOS";
7551   case X86ISD::REP_MOVS:           return "X86ISD::REP_MOVS";
7552   case X86ISD::GlobalBaseReg:      return "X86ISD::GlobalBaseReg";
7553   case X86ISD::Wrapper:            return "X86ISD::Wrapper";
7554   case X86ISD::WrapperRIP:         return "X86ISD::WrapperRIP";
7555   case X86ISD::PEXTRB:             return "X86ISD::PEXTRB";
7556   case X86ISD::PEXTRW:             return "X86ISD::PEXTRW";
7557   case X86ISD::INSERTPS:           return "X86ISD::INSERTPS";
7558   case X86ISD::PINSRB:             return "X86ISD::PINSRB";
7559   case X86ISD::PINSRW:             return "X86ISD::PINSRW";
7560   case X86ISD::PSHUFB:             return "X86ISD::PSHUFB";
7561   case X86ISD::FMAX:               return "X86ISD::FMAX";
7562   case X86ISD::FMIN:               return "X86ISD::FMIN";
7563   case X86ISD::FRSQRT:             return "X86ISD::FRSQRT";
7564   case X86ISD::FRCP:               return "X86ISD::FRCP";
7565   case X86ISD::TLSADDR:            return "X86ISD::TLSADDR";
7566   case X86ISD::SegmentBaseAddress: return "X86ISD::SegmentBaseAddress";
7567   case X86ISD::EH_RETURN:          return "X86ISD::EH_RETURN";
7568   case X86ISD::TC_RETURN:          return "X86ISD::TC_RETURN";
7569   case X86ISD::FNSTCW16m:          return "X86ISD::FNSTCW16m";
7570   case X86ISD::LCMPXCHG_DAG:       return "X86ISD::LCMPXCHG_DAG";
7571   case X86ISD::LCMPXCHG8_DAG:      return "X86ISD::LCMPXCHG8_DAG";
7572   case X86ISD::ATOMADD64_DAG:      return "X86ISD::ATOMADD64_DAG";
7573   case X86ISD::ATOMSUB64_DAG:      return "X86ISD::ATOMSUB64_DAG";
7574   case X86ISD::ATOMOR64_DAG:       return "X86ISD::ATOMOR64_DAG";
7575   case X86ISD::ATOMXOR64_DAG:      return "X86ISD::ATOMXOR64_DAG";
7576   case X86ISD::ATOMAND64_DAG:      return "X86ISD::ATOMAND64_DAG";
7577   case X86ISD::ATOMNAND64_DAG:     return "X86ISD::ATOMNAND64_DAG";
7578   case X86ISD::VZEXT_MOVL:         return "X86ISD::VZEXT_MOVL";
7579   case X86ISD::VZEXT_LOAD:         return "X86ISD::VZEXT_LOAD";
7580   case X86ISD::VSHL:               return "X86ISD::VSHL";
7581   case X86ISD::VSRL:               return "X86ISD::VSRL";
7582   case X86ISD::CMPPD:              return "X86ISD::CMPPD";
7583   case X86ISD::CMPPS:              return "X86ISD::CMPPS";
7584   case X86ISD::PCMPEQB:            return "X86ISD::PCMPEQB";
7585   case X86ISD::PCMPEQW:            return "X86ISD::PCMPEQW";
7586   case X86ISD::PCMPEQD:            return "X86ISD::PCMPEQD";
7587   case X86ISD::PCMPEQQ:            return "X86ISD::PCMPEQQ";
7588   case X86ISD::PCMPGTB:            return "X86ISD::PCMPGTB";
7589   case X86ISD::PCMPGTW:            return "X86ISD::PCMPGTW";
7590   case X86ISD::PCMPGTD:            return "X86ISD::PCMPGTD";
7591   case X86ISD::PCMPGTQ:            return "X86ISD::PCMPGTQ";
7592   case X86ISD::ADD:                return "X86ISD::ADD";
7593   case X86ISD::SUB:                return "X86ISD::SUB";
7594   case X86ISD::SMUL:               return "X86ISD::SMUL";
7595   case X86ISD::UMUL:               return "X86ISD::UMUL";
7596   case X86ISD::INC:                return "X86ISD::INC";
7597   case X86ISD::DEC:                return "X86ISD::DEC";
7598   case X86ISD::OR:                 return "X86ISD::OR";
7599   case X86ISD::XOR:                return "X86ISD::XOR";
7600   case X86ISD::AND:                return "X86ISD::AND";
7601   case X86ISD::MUL_IMM:            return "X86ISD::MUL_IMM";
7602   case X86ISD::PTEST:              return "X86ISD::PTEST";
7603   case X86ISD::VASTART_SAVE_XMM_REGS: return "X86ISD::VASTART_SAVE_XMM_REGS";
7604   }
7605 }
7606
7607 // isLegalAddressingMode - Return true if the addressing mode represented
7608 // by AM is legal for this target, for a load/store of the specified type.
7609 bool X86TargetLowering::isLegalAddressingMode(const AddrMode &AM,
7610                                               const Type *Ty) const {
7611   // X86 supports extremely general addressing modes.
7612   CodeModel::Model M = getTargetMachine().getCodeModel();
7613
7614   // X86 allows a sign-extended 32-bit immediate field as a displacement.
7615   if (!X86::isOffsetSuitableForCodeModel(AM.BaseOffs, M, AM.BaseGV != NULL))
7616     return false;
7617
7618   if (AM.BaseGV) {
7619     unsigned GVFlags =
7620       Subtarget->ClassifyGlobalReference(AM.BaseGV, getTargetMachine());
7621
7622     // If a reference to this global requires an extra load, we can't fold it.
7623     if (isGlobalStubReference(GVFlags))
7624       return false;
7625
7626     // If BaseGV requires a register for the PIC base, we cannot also have a
7627     // BaseReg specified.
7628     if (AM.HasBaseReg && isGlobalRelativeToPICBase(GVFlags))
7629       return false;
7630
7631     // If lower 4G is not available, then we must use rip-relative addressing.
7632     if (Subtarget->is64Bit() && (AM.BaseOffs || AM.Scale > 1))
7633       return false;
7634   }
7635
7636   switch (AM.Scale) {
7637   case 0:
7638   case 1:
7639   case 2:
7640   case 4:
7641   case 8:
7642     // These scales always work.
7643     break;
7644   case 3:
7645   case 5:
7646   case 9:
7647     // These scales are formed with basereg+scalereg.  Only accept if there is
7648     // no basereg yet.
7649     if (AM.HasBaseReg)
7650       return false;
7651     break;
7652   default:  // Other stuff never works.
7653     return false;
7654   }
7655
7656   return true;
7657 }
7658
7659
7660 bool X86TargetLowering::isTruncateFree(const Type *Ty1, const Type *Ty2) const {
7661   if (!Ty1->isInteger() || !Ty2->isInteger())
7662     return false;
7663   unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
7664   unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
7665   if (NumBits1 <= NumBits2)
7666     return false;
7667   return Subtarget->is64Bit() || NumBits1 < 64;
7668 }
7669
7670 bool X86TargetLowering::isTruncateFree(EVT VT1, EVT VT2) const {
7671   if (!VT1.isInteger() || !VT2.isInteger())
7672     return false;
7673   unsigned NumBits1 = VT1.getSizeInBits();
7674   unsigned NumBits2 = VT2.getSizeInBits();
7675   if (NumBits1 <= NumBits2)
7676     return false;
7677   return Subtarget->is64Bit() || NumBits1 < 64;
7678 }
7679
7680 bool X86TargetLowering::isZExtFree(const Type *Ty1, const Type *Ty2) const {
7681   // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
7682   return Ty1->isInteger(32) && Ty2->isInteger(64) && Subtarget->is64Bit();
7683 }
7684
7685 bool X86TargetLowering::isZExtFree(EVT VT1, EVT VT2) const {
7686   // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
7687   return VT1 == MVT::i32 && VT2 == MVT::i64 && Subtarget->is64Bit();
7688 }
7689
7690 bool X86TargetLowering::isNarrowingProfitable(EVT VT1, EVT VT2) const {
7691   // i16 instructions are longer (0x66 prefix) and potentially slower.
7692   return !(VT1 == MVT::i32 && VT2 == MVT::i16);
7693 }
7694
7695 /// isShuffleMaskLegal - Targets can use this to indicate that they only
7696 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
7697 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
7698 /// are assumed to be legal.
7699 bool
7700 X86TargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M,
7701                                       EVT VT) const {
7702   // Only do shuffles on 128-bit vector types for now.
7703   if (VT.getSizeInBits() == 64)
7704     return false;
7705
7706   // FIXME: pshufb, blends, shifts.
7707   return (VT.getVectorNumElements() == 2 ||
7708           ShuffleVectorSDNode::isSplatMask(&M[0], VT) ||
7709           isMOVLMask(M, VT) ||
7710           isSHUFPMask(M, VT) ||
7711           isPSHUFDMask(M, VT) ||
7712           isPSHUFHWMask(M, VT) ||
7713           isPSHUFLWMask(M, VT) ||
7714           isPALIGNRMask(M, VT, Subtarget->hasSSSE3()) ||
7715           isUNPCKLMask(M, VT) ||
7716           isUNPCKHMask(M, VT) ||
7717           isUNPCKL_v_undef_Mask(M, VT) ||
7718           isUNPCKH_v_undef_Mask(M, VT));
7719 }
7720
7721 bool
7722 X86TargetLowering::isVectorClearMaskLegal(const SmallVectorImpl<int> &Mask,
7723                                           EVT VT) const {
7724   unsigned NumElts = VT.getVectorNumElements();
7725   // FIXME: This collection of masks seems suspect.
7726   if (NumElts == 2)
7727     return true;
7728   if (NumElts == 4 && VT.getSizeInBits() == 128) {
7729     return (isMOVLMask(Mask, VT)  ||
7730             isCommutedMOVLMask(Mask, VT, true) ||
7731             isSHUFPMask(Mask, VT) ||
7732             isCommutedSHUFPMask(Mask, VT));
7733   }
7734   return false;
7735 }
7736
7737 //===----------------------------------------------------------------------===//
7738 //                           X86 Scheduler Hooks
7739 //===----------------------------------------------------------------------===//
7740
7741 // private utility function
7742 MachineBasicBlock *
7743 X86TargetLowering::EmitAtomicBitwiseWithCustomInserter(MachineInstr *bInstr,
7744                                                        MachineBasicBlock *MBB,
7745                                                        unsigned regOpc,
7746                                                        unsigned immOpc,
7747                                                        unsigned LoadOpc,
7748                                                        unsigned CXchgOpc,
7749                                                        unsigned copyOpc,
7750                                                        unsigned notOpc,
7751                                                        unsigned EAXreg,
7752                                                        TargetRegisterClass *RC,
7753                                                        bool invSrc) const {
7754   // For the atomic bitwise operator, we generate
7755   //   thisMBB:
7756   //   newMBB:
7757   //     ld  t1 = [bitinstr.addr]
7758   //     op  t2 = t1, [bitinstr.val]
7759   //     mov EAX = t1
7760   //     lcs dest = [bitinstr.addr], t2  [EAX is implicit]
7761   //     bz  newMBB
7762   //     fallthrough -->nextMBB
7763   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
7764   const BasicBlock *LLVM_BB = MBB->getBasicBlock();
7765   MachineFunction::iterator MBBIter = MBB;
7766   ++MBBIter;
7767
7768   /// First build the CFG
7769   MachineFunction *F = MBB->getParent();
7770   MachineBasicBlock *thisMBB = MBB;
7771   MachineBasicBlock *newMBB = F->CreateMachineBasicBlock(LLVM_BB);
7772   MachineBasicBlock *nextMBB = F->CreateMachineBasicBlock(LLVM_BB);
7773   F->insert(MBBIter, newMBB);
7774   F->insert(MBBIter, nextMBB);
7775
7776   // Move all successors to thisMBB to nextMBB
7777   nextMBB->transferSuccessors(thisMBB);
7778
7779   // Update thisMBB to fall through to newMBB
7780   thisMBB->addSuccessor(newMBB);
7781
7782   // newMBB jumps to itself and fall through to nextMBB
7783   newMBB->addSuccessor(nextMBB);
7784   newMBB->addSuccessor(newMBB);
7785
7786   // Insert instructions into newMBB based on incoming instruction
7787   assert(bInstr->getNumOperands() < X86AddrNumOperands + 4 &&
7788          "unexpected number of operands");
7789   DebugLoc dl = bInstr->getDebugLoc();
7790   MachineOperand& destOper = bInstr->getOperand(0);
7791   MachineOperand* argOpers[2 + X86AddrNumOperands];
7792   int numArgs = bInstr->getNumOperands() - 1;
7793   for (int i=0; i < numArgs; ++i)
7794     argOpers[i] = &bInstr->getOperand(i+1);
7795
7796   // x86 address has 4 operands: base, index, scale, and displacement
7797   int lastAddrIndx = X86AddrNumOperands - 1; // [0,3]
7798   int valArgIndx = lastAddrIndx + 1;
7799
7800   unsigned t1 = F->getRegInfo().createVirtualRegister(RC);
7801   MachineInstrBuilder MIB = BuildMI(newMBB, dl, TII->get(LoadOpc), t1);
7802   for (int i=0; i <= lastAddrIndx; ++i)
7803     (*MIB).addOperand(*argOpers[i]);
7804
7805   unsigned tt = F->getRegInfo().createVirtualRegister(RC);
7806   if (invSrc) {
7807     MIB = BuildMI(newMBB, dl, TII->get(notOpc), tt).addReg(t1);
7808   }
7809   else
7810     tt = t1;
7811
7812   unsigned t2 = F->getRegInfo().createVirtualRegister(RC);
7813   assert((argOpers[valArgIndx]->isReg() ||
7814           argOpers[valArgIndx]->isImm()) &&
7815          "invalid operand");
7816   if (argOpers[valArgIndx]->isReg())
7817     MIB = BuildMI(newMBB, dl, TII->get(regOpc), t2);
7818   else
7819     MIB = BuildMI(newMBB, dl, TII->get(immOpc), t2);
7820   MIB.addReg(tt);
7821   (*MIB).addOperand(*argOpers[valArgIndx]);
7822
7823   MIB = BuildMI(newMBB, dl, TII->get(copyOpc), EAXreg);
7824   MIB.addReg(t1);
7825
7826   MIB = BuildMI(newMBB, dl, TII->get(CXchgOpc));
7827   for (int i=0; i <= lastAddrIndx; ++i)
7828     (*MIB).addOperand(*argOpers[i]);
7829   MIB.addReg(t2);
7830   assert(bInstr->hasOneMemOperand() && "Unexpected number of memoperand");
7831   (*MIB).setMemRefs(bInstr->memoperands_begin(),
7832                     bInstr->memoperands_end());
7833
7834   MIB = BuildMI(newMBB, dl, TII->get(copyOpc), destOper.getReg());
7835   MIB.addReg(EAXreg);
7836
7837   // insert branch
7838   BuildMI(newMBB, dl, TII->get(X86::JNE)).addMBB(newMBB);
7839
7840   F->DeleteMachineInstr(bInstr);   // The pseudo instruction is gone now.
7841   return nextMBB;
7842 }
7843
7844 // private utility function:  64 bit atomics on 32 bit host.
7845 MachineBasicBlock *
7846 X86TargetLowering::EmitAtomicBit6432WithCustomInserter(MachineInstr *bInstr,
7847                                                        MachineBasicBlock *MBB,
7848                                                        unsigned regOpcL,
7849                                                        unsigned regOpcH,
7850                                                        unsigned immOpcL,
7851                                                        unsigned immOpcH,
7852                                                        bool invSrc) const {
7853   // For the atomic bitwise operator, we generate
7854   //   thisMBB (instructions are in pairs, except cmpxchg8b)
7855   //     ld t1,t2 = [bitinstr.addr]
7856   //   newMBB:
7857   //     out1, out2 = phi (thisMBB, t1/t2) (newMBB, t3/t4)
7858   //     op  t5, t6 <- out1, out2, [bitinstr.val]
7859   //      (for SWAP, substitute:  mov t5, t6 <- [bitinstr.val])
7860   //     mov ECX, EBX <- t5, t6
7861   //     mov EAX, EDX <- t1, t2
7862   //     cmpxchg8b [bitinstr.addr]  [EAX, EDX, EBX, ECX implicit]
7863   //     mov t3, t4 <- EAX, EDX
7864   //     bz  newMBB
7865   //     result in out1, out2
7866   //     fallthrough -->nextMBB
7867
7868   const TargetRegisterClass *RC = X86::GR32RegisterClass;
7869   const unsigned LoadOpc = X86::MOV32rm;
7870   const unsigned copyOpc = X86::MOV32rr;
7871   const unsigned NotOpc = X86::NOT32r;
7872   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
7873   const BasicBlock *LLVM_BB = MBB->getBasicBlock();
7874   MachineFunction::iterator MBBIter = MBB;
7875   ++MBBIter;
7876
7877   /// First build the CFG
7878   MachineFunction *F = MBB->getParent();
7879   MachineBasicBlock *thisMBB = MBB;
7880   MachineBasicBlock *newMBB = F->CreateMachineBasicBlock(LLVM_BB);
7881   MachineBasicBlock *nextMBB = F->CreateMachineBasicBlock(LLVM_BB);
7882   F->insert(MBBIter, newMBB);
7883   F->insert(MBBIter, nextMBB);
7884
7885   // Move all successors to thisMBB to nextMBB
7886   nextMBB->transferSuccessors(thisMBB);
7887
7888   // Update thisMBB to fall through to newMBB
7889   thisMBB->addSuccessor(newMBB);
7890
7891   // newMBB jumps to itself and fall through to nextMBB
7892   newMBB->addSuccessor(nextMBB);
7893   newMBB->addSuccessor(newMBB);
7894
7895   DebugLoc dl = bInstr->getDebugLoc();
7896   // Insert instructions into newMBB based on incoming instruction
7897   // There are 8 "real" operands plus 9 implicit def/uses, ignored here.
7898   assert(bInstr->getNumOperands() < X86AddrNumOperands + 14 &&
7899          "unexpected number of operands");
7900   MachineOperand& dest1Oper = bInstr->getOperand(0);
7901   MachineOperand& dest2Oper = bInstr->getOperand(1);
7902   MachineOperand* argOpers[2 + X86AddrNumOperands];
7903   for (int i=0; i < 2 + X86AddrNumOperands; ++i)
7904     argOpers[i] = &bInstr->getOperand(i+2);
7905
7906   // x86 address has 5 operands: base, index, scale, displacement, and segment.
7907   int lastAddrIndx = X86AddrNumOperands - 1; // [0,3]
7908
7909   unsigned t1 = F->getRegInfo().createVirtualRegister(RC);
7910   MachineInstrBuilder MIB = BuildMI(thisMBB, dl, TII->get(LoadOpc), t1);
7911   for (int i=0; i <= lastAddrIndx; ++i)
7912     (*MIB).addOperand(*argOpers[i]);
7913   unsigned t2 = F->getRegInfo().createVirtualRegister(RC);
7914   MIB = BuildMI(thisMBB, dl, TII->get(LoadOpc), t2);
7915   // add 4 to displacement.
7916   for (int i=0; i <= lastAddrIndx-2; ++i)
7917     (*MIB).addOperand(*argOpers[i]);
7918   MachineOperand newOp3 = *(argOpers[3]);
7919   if (newOp3.isImm())
7920     newOp3.setImm(newOp3.getImm()+4);
7921   else
7922     newOp3.setOffset(newOp3.getOffset()+4);
7923   (*MIB).addOperand(newOp3);
7924   (*MIB).addOperand(*argOpers[lastAddrIndx]);
7925
7926   // t3/4 are defined later, at the bottom of the loop
7927   unsigned t3 = F->getRegInfo().createVirtualRegister(RC);
7928   unsigned t4 = F->getRegInfo().createVirtualRegister(RC);
7929   BuildMI(newMBB, dl, TII->get(X86::PHI), dest1Oper.getReg())
7930     .addReg(t1).addMBB(thisMBB).addReg(t3).addMBB(newMBB);
7931   BuildMI(newMBB, dl, TII->get(X86::PHI), dest2Oper.getReg())
7932     .addReg(t2).addMBB(thisMBB).addReg(t4).addMBB(newMBB);
7933
7934   // The subsequent operations should be using the destination registers of
7935   //the PHI instructions.
7936   if (invSrc) {
7937     t1 = F->getRegInfo().createVirtualRegister(RC);
7938     t2 = F->getRegInfo().createVirtualRegister(RC);
7939     MIB = BuildMI(newMBB, dl, TII->get(NotOpc), t1).addReg(dest1Oper.getReg());
7940     MIB = BuildMI(newMBB, dl, TII->get(NotOpc), t2).addReg(dest2Oper.getReg());
7941   } else {
7942     t1 = dest1Oper.getReg();
7943     t2 = dest2Oper.getReg();
7944   }
7945
7946   int valArgIndx = lastAddrIndx + 1;
7947   assert((argOpers[valArgIndx]->isReg() ||
7948           argOpers[valArgIndx]->isImm()) &&
7949          "invalid operand");
7950   unsigned t5 = F->getRegInfo().createVirtualRegister(RC);
7951   unsigned t6 = F->getRegInfo().createVirtualRegister(RC);
7952   if (argOpers[valArgIndx]->isReg())
7953     MIB = BuildMI(newMBB, dl, TII->get(regOpcL), t5);
7954   else
7955     MIB = BuildMI(newMBB, dl, TII->get(immOpcL), t5);
7956   if (regOpcL != X86::MOV32rr)
7957     MIB.addReg(t1);
7958   (*MIB).addOperand(*argOpers[valArgIndx]);
7959   assert(argOpers[valArgIndx + 1]->isReg() ==
7960          argOpers[valArgIndx]->isReg());
7961   assert(argOpers[valArgIndx + 1]->isImm() ==
7962          argOpers[valArgIndx]->isImm());
7963   if (argOpers[valArgIndx + 1]->isReg())
7964     MIB = BuildMI(newMBB, dl, TII->get(regOpcH), t6);
7965   else
7966     MIB = BuildMI(newMBB, dl, TII->get(immOpcH), t6);
7967   if (regOpcH != X86::MOV32rr)
7968     MIB.addReg(t2);
7969   (*MIB).addOperand(*argOpers[valArgIndx + 1]);
7970
7971   MIB = BuildMI(newMBB, dl, TII->get(copyOpc), X86::EAX);
7972   MIB.addReg(t1);
7973   MIB = BuildMI(newMBB, dl, TII->get(copyOpc), X86::EDX);
7974   MIB.addReg(t2);
7975
7976   MIB = BuildMI(newMBB, dl, TII->get(copyOpc), X86::EBX);
7977   MIB.addReg(t5);
7978   MIB = BuildMI(newMBB, dl, TII->get(copyOpc), X86::ECX);
7979   MIB.addReg(t6);
7980
7981   MIB = BuildMI(newMBB, dl, TII->get(X86::LCMPXCHG8B));
7982   for (int i=0; i <= lastAddrIndx; ++i)
7983     (*MIB).addOperand(*argOpers[i]);
7984
7985   assert(bInstr->hasOneMemOperand() && "Unexpected number of memoperand");
7986   (*MIB).setMemRefs(bInstr->memoperands_begin(),
7987                     bInstr->memoperands_end());
7988
7989   MIB = BuildMI(newMBB, dl, TII->get(copyOpc), t3);
7990   MIB.addReg(X86::EAX);
7991   MIB = BuildMI(newMBB, dl, TII->get(copyOpc), t4);
7992   MIB.addReg(X86::EDX);
7993
7994   // insert branch
7995   BuildMI(newMBB, dl, TII->get(X86::JNE)).addMBB(newMBB);
7996
7997   F->DeleteMachineInstr(bInstr);   // The pseudo instruction is gone now.
7998   return nextMBB;
7999 }
8000
8001 // private utility function
8002 MachineBasicBlock *
8003 X86TargetLowering::EmitAtomicMinMaxWithCustomInserter(MachineInstr *mInstr,
8004                                                       MachineBasicBlock *MBB,
8005                                                       unsigned cmovOpc) const {
8006   // For the atomic min/max operator, we generate
8007   //   thisMBB:
8008   //   newMBB:
8009   //     ld t1 = [min/max.addr]
8010   //     mov t2 = [min/max.val]
8011   //     cmp  t1, t2
8012   //     cmov[cond] t2 = t1
8013   //     mov EAX = t1
8014   //     lcs dest = [bitinstr.addr], t2  [EAX is implicit]
8015   //     bz   newMBB
8016   //     fallthrough -->nextMBB
8017   //
8018   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
8019   const BasicBlock *LLVM_BB = MBB->getBasicBlock();
8020   MachineFunction::iterator MBBIter = MBB;
8021   ++MBBIter;
8022
8023   /// First build the CFG
8024   MachineFunction *F = MBB->getParent();
8025   MachineBasicBlock *thisMBB = MBB;
8026   MachineBasicBlock *newMBB = F->CreateMachineBasicBlock(LLVM_BB);
8027   MachineBasicBlock *nextMBB = F->CreateMachineBasicBlock(LLVM_BB);
8028   F->insert(MBBIter, newMBB);
8029   F->insert(MBBIter, nextMBB);
8030
8031   // Move all successors of thisMBB to nextMBB
8032   nextMBB->transferSuccessors(thisMBB);
8033
8034   // Update thisMBB to fall through to newMBB
8035   thisMBB->addSuccessor(newMBB);
8036
8037   // newMBB jumps to newMBB and fall through to nextMBB
8038   newMBB->addSuccessor(nextMBB);
8039   newMBB->addSuccessor(newMBB);
8040
8041   DebugLoc dl = mInstr->getDebugLoc();
8042   // Insert instructions into newMBB based on incoming instruction
8043   assert(mInstr->getNumOperands() < X86AddrNumOperands + 4 &&
8044          "unexpected number of operands");
8045   MachineOperand& destOper = mInstr->getOperand(0);
8046   MachineOperand* argOpers[2 + X86AddrNumOperands];
8047   int numArgs = mInstr->getNumOperands() - 1;
8048   for (int i=0; i < numArgs; ++i)
8049     argOpers[i] = &mInstr->getOperand(i+1);
8050
8051   // x86 address has 4 operands: base, index, scale, and displacement
8052   int lastAddrIndx = X86AddrNumOperands - 1; // [0,3]
8053   int valArgIndx = lastAddrIndx + 1;
8054
8055   unsigned t1 = F->getRegInfo().createVirtualRegister(X86::GR32RegisterClass);
8056   MachineInstrBuilder MIB = BuildMI(newMBB, dl, TII->get(X86::MOV32rm), t1);
8057   for (int i=0; i <= lastAddrIndx; ++i)
8058     (*MIB).addOperand(*argOpers[i]);
8059
8060   // We only support register and immediate values
8061   assert((argOpers[valArgIndx]->isReg() ||
8062           argOpers[valArgIndx]->isImm()) &&
8063          "invalid operand");
8064
8065   unsigned t2 = F->getRegInfo().createVirtualRegister(X86::GR32RegisterClass);
8066   if (argOpers[valArgIndx]->isReg())
8067     MIB = BuildMI(newMBB, dl, TII->get(X86::MOV32rr), t2);
8068   else
8069     MIB = BuildMI(newMBB, dl, TII->get(X86::MOV32rr), t2);
8070   (*MIB).addOperand(*argOpers[valArgIndx]);
8071
8072   MIB = BuildMI(newMBB, dl, TII->get(X86::MOV32rr), X86::EAX);
8073   MIB.addReg(t1);
8074
8075   MIB = BuildMI(newMBB, dl, TII->get(X86::CMP32rr));
8076   MIB.addReg(t1);
8077   MIB.addReg(t2);
8078
8079   // Generate movc
8080   unsigned t3 = F->getRegInfo().createVirtualRegister(X86::GR32RegisterClass);
8081   MIB = BuildMI(newMBB, dl, TII->get(cmovOpc),t3);
8082   MIB.addReg(t2);
8083   MIB.addReg(t1);
8084
8085   // Cmp and exchange if none has modified the memory location
8086   MIB = BuildMI(newMBB, dl, TII->get(X86::LCMPXCHG32));
8087   for (int i=0; i <= lastAddrIndx; ++i)
8088     (*MIB).addOperand(*argOpers[i]);
8089   MIB.addReg(t3);
8090   assert(mInstr->hasOneMemOperand() && "Unexpected number of memoperand");
8091   (*MIB).setMemRefs(mInstr->memoperands_begin(),
8092                     mInstr->memoperands_end());
8093
8094   MIB = BuildMI(newMBB, dl, TII->get(X86::MOV32rr), destOper.getReg());
8095   MIB.addReg(X86::EAX);
8096
8097   // insert branch
8098   BuildMI(newMBB, dl, TII->get(X86::JNE)).addMBB(newMBB);
8099
8100   F->DeleteMachineInstr(mInstr);   // The pseudo instruction is gone now.
8101   return nextMBB;
8102 }
8103
8104 // FIXME: When we get size specific XMM0 registers, i.e. XMM0_V16I8
8105 // all of this code can be replaced with that in the .td file.
8106 MachineBasicBlock *
8107 X86TargetLowering::EmitPCMP(MachineInstr *MI, MachineBasicBlock *BB,
8108                             unsigned numArgs, bool memArg) const {
8109
8110   MachineFunction *F = BB->getParent();
8111   DebugLoc dl = MI->getDebugLoc();
8112   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
8113
8114   unsigned Opc;
8115   if (memArg)
8116     Opc = numArgs == 3 ? X86::PCMPISTRM128rm : X86::PCMPESTRM128rm;
8117   else
8118     Opc = numArgs == 3 ? X86::PCMPISTRM128rr : X86::PCMPESTRM128rr;
8119
8120   MachineInstrBuilder MIB = BuildMI(BB, dl, TII->get(Opc));
8121
8122   for (unsigned i = 0; i < numArgs; ++i) {
8123     MachineOperand &Op = MI->getOperand(i+1);
8124
8125     if (!(Op.isReg() && Op.isImplicit()))
8126       MIB.addOperand(Op);
8127   }
8128
8129   BuildMI(BB, dl, TII->get(X86::MOVAPSrr), MI->getOperand(0).getReg())
8130     .addReg(X86::XMM0);
8131
8132   F->DeleteMachineInstr(MI);
8133
8134   return BB;
8135 }
8136
8137 MachineBasicBlock *
8138 X86TargetLowering::EmitVAStartSaveXMMRegsWithCustomInserter(
8139                                                  MachineInstr *MI,
8140                                                  MachineBasicBlock *MBB) const {
8141   // Emit code to save XMM registers to the stack. The ABI says that the
8142   // number of registers to save is given in %al, so it's theoretically
8143   // possible to do an indirect jump trick to avoid saving all of them,
8144   // however this code takes a simpler approach and just executes all
8145   // of the stores if %al is non-zero. It's less code, and it's probably
8146   // easier on the hardware branch predictor, and stores aren't all that
8147   // expensive anyway.
8148
8149   // Create the new basic blocks. One block contains all the XMM stores,
8150   // and one block is the final destination regardless of whether any
8151   // stores were performed.
8152   const BasicBlock *LLVM_BB = MBB->getBasicBlock();
8153   MachineFunction *F = MBB->getParent();
8154   MachineFunction::iterator MBBIter = MBB;
8155   ++MBBIter;
8156   MachineBasicBlock *XMMSaveMBB = F->CreateMachineBasicBlock(LLVM_BB);
8157   MachineBasicBlock *EndMBB = F->CreateMachineBasicBlock(LLVM_BB);
8158   F->insert(MBBIter, XMMSaveMBB);
8159   F->insert(MBBIter, EndMBB);
8160
8161   // Set up the CFG.
8162   // Move any original successors of MBB to the end block.
8163   EndMBB->transferSuccessors(MBB);
8164   // The original block will now fall through to the XMM save block.
8165   MBB->addSuccessor(XMMSaveMBB);
8166   // The XMMSaveMBB will fall through to the end block.
8167   XMMSaveMBB->addSuccessor(EndMBB);
8168
8169   // Now add the instructions.
8170   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
8171   DebugLoc DL = MI->getDebugLoc();
8172
8173   unsigned CountReg = MI->getOperand(0).getReg();
8174   int64_t RegSaveFrameIndex = MI->getOperand(1).getImm();
8175   int64_t VarArgsFPOffset = MI->getOperand(2).getImm();
8176
8177   if (!Subtarget->isTargetWin64()) {
8178     // If %al is 0, branch around the XMM save block.
8179     BuildMI(MBB, DL, TII->get(X86::TEST8rr)).addReg(CountReg).addReg(CountReg);
8180     BuildMI(MBB, DL, TII->get(X86::JE)).addMBB(EndMBB);
8181     MBB->addSuccessor(EndMBB);
8182   }
8183
8184   // In the XMM save block, save all the XMM argument registers.
8185   for (int i = 3, e = MI->getNumOperands(); i != e; ++i) {
8186     int64_t Offset = (i - 3) * 16 + VarArgsFPOffset;
8187     MachineMemOperand *MMO =
8188       F->getMachineMemOperand(
8189         PseudoSourceValue::getFixedStack(RegSaveFrameIndex),
8190         MachineMemOperand::MOStore, Offset,
8191         /*Size=*/16, /*Align=*/16);
8192     BuildMI(XMMSaveMBB, DL, TII->get(X86::MOVAPSmr))
8193       .addFrameIndex(RegSaveFrameIndex)
8194       .addImm(/*Scale=*/1)
8195       .addReg(/*IndexReg=*/0)
8196       .addImm(/*Disp=*/Offset)
8197       .addReg(/*Segment=*/0)
8198       .addReg(MI->getOperand(i).getReg())
8199       .addMemOperand(MMO);
8200   }
8201
8202   F->DeleteMachineInstr(MI);   // The pseudo instruction is gone now.
8203
8204   return EndMBB;
8205 }
8206
8207 MachineBasicBlock *
8208 X86TargetLowering::EmitLoweredSelect(MachineInstr *MI,
8209                                      MachineBasicBlock *BB,
8210                    DenseMap<MachineBasicBlock*, MachineBasicBlock*> *EM) const {
8211   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
8212   DebugLoc DL = MI->getDebugLoc();
8213
8214   // To "insert" a SELECT_CC instruction, we actually have to insert the
8215   // diamond control-flow pattern.  The incoming instruction knows the
8216   // destination vreg to set, the condition code register to branch on, the
8217   // true/false values to select between, and a branch opcode to use.
8218   const BasicBlock *LLVM_BB = BB->getBasicBlock();
8219   MachineFunction::iterator It = BB;
8220   ++It;
8221
8222   //  thisMBB:
8223   //  ...
8224   //   TrueVal = ...
8225   //   cmpTY ccX, r1, r2
8226   //   bCC copy1MBB
8227   //   fallthrough --> copy0MBB
8228   MachineBasicBlock *thisMBB = BB;
8229   MachineFunction *F = BB->getParent();
8230   MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
8231   MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
8232   unsigned Opc =
8233     X86::GetCondBranchFromCond((X86::CondCode)MI->getOperand(3).getImm());
8234   BuildMI(BB, DL, TII->get(Opc)).addMBB(sinkMBB);
8235   F->insert(It, copy0MBB);
8236   F->insert(It, sinkMBB);
8237   // Update machine-CFG edges by first adding all successors of the current
8238   // block to the new block which will contain the Phi node for the select.
8239   // Also inform sdisel of the edge changes.
8240   for (MachineBasicBlock::succ_iterator I = BB->succ_begin(),
8241          E = BB->succ_end(); I != E; ++I) {
8242     EM->insert(std::make_pair(*I, sinkMBB));
8243     sinkMBB->addSuccessor(*I);
8244   }
8245   // Next, remove all successors of the current block, and add the true
8246   // and fallthrough blocks as its successors.
8247   while (!BB->succ_empty())
8248     BB->removeSuccessor(BB->succ_begin());
8249   // Add the true and fallthrough blocks as its successors.
8250   BB->addSuccessor(copy0MBB);
8251   BB->addSuccessor(sinkMBB);
8252
8253   //  copy0MBB:
8254   //   %FalseValue = ...
8255   //   # fallthrough to sinkMBB
8256   BB = copy0MBB;
8257
8258   // Update machine-CFG edges
8259   BB->addSuccessor(sinkMBB);
8260
8261   //  sinkMBB:
8262   //   %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
8263   //  ...
8264   BB = sinkMBB;
8265   BuildMI(BB, DL, TII->get(X86::PHI), MI->getOperand(0).getReg())
8266     .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB)
8267     .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
8268
8269   F->DeleteMachineInstr(MI);   // The pseudo instruction is gone now.
8270   return BB;
8271 }
8272
8273
8274 MachineBasicBlock *
8275 X86TargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
8276                                                MachineBasicBlock *BB,
8277                    DenseMap<MachineBasicBlock*, MachineBasicBlock*> *EM) const {
8278   switch (MI->getOpcode()) {
8279   default: assert(false && "Unexpected instr type to insert");
8280   case X86::CMOV_GR8:
8281   case X86::CMOV_V1I64:
8282   case X86::CMOV_FR32:
8283   case X86::CMOV_FR64:
8284   case X86::CMOV_V4F32:
8285   case X86::CMOV_V2F64:
8286   case X86::CMOV_V2I64:
8287     return EmitLoweredSelect(MI, BB, EM);
8288
8289   case X86::FP32_TO_INT16_IN_MEM:
8290   case X86::FP32_TO_INT32_IN_MEM:
8291   case X86::FP32_TO_INT64_IN_MEM:
8292   case X86::FP64_TO_INT16_IN_MEM:
8293   case X86::FP64_TO_INT32_IN_MEM:
8294   case X86::FP64_TO_INT64_IN_MEM:
8295   case X86::FP80_TO_INT16_IN_MEM:
8296   case X86::FP80_TO_INT32_IN_MEM:
8297   case X86::FP80_TO_INT64_IN_MEM: {
8298     const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
8299     DebugLoc DL = MI->getDebugLoc();
8300
8301     // Change the floating point control register to use "round towards zero"
8302     // mode when truncating to an integer value.
8303     MachineFunction *F = BB->getParent();
8304     int CWFrameIdx = F->getFrameInfo()->CreateStackObject(2, 2, false);
8305     addFrameReference(BuildMI(BB, DL, TII->get(X86::FNSTCW16m)), CWFrameIdx);
8306
8307     // Load the old value of the high byte of the control word...
8308     unsigned OldCW =
8309       F->getRegInfo().createVirtualRegister(X86::GR16RegisterClass);
8310     addFrameReference(BuildMI(BB, DL, TII->get(X86::MOV16rm), OldCW),
8311                       CWFrameIdx);
8312
8313     // Set the high part to be round to zero...
8314     addFrameReference(BuildMI(BB, DL, TII->get(X86::MOV16mi)), CWFrameIdx)
8315       .addImm(0xC7F);
8316
8317     // Reload the modified control word now...
8318     addFrameReference(BuildMI(BB, DL, TII->get(X86::FLDCW16m)), CWFrameIdx);
8319
8320     // Restore the memory image of control word to original value
8321     addFrameReference(BuildMI(BB, DL, TII->get(X86::MOV16mr)), CWFrameIdx)
8322       .addReg(OldCW);
8323
8324     // Get the X86 opcode to use.
8325     unsigned Opc;
8326     switch (MI->getOpcode()) {
8327     default: llvm_unreachable("illegal opcode!");
8328     case X86::FP32_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m32; break;
8329     case X86::FP32_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m32; break;
8330     case X86::FP32_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m32; break;
8331     case X86::FP64_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m64; break;
8332     case X86::FP64_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m64; break;
8333     case X86::FP64_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m64; break;
8334     case X86::FP80_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m80; break;
8335     case X86::FP80_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m80; break;
8336     case X86::FP80_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m80; break;
8337     }
8338
8339     X86AddressMode AM;
8340     MachineOperand &Op = MI->getOperand(0);
8341     if (Op.isReg()) {
8342       AM.BaseType = X86AddressMode::RegBase;
8343       AM.Base.Reg = Op.getReg();
8344     } else {
8345       AM.BaseType = X86AddressMode::FrameIndexBase;
8346       AM.Base.FrameIndex = Op.getIndex();
8347     }
8348     Op = MI->getOperand(1);
8349     if (Op.isImm())
8350       AM.Scale = Op.getImm();
8351     Op = MI->getOperand(2);
8352     if (Op.isImm())
8353       AM.IndexReg = Op.getImm();
8354     Op = MI->getOperand(3);
8355     if (Op.isGlobal()) {
8356       AM.GV = Op.getGlobal();
8357     } else {
8358       AM.Disp = Op.getImm();
8359     }
8360     addFullAddress(BuildMI(BB, DL, TII->get(Opc)), AM)
8361                       .addReg(MI->getOperand(X86AddrNumOperands).getReg());
8362
8363     // Reload the original control word now.
8364     addFrameReference(BuildMI(BB, DL, TII->get(X86::FLDCW16m)), CWFrameIdx);
8365
8366     F->DeleteMachineInstr(MI);   // The pseudo instruction is gone now.
8367     return BB;
8368   }
8369     // String/text processing lowering.
8370   case X86::PCMPISTRM128REG:
8371     return EmitPCMP(MI, BB, 3, false /* in-mem */);
8372   case X86::PCMPISTRM128MEM:
8373     return EmitPCMP(MI, BB, 3, true /* in-mem */);
8374   case X86::PCMPESTRM128REG:
8375     return EmitPCMP(MI, BB, 5, false /* in mem */);
8376   case X86::PCMPESTRM128MEM:
8377     return EmitPCMP(MI, BB, 5, true /* in mem */);
8378
8379     // Atomic Lowering.
8380   case X86::ATOMAND32:
8381     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND32rr,
8382                                                X86::AND32ri, X86::MOV32rm,
8383                                                X86::LCMPXCHG32, X86::MOV32rr,
8384                                                X86::NOT32r, X86::EAX,
8385                                                X86::GR32RegisterClass);
8386   case X86::ATOMOR32:
8387     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR32rr,
8388                                                X86::OR32ri, X86::MOV32rm,
8389                                                X86::LCMPXCHG32, X86::MOV32rr,
8390                                                X86::NOT32r, X86::EAX,
8391                                                X86::GR32RegisterClass);
8392   case X86::ATOMXOR32:
8393     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR32rr,
8394                                                X86::XOR32ri, X86::MOV32rm,
8395                                                X86::LCMPXCHG32, X86::MOV32rr,
8396                                                X86::NOT32r, X86::EAX,
8397                                                X86::GR32RegisterClass);
8398   case X86::ATOMNAND32:
8399     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND32rr,
8400                                                X86::AND32ri, X86::MOV32rm,
8401                                                X86::LCMPXCHG32, X86::MOV32rr,
8402                                                X86::NOT32r, X86::EAX,
8403                                                X86::GR32RegisterClass, true);
8404   case X86::ATOMMIN32:
8405     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVL32rr);
8406   case X86::ATOMMAX32:
8407     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVG32rr);
8408   case X86::ATOMUMIN32:
8409     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVB32rr);
8410   case X86::ATOMUMAX32:
8411     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVA32rr);
8412
8413   case X86::ATOMAND16:
8414     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND16rr,
8415                                                X86::AND16ri, X86::MOV16rm,
8416                                                X86::LCMPXCHG16, X86::MOV16rr,
8417                                                X86::NOT16r, X86::AX,
8418                                                X86::GR16RegisterClass);
8419   case X86::ATOMOR16:
8420     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR16rr,
8421                                                X86::OR16ri, X86::MOV16rm,
8422                                                X86::LCMPXCHG16, X86::MOV16rr,
8423                                                X86::NOT16r, X86::AX,
8424                                                X86::GR16RegisterClass);
8425   case X86::ATOMXOR16:
8426     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR16rr,
8427                                                X86::XOR16ri, X86::MOV16rm,
8428                                                X86::LCMPXCHG16, X86::MOV16rr,
8429                                                X86::NOT16r, X86::AX,
8430                                                X86::GR16RegisterClass);
8431   case X86::ATOMNAND16:
8432     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND16rr,
8433                                                X86::AND16ri, X86::MOV16rm,
8434                                                X86::LCMPXCHG16, X86::MOV16rr,
8435                                                X86::NOT16r, X86::AX,
8436                                                X86::GR16RegisterClass, true);
8437   case X86::ATOMMIN16:
8438     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVL16rr);
8439   case X86::ATOMMAX16:
8440     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVG16rr);
8441   case X86::ATOMUMIN16:
8442     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVB16rr);
8443   case X86::ATOMUMAX16:
8444     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVA16rr);
8445
8446   case X86::ATOMAND8:
8447     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND8rr,
8448                                                X86::AND8ri, X86::MOV8rm,
8449                                                X86::LCMPXCHG8, X86::MOV8rr,
8450                                                X86::NOT8r, X86::AL,
8451                                                X86::GR8RegisterClass);
8452   case X86::ATOMOR8:
8453     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR8rr,
8454                                                X86::OR8ri, X86::MOV8rm,
8455                                                X86::LCMPXCHG8, X86::MOV8rr,
8456                                                X86::NOT8r, X86::AL,
8457                                                X86::GR8RegisterClass);
8458   case X86::ATOMXOR8:
8459     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR8rr,
8460                                                X86::XOR8ri, X86::MOV8rm,
8461                                                X86::LCMPXCHG8, X86::MOV8rr,
8462                                                X86::NOT8r, X86::AL,
8463                                                X86::GR8RegisterClass);
8464   case X86::ATOMNAND8:
8465     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND8rr,
8466                                                X86::AND8ri, X86::MOV8rm,
8467                                                X86::LCMPXCHG8, X86::MOV8rr,
8468                                                X86::NOT8r, X86::AL,
8469                                                X86::GR8RegisterClass, true);
8470   // FIXME: There are no CMOV8 instructions; MIN/MAX need some other way.
8471   // This group is for 64-bit host.
8472   case X86::ATOMAND64:
8473     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND64rr,
8474                                                X86::AND64ri32, X86::MOV64rm,
8475                                                X86::LCMPXCHG64, X86::MOV64rr,
8476                                                X86::NOT64r, X86::RAX,
8477                                                X86::GR64RegisterClass);
8478   case X86::ATOMOR64:
8479     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR64rr,
8480                                                X86::OR64ri32, X86::MOV64rm,
8481                                                X86::LCMPXCHG64, X86::MOV64rr,
8482                                                X86::NOT64r, X86::RAX,
8483                                                X86::GR64RegisterClass);
8484   case X86::ATOMXOR64:
8485     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR64rr,
8486                                                X86::XOR64ri32, X86::MOV64rm,
8487                                                X86::LCMPXCHG64, X86::MOV64rr,
8488                                                X86::NOT64r, X86::RAX,
8489                                                X86::GR64RegisterClass);
8490   case X86::ATOMNAND64:
8491     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND64rr,
8492                                                X86::AND64ri32, X86::MOV64rm,
8493                                                X86::LCMPXCHG64, X86::MOV64rr,
8494                                                X86::NOT64r, X86::RAX,
8495                                                X86::GR64RegisterClass, true);
8496   case X86::ATOMMIN64:
8497     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVL64rr);
8498   case X86::ATOMMAX64:
8499     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVG64rr);
8500   case X86::ATOMUMIN64:
8501     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVB64rr);
8502   case X86::ATOMUMAX64:
8503     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVA64rr);
8504
8505   // This group does 64-bit operations on a 32-bit host.
8506   case X86::ATOMAND6432:
8507     return EmitAtomicBit6432WithCustomInserter(MI, BB,
8508                                                X86::AND32rr, X86::AND32rr,
8509                                                X86::AND32ri, X86::AND32ri,
8510                                                false);
8511   case X86::ATOMOR6432:
8512     return EmitAtomicBit6432WithCustomInserter(MI, BB,
8513                                                X86::OR32rr, X86::OR32rr,
8514                                                X86::OR32ri, X86::OR32ri,
8515                                                false);
8516   case X86::ATOMXOR6432:
8517     return EmitAtomicBit6432WithCustomInserter(MI, BB,
8518                                                X86::XOR32rr, X86::XOR32rr,
8519                                                X86::XOR32ri, X86::XOR32ri,
8520                                                false);
8521   case X86::ATOMNAND6432:
8522     return EmitAtomicBit6432WithCustomInserter(MI, BB,
8523                                                X86::AND32rr, X86::AND32rr,
8524                                                X86::AND32ri, X86::AND32ri,
8525                                                true);
8526   case X86::ATOMADD6432:
8527     return EmitAtomicBit6432WithCustomInserter(MI, BB,
8528                                                X86::ADD32rr, X86::ADC32rr,
8529                                                X86::ADD32ri, X86::ADC32ri,
8530                                                false);
8531   case X86::ATOMSUB6432:
8532     return EmitAtomicBit6432WithCustomInserter(MI, BB,
8533                                                X86::SUB32rr, X86::SBB32rr,
8534                                                X86::SUB32ri, X86::SBB32ri,
8535                                                false);
8536   case X86::ATOMSWAP6432:
8537     return EmitAtomicBit6432WithCustomInserter(MI, BB,
8538                                                X86::MOV32rr, X86::MOV32rr,
8539                                                X86::MOV32ri, X86::MOV32ri,
8540                                                false);
8541   case X86::VASTART_SAVE_XMM_REGS:
8542     return EmitVAStartSaveXMMRegsWithCustomInserter(MI, BB);
8543   }
8544 }
8545
8546 //===----------------------------------------------------------------------===//
8547 //                           X86 Optimization Hooks
8548 //===----------------------------------------------------------------------===//
8549
8550 void X86TargetLowering::computeMaskedBitsForTargetNode(const SDValue Op,
8551                                                        const APInt &Mask,
8552                                                        APInt &KnownZero,
8553                                                        APInt &KnownOne,
8554                                                        const SelectionDAG &DAG,
8555                                                        unsigned Depth) const {
8556   unsigned Opc = Op.getOpcode();
8557   assert((Opc >= ISD::BUILTIN_OP_END ||
8558           Opc == ISD::INTRINSIC_WO_CHAIN ||
8559           Opc == ISD::INTRINSIC_W_CHAIN ||
8560           Opc == ISD::INTRINSIC_VOID) &&
8561          "Should use MaskedValueIsZero if you don't know whether Op"
8562          " is a target node!");
8563
8564   KnownZero = KnownOne = APInt(Mask.getBitWidth(), 0);   // Don't know anything.
8565   switch (Opc) {
8566   default: break;
8567   case X86ISD::ADD:
8568   case X86ISD::SUB:
8569   case X86ISD::SMUL:
8570   case X86ISD::UMUL:
8571   case X86ISD::INC:
8572   case X86ISD::DEC:
8573   case X86ISD::OR:
8574   case X86ISD::XOR:
8575   case X86ISD::AND:
8576     // These nodes' second result is a boolean.
8577     if (Op.getResNo() == 0)
8578       break;
8579     // Fallthrough
8580   case X86ISD::SETCC:
8581     KnownZero |= APInt::getHighBitsSet(Mask.getBitWidth(),
8582                                        Mask.getBitWidth() - 1);
8583     break;
8584   }
8585 }
8586
8587 /// isGAPlusOffset - Returns true (and the GlobalValue and the offset) if the
8588 /// node is a GlobalAddress + offset.
8589 bool X86TargetLowering::isGAPlusOffset(SDNode *N,
8590                                        GlobalValue* &GA, int64_t &Offset) const{
8591   if (N->getOpcode() == X86ISD::Wrapper) {
8592     if (isa<GlobalAddressSDNode>(N->getOperand(0))) {
8593       GA = cast<GlobalAddressSDNode>(N->getOperand(0))->getGlobal();
8594       Offset = cast<GlobalAddressSDNode>(N->getOperand(0))->getOffset();
8595       return true;
8596     }
8597   }
8598   return TargetLowering::isGAPlusOffset(N, GA, Offset);
8599 }
8600
8601 static bool EltsFromConsecutiveLoads(ShuffleVectorSDNode *N, unsigned NumElems,
8602                                      EVT EltVT, LoadSDNode *&LDBase,
8603                                      unsigned &LastLoadedElt,
8604                                      SelectionDAG &DAG, MachineFrameInfo *MFI,
8605                                      const TargetLowering &TLI) {
8606   LDBase = NULL;
8607   LastLoadedElt = -1U;
8608   for (unsigned i = 0; i < NumElems; ++i) {
8609     if (N->getMaskElt(i) < 0) {
8610       if (!LDBase)
8611         return false;
8612       continue;
8613     }
8614
8615     SDValue Elt = DAG.getShuffleScalarElt(N, i);
8616     if (!Elt.getNode() ||
8617         (Elt.getOpcode() != ISD::UNDEF && !ISD::isNON_EXTLoad(Elt.getNode())))
8618       return false;
8619     if (!LDBase) {
8620       if (Elt.getNode()->getOpcode() == ISD::UNDEF)
8621         return false;
8622       LDBase = cast<LoadSDNode>(Elt.getNode());
8623       LastLoadedElt = i;
8624       continue;
8625     }
8626     if (Elt.getOpcode() == ISD::UNDEF)
8627       continue;
8628
8629     LoadSDNode *LD = cast<LoadSDNode>(Elt);
8630     if (!DAG.isConsecutiveLoad(LD, LDBase, EltVT.getSizeInBits()/8, i))
8631       return false;
8632     LastLoadedElt = i;
8633   }
8634   return true;
8635 }
8636
8637 /// PerformShuffleCombine - Combine a vector_shuffle that is equal to
8638 /// build_vector load1, load2, load3, load4, <0, 1, 2, 3> into a 128-bit load
8639 /// if the load addresses are consecutive, non-overlapping, and in the right
8640 /// order.  In the case of v2i64, it will see if it can rewrite the
8641 /// shuffle to be an appropriate build vector so it can take advantage of
8642 // performBuildVectorCombine.
8643 static SDValue PerformShuffleCombine(SDNode *N, SelectionDAG &DAG,
8644                                      const TargetLowering &TLI) {
8645   DebugLoc dl = N->getDebugLoc();
8646   EVT VT = N->getValueType(0);
8647   EVT EltVT = VT.getVectorElementType();
8648   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
8649   unsigned NumElems = VT.getVectorNumElements();
8650
8651   if (VT.getSizeInBits() != 128)
8652     return SDValue();
8653
8654   // Try to combine a vector_shuffle into a 128-bit load.
8655   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
8656   LoadSDNode *LD = NULL;
8657   unsigned LastLoadedElt;
8658   if (!EltsFromConsecutiveLoads(SVN, NumElems, EltVT, LD, LastLoadedElt, DAG,
8659                                 MFI, TLI))
8660     return SDValue();
8661
8662   if (LastLoadedElt == NumElems - 1) {
8663     if (DAG.InferPtrAlignment(LD->getBasePtr()) >= 16)
8664       return DAG.getLoad(VT, dl, LD->getChain(), LD->getBasePtr(),
8665                          LD->getSrcValue(), LD->getSrcValueOffset(),
8666                          LD->isVolatile());
8667     return DAG.getLoad(VT, dl, LD->getChain(), LD->getBasePtr(),
8668                        LD->getSrcValue(), LD->getSrcValueOffset(),
8669                        LD->isVolatile(), LD->getAlignment());
8670   } else if (NumElems == 4 && LastLoadedElt == 1) {
8671     SDVTList Tys = DAG.getVTList(MVT::v2i64, MVT::Other);
8672     SDValue Ops[] = { LD->getChain(), LD->getBasePtr() };
8673     SDValue ResNode = DAG.getNode(X86ISD::VZEXT_LOAD, dl, Tys, Ops, 2);
8674     return DAG.getNode(ISD::BIT_CONVERT, dl, VT, ResNode);
8675   }
8676   return SDValue();
8677 }
8678
8679 /// PerformSELECTCombine - Do target-specific dag combines on SELECT nodes.
8680 static SDValue PerformSELECTCombine(SDNode *N, SelectionDAG &DAG,
8681                                     const X86Subtarget *Subtarget) {
8682   DebugLoc DL = N->getDebugLoc();
8683   SDValue Cond = N->getOperand(0);
8684   // Get the LHS/RHS of the select.
8685   SDValue LHS = N->getOperand(1);
8686   SDValue RHS = N->getOperand(2);
8687
8688   // If we have SSE[12] support, try to form min/max nodes. SSE min/max
8689   // instructions have the peculiarity that if either operand is a NaN,
8690   // they chose what we call the RHS operand (and as such are not symmetric).
8691   // It happens that this matches the semantics of the common C idiom
8692   // x<y?x:y and related forms, so we can recognize these cases.
8693   if (Subtarget->hasSSE2() &&
8694       (LHS.getValueType() == MVT::f32 || LHS.getValueType() == MVT::f64) &&
8695       Cond.getOpcode() == ISD::SETCC) {
8696     ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
8697
8698     unsigned Opcode = 0;
8699     // Check for x CC y ? x : y.
8700     if (LHS == Cond.getOperand(0) && RHS == Cond.getOperand(1)) {
8701       switch (CC) {
8702       default: break;
8703       case ISD::SETULT:
8704         // This can be a min if we can prove that at least one of the operands
8705         // is not a nan.
8706         if (!FiniteOnlyFPMath()) {
8707           if (DAG.isKnownNeverNaN(RHS)) {
8708             // Put the potential NaN in the RHS so that SSE will preserve it.
8709             std::swap(LHS, RHS);
8710           } else if (!DAG.isKnownNeverNaN(LHS))
8711             break;
8712         }
8713         Opcode = X86ISD::FMIN;
8714         break;
8715       case ISD::SETOLE:
8716         // This can be a min if we can prove that at least one of the operands
8717         // is not a nan.
8718         if (!FiniteOnlyFPMath()) {
8719           if (DAG.isKnownNeverNaN(LHS)) {
8720             // Put the potential NaN in the RHS so that SSE will preserve it.
8721             std::swap(LHS, RHS);
8722           } else if (!DAG.isKnownNeverNaN(RHS))
8723             break;
8724         }
8725         Opcode = X86ISD::FMIN;
8726         break;
8727       case ISD::SETULE:
8728         // This can be a min, but if either operand is a NaN we need it to
8729         // preserve the original LHS.
8730         std::swap(LHS, RHS);
8731       case ISD::SETOLT:
8732       case ISD::SETLT:
8733       case ISD::SETLE:
8734         Opcode = X86ISD::FMIN;
8735         break;
8736
8737       case ISD::SETOGE:
8738         // This can be a max if we can prove that at least one of the operands
8739         // is not a nan.
8740         if (!FiniteOnlyFPMath()) {
8741           if (DAG.isKnownNeverNaN(LHS)) {
8742             // Put the potential NaN in the RHS so that SSE will preserve it.
8743             std::swap(LHS, RHS);
8744           } else if (!DAG.isKnownNeverNaN(RHS))
8745             break;
8746         }
8747         Opcode = X86ISD::FMAX;
8748         break;
8749       case ISD::SETUGT:
8750         // This can be a max if we can prove that at least one of the operands
8751         // is not a nan.
8752         if (!FiniteOnlyFPMath()) {
8753           if (DAG.isKnownNeverNaN(RHS)) {
8754             // Put the potential NaN in the RHS so that SSE will preserve it.
8755             std::swap(LHS, RHS);
8756           } else if (!DAG.isKnownNeverNaN(LHS))
8757             break;
8758         }
8759         Opcode = X86ISD::FMAX;
8760         break;
8761       case ISD::SETUGE:
8762         // This can be a max, but if either operand is a NaN we need it to
8763         // preserve the original LHS.
8764         std::swap(LHS, RHS);
8765       case ISD::SETOGT:
8766       case ISD::SETGT:
8767       case ISD::SETGE:
8768         Opcode = X86ISD::FMAX;
8769         break;
8770       }
8771     // Check for x CC y ? y : x -- a min/max with reversed arms.
8772     } else if (LHS == Cond.getOperand(1) && RHS == Cond.getOperand(0)) {
8773       switch (CC) {
8774       default: break;
8775       case ISD::SETOGE:
8776         // This can be a min if we can prove that at least one of the operands
8777         // is not a nan.
8778         if (!FiniteOnlyFPMath()) {
8779           if (DAG.isKnownNeverNaN(RHS)) {
8780             // Put the potential NaN in the RHS so that SSE will preserve it.
8781             std::swap(LHS, RHS);
8782           } else if (!DAG.isKnownNeverNaN(LHS))
8783             break;
8784         }
8785         Opcode = X86ISD::FMIN;
8786         break;
8787       case ISD::SETUGT:
8788         // This can be a min if we can prove that at least one of the operands
8789         // is not a nan.
8790         if (!FiniteOnlyFPMath()) {
8791           if (DAG.isKnownNeverNaN(LHS)) {
8792             // Put the potential NaN in the RHS so that SSE will preserve it.
8793             std::swap(LHS, RHS);
8794           } else if (!DAG.isKnownNeverNaN(RHS))
8795             break;
8796         }
8797         Opcode = X86ISD::FMIN;
8798         break;
8799       case ISD::SETUGE:
8800         // This can be a min, but if either operand is a NaN we need it to
8801         // preserve the original LHS.
8802         std::swap(LHS, RHS);
8803       case ISD::SETOGT:
8804       case ISD::SETGT:
8805       case ISD::SETGE:
8806         Opcode = X86ISD::FMIN;
8807         break;
8808
8809       case ISD::SETULT:
8810         // This can be a max if we can prove that at least one of the operands
8811         // is not a nan.
8812         if (!FiniteOnlyFPMath()) {
8813           if (DAG.isKnownNeverNaN(LHS)) {
8814             // Put the potential NaN in the RHS so that SSE will preserve it.
8815             std::swap(LHS, RHS);
8816           } else if (!DAG.isKnownNeverNaN(RHS))
8817             break;
8818         }
8819         Opcode = X86ISD::FMAX;
8820         break;
8821       case ISD::SETOLE:
8822         // This can be a max if we can prove that at least one of the operands
8823         // is not a nan.
8824         if (!FiniteOnlyFPMath()) {
8825           if (DAG.isKnownNeverNaN(RHS)) {
8826             // Put the potential NaN in the RHS so that SSE will preserve it.
8827             std::swap(LHS, RHS);
8828           } else if (!DAG.isKnownNeverNaN(LHS))
8829             break;
8830         }
8831         Opcode = X86ISD::FMAX;
8832         break;
8833       case ISD::SETULE:
8834         // This can be a max, but if either operand is a NaN we need it to
8835         // preserve the original LHS.
8836         std::swap(LHS, RHS);
8837       case ISD::SETOLT:
8838       case ISD::SETLT:
8839       case ISD::SETLE:
8840         Opcode = X86ISD::FMAX;
8841         break;
8842       }
8843     }
8844
8845     if (Opcode)
8846       return DAG.getNode(Opcode, DL, N->getValueType(0), LHS, RHS);
8847   }
8848
8849   // If this is a select between two integer constants, try to do some
8850   // optimizations.
8851   if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(LHS)) {
8852     if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(RHS))
8853       // Don't do this for crazy integer types.
8854       if (DAG.getTargetLoweringInfo().isTypeLegal(LHS.getValueType())) {
8855         // If this is efficiently invertible, canonicalize the LHSC/RHSC values
8856         // so that TrueC (the true value) is larger than FalseC.
8857         bool NeedsCondInvert = false;
8858
8859         if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue()) &&
8860             // Efficiently invertible.
8861             (Cond.getOpcode() == ISD::SETCC ||  // setcc -> invertible.
8862              (Cond.getOpcode() == ISD::XOR &&   // xor(X, C) -> invertible.
8863               isa<ConstantSDNode>(Cond.getOperand(1))))) {
8864           NeedsCondInvert = true;
8865           std::swap(TrueC, FalseC);
8866         }
8867
8868         // Optimize C ? 8 : 0 -> zext(C) << 3.  Likewise for any pow2/0.
8869         if (FalseC->getAPIntValue() == 0 &&
8870             TrueC->getAPIntValue().isPowerOf2()) {
8871           if (NeedsCondInvert) // Invert the condition if needed.
8872             Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
8873                                DAG.getConstant(1, Cond.getValueType()));
8874
8875           // Zero extend the condition if needed.
8876           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, LHS.getValueType(), Cond);
8877
8878           unsigned ShAmt = TrueC->getAPIntValue().logBase2();
8879           return DAG.getNode(ISD::SHL, DL, LHS.getValueType(), Cond,
8880                              DAG.getConstant(ShAmt, MVT::i8));
8881         }
8882
8883         // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.
8884         if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
8885           if (NeedsCondInvert) // Invert the condition if needed.
8886             Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
8887                                DAG.getConstant(1, Cond.getValueType()));
8888
8889           // Zero extend the condition if needed.
8890           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
8891                              FalseC->getValueType(0), Cond);
8892           return DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
8893                              SDValue(FalseC, 0));
8894         }
8895
8896         // Optimize cases that will turn into an LEA instruction.  This requires
8897         // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
8898         if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
8899           uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
8900           if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
8901
8902           bool isFastMultiplier = false;
8903           if (Diff < 10) {
8904             switch ((unsigned char)Diff) {
8905               default: break;
8906               case 1:  // result = add base, cond
8907               case 2:  // result = lea base(    , cond*2)
8908               case 3:  // result = lea base(cond, cond*2)
8909               case 4:  // result = lea base(    , cond*4)
8910               case 5:  // result = lea base(cond, cond*4)
8911               case 8:  // result = lea base(    , cond*8)
8912               case 9:  // result = lea base(cond, cond*8)
8913                 isFastMultiplier = true;
8914                 break;
8915             }
8916           }
8917
8918           if (isFastMultiplier) {
8919             APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
8920             if (NeedsCondInvert) // Invert the condition if needed.
8921               Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
8922                                  DAG.getConstant(1, Cond.getValueType()));
8923
8924             // Zero extend the condition if needed.
8925             Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
8926                                Cond);
8927             // Scale the condition by the difference.
8928             if (Diff != 1)
8929               Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
8930                                  DAG.getConstant(Diff, Cond.getValueType()));
8931
8932             // Add the base if non-zero.
8933             if (FalseC->getAPIntValue() != 0)
8934               Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
8935                                  SDValue(FalseC, 0));
8936             return Cond;
8937           }
8938         }
8939       }
8940   }
8941
8942   return SDValue();
8943 }
8944
8945 /// Optimize X86ISD::CMOV [LHS, RHS, CONDCODE (e.g. X86::COND_NE), CONDVAL]
8946 static SDValue PerformCMOVCombine(SDNode *N, SelectionDAG &DAG,
8947                                   TargetLowering::DAGCombinerInfo &DCI) {
8948   DebugLoc DL = N->getDebugLoc();
8949
8950   // If the flag operand isn't dead, don't touch this CMOV.
8951   if (N->getNumValues() == 2 && !SDValue(N, 1).use_empty())
8952     return SDValue();
8953
8954   // If this is a select between two integer constants, try to do some
8955   // optimizations.  Note that the operands are ordered the opposite of SELECT
8956   // operands.
8957   if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(N->getOperand(1))) {
8958     if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(N->getOperand(0))) {
8959       // Canonicalize the TrueC/FalseC values so that TrueC (the true value) is
8960       // larger than FalseC (the false value).
8961       X86::CondCode CC = (X86::CondCode)N->getConstantOperandVal(2);
8962
8963       if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue())) {
8964         CC = X86::GetOppositeBranchCondition(CC);
8965         std::swap(TrueC, FalseC);
8966       }
8967
8968       // Optimize C ? 8 : 0 -> zext(setcc(C)) << 3.  Likewise for any pow2/0.
8969       // This is efficient for any integer data type (including i8/i16) and
8970       // shift amount.
8971       if (FalseC->getAPIntValue() == 0 && TrueC->getAPIntValue().isPowerOf2()) {
8972         SDValue Cond = N->getOperand(3);
8973         Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
8974                            DAG.getConstant(CC, MVT::i8), Cond);
8975
8976         // Zero extend the condition if needed.
8977         Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, TrueC->getValueType(0), Cond);
8978
8979         unsigned ShAmt = TrueC->getAPIntValue().logBase2();
8980         Cond = DAG.getNode(ISD::SHL, DL, Cond.getValueType(), Cond,
8981                            DAG.getConstant(ShAmt, MVT::i8));
8982         if (N->getNumValues() == 2)  // Dead flag value?
8983           return DCI.CombineTo(N, Cond, SDValue());
8984         return Cond;
8985       }
8986
8987       // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.  This is efficient
8988       // for any integer data type, including i8/i16.
8989       if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
8990         SDValue Cond = N->getOperand(3);
8991         Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
8992                            DAG.getConstant(CC, MVT::i8), Cond);
8993
8994         // Zero extend the condition if needed.
8995         Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
8996                            FalseC->getValueType(0), Cond);
8997         Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
8998                            SDValue(FalseC, 0));
8999
9000         if (N->getNumValues() == 2)  // Dead flag value?
9001           return DCI.CombineTo(N, Cond, SDValue());
9002         return Cond;
9003       }
9004
9005       // Optimize cases that will turn into an LEA instruction.  This requires
9006       // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
9007       if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
9008         uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
9009         if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
9010
9011         bool isFastMultiplier = false;
9012         if (Diff < 10) {
9013           switch ((unsigned char)Diff) {
9014           default: break;
9015           case 1:  // result = add base, cond
9016           case 2:  // result = lea base(    , cond*2)
9017           case 3:  // result = lea base(cond, cond*2)
9018           case 4:  // result = lea base(    , cond*4)
9019           case 5:  // result = lea base(cond, cond*4)
9020           case 8:  // result = lea base(    , cond*8)
9021           case 9:  // result = lea base(cond, cond*8)
9022             isFastMultiplier = true;
9023             break;
9024           }
9025         }
9026
9027         if (isFastMultiplier) {
9028           APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
9029           SDValue Cond = N->getOperand(3);
9030           Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
9031                              DAG.getConstant(CC, MVT::i8), Cond);
9032           // Zero extend the condition if needed.
9033           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
9034                              Cond);
9035           // Scale the condition by the difference.
9036           if (Diff != 1)
9037             Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
9038                                DAG.getConstant(Diff, Cond.getValueType()));
9039
9040           // Add the base if non-zero.
9041           if (FalseC->getAPIntValue() != 0)
9042             Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
9043                                SDValue(FalseC, 0));
9044           if (N->getNumValues() == 2)  // Dead flag value?
9045             return DCI.CombineTo(N, Cond, SDValue());
9046           return Cond;
9047         }
9048       }
9049     }
9050   }
9051   return SDValue();
9052 }
9053
9054
9055 /// PerformMulCombine - Optimize a single multiply with constant into two
9056 /// in order to implement it with two cheaper instructions, e.g.
9057 /// LEA + SHL, LEA + LEA.
9058 static SDValue PerformMulCombine(SDNode *N, SelectionDAG &DAG,
9059                                  TargetLowering::DAGCombinerInfo &DCI) {
9060   if (DAG.getMachineFunction().
9061       getFunction()->hasFnAttr(Attribute::OptimizeForSize))
9062     return SDValue();
9063
9064   if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
9065     return SDValue();
9066
9067   EVT VT = N->getValueType(0);
9068   if (VT != MVT::i64)
9069     return SDValue();
9070
9071   ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
9072   if (!C)
9073     return SDValue();
9074   uint64_t MulAmt = C->getZExtValue();
9075   if (isPowerOf2_64(MulAmt) || MulAmt == 3 || MulAmt == 5 || MulAmt == 9)
9076     return SDValue();
9077
9078   uint64_t MulAmt1 = 0;
9079   uint64_t MulAmt2 = 0;
9080   if ((MulAmt % 9) == 0) {
9081     MulAmt1 = 9;
9082     MulAmt2 = MulAmt / 9;
9083   } else if ((MulAmt % 5) == 0) {
9084     MulAmt1 = 5;
9085     MulAmt2 = MulAmt / 5;
9086   } else if ((MulAmt % 3) == 0) {
9087     MulAmt1 = 3;
9088     MulAmt2 = MulAmt / 3;
9089   }
9090   if (MulAmt2 &&
9091       (isPowerOf2_64(MulAmt2) || MulAmt2 == 3 || MulAmt2 == 5 || MulAmt2 == 9)){
9092     DebugLoc DL = N->getDebugLoc();
9093
9094     if (isPowerOf2_64(MulAmt2) &&
9095         !(N->hasOneUse() && N->use_begin()->getOpcode() == ISD::ADD))
9096       // If second multiplifer is pow2, issue it first. We want the multiply by
9097       // 3, 5, or 9 to be folded into the addressing mode unless the lone use
9098       // is an add.
9099       std::swap(MulAmt1, MulAmt2);
9100
9101     SDValue NewMul;
9102     if (isPowerOf2_64(MulAmt1))
9103       NewMul = DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
9104                            DAG.getConstant(Log2_64(MulAmt1), MVT::i8));
9105     else
9106       NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, N->getOperand(0),
9107                            DAG.getConstant(MulAmt1, VT));
9108
9109     if (isPowerOf2_64(MulAmt2))
9110       NewMul = DAG.getNode(ISD::SHL, DL, VT, NewMul,
9111                            DAG.getConstant(Log2_64(MulAmt2), MVT::i8));
9112     else
9113       NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, NewMul,
9114                            DAG.getConstant(MulAmt2, VT));
9115
9116     // Do not add new nodes to DAG combiner worklist.
9117     DCI.CombineTo(N, NewMul, false);
9118   }
9119   return SDValue();
9120 }
9121
9122 static SDValue PerformSHLCombine(SDNode *N, SelectionDAG &DAG) {
9123   SDValue N0 = N->getOperand(0);
9124   SDValue N1 = N->getOperand(1);
9125   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
9126   EVT VT = N0.getValueType();
9127
9128   // fold (shl (and (setcc_c), c1), c2) -> (and setcc_c, (c1 << c2))
9129   // since the result of setcc_c is all zero's or all ones.
9130   if (N1C && N0.getOpcode() == ISD::AND &&
9131       N0.getOperand(1).getOpcode() == ISD::Constant) {
9132     SDValue N00 = N0.getOperand(0);
9133     if (N00.getOpcode() == X86ISD::SETCC_CARRY ||
9134         ((N00.getOpcode() == ISD::ANY_EXTEND ||
9135           N00.getOpcode() == ISD::ZERO_EXTEND) &&
9136          N00.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY)) {
9137       APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
9138       APInt ShAmt = N1C->getAPIntValue();
9139       Mask = Mask.shl(ShAmt);
9140       if (Mask != 0)
9141         return DAG.getNode(ISD::AND, N->getDebugLoc(), VT,
9142                            N00, DAG.getConstant(Mask, VT));
9143     }
9144   }
9145
9146   return SDValue();
9147 }
9148
9149 /// PerformShiftCombine - Transforms vector shift nodes to use vector shifts
9150 ///                       when possible.
9151 static SDValue PerformShiftCombine(SDNode* N, SelectionDAG &DAG,
9152                                    const X86Subtarget *Subtarget) {
9153   EVT VT = N->getValueType(0);
9154   if (!VT.isVector() && VT.isInteger() &&
9155       N->getOpcode() == ISD::SHL)
9156     return PerformSHLCombine(N, DAG);
9157
9158   // On X86 with SSE2 support, we can transform this to a vector shift if
9159   // all elements are shifted by the same amount.  We can't do this in legalize
9160   // because the a constant vector is typically transformed to a constant pool
9161   // so we have no knowledge of the shift amount.
9162   if (!Subtarget->hasSSE2())
9163     return SDValue();
9164
9165   if (VT != MVT::v2i64 && VT != MVT::v4i32 && VT != MVT::v8i16)
9166     return SDValue();
9167
9168   SDValue ShAmtOp = N->getOperand(1);
9169   EVT EltVT = VT.getVectorElementType();
9170   DebugLoc DL = N->getDebugLoc();
9171   SDValue BaseShAmt = SDValue();
9172   if (ShAmtOp.getOpcode() == ISD::BUILD_VECTOR) {
9173     unsigned NumElts = VT.getVectorNumElements();
9174     unsigned i = 0;
9175     for (; i != NumElts; ++i) {
9176       SDValue Arg = ShAmtOp.getOperand(i);
9177       if (Arg.getOpcode() == ISD::UNDEF) continue;
9178       BaseShAmt = Arg;
9179       break;
9180     }
9181     for (; i != NumElts; ++i) {
9182       SDValue Arg = ShAmtOp.getOperand(i);
9183       if (Arg.getOpcode() == ISD::UNDEF) continue;
9184       if (Arg != BaseShAmt) {
9185         return SDValue();
9186       }
9187     }
9188   } else if (ShAmtOp.getOpcode() == ISD::VECTOR_SHUFFLE &&
9189              cast<ShuffleVectorSDNode>(ShAmtOp)->isSplat()) {
9190     SDValue InVec = ShAmtOp.getOperand(0);
9191     if (InVec.getOpcode() == ISD::BUILD_VECTOR) {
9192       unsigned NumElts = InVec.getValueType().getVectorNumElements();
9193       unsigned i = 0;
9194       for (; i != NumElts; ++i) {
9195         SDValue Arg = InVec.getOperand(i);
9196         if (Arg.getOpcode() == ISD::UNDEF) continue;
9197         BaseShAmt = Arg;
9198         break;
9199       }
9200     } else if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT) {
9201        if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(InVec.getOperand(2))) {
9202          unsigned SplatIdx = cast<ShuffleVectorSDNode>(ShAmtOp)->getSplatIndex();
9203          if (C->getZExtValue() == SplatIdx)
9204            BaseShAmt = InVec.getOperand(1);
9205        }
9206     }
9207     if (BaseShAmt.getNode() == 0)
9208       BaseShAmt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, EltVT, ShAmtOp,
9209                               DAG.getIntPtrConstant(0));
9210   } else
9211     return SDValue();
9212
9213   // The shift amount is an i32.
9214   if (EltVT.bitsGT(MVT::i32))
9215     BaseShAmt = DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, BaseShAmt);
9216   else if (EltVT.bitsLT(MVT::i32))
9217     BaseShAmt = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, BaseShAmt);
9218
9219   // The shift amount is identical so we can do a vector shift.
9220   SDValue  ValOp = N->getOperand(0);
9221   switch (N->getOpcode()) {
9222   default:
9223     llvm_unreachable("Unknown shift opcode!");
9224     break;
9225   case ISD::SHL:
9226     if (VT == MVT::v2i64)
9227       return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
9228                          DAG.getConstant(Intrinsic::x86_sse2_pslli_q, MVT::i32),
9229                          ValOp, BaseShAmt);
9230     if (VT == MVT::v4i32)
9231       return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
9232                          DAG.getConstant(Intrinsic::x86_sse2_pslli_d, MVT::i32),
9233                          ValOp, BaseShAmt);
9234     if (VT == MVT::v8i16)
9235       return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
9236                          DAG.getConstant(Intrinsic::x86_sse2_pslli_w, MVT::i32),
9237                          ValOp, BaseShAmt);
9238     break;
9239   case ISD::SRA:
9240     if (VT == MVT::v4i32)
9241       return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
9242                          DAG.getConstant(Intrinsic::x86_sse2_psrai_d, MVT::i32),
9243                          ValOp, BaseShAmt);
9244     if (VT == MVT::v8i16)
9245       return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
9246                          DAG.getConstant(Intrinsic::x86_sse2_psrai_w, MVT::i32),
9247                          ValOp, BaseShAmt);
9248     break;
9249   case ISD::SRL:
9250     if (VT == MVT::v2i64)
9251       return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
9252                          DAG.getConstant(Intrinsic::x86_sse2_psrli_q, MVT::i32),
9253                          ValOp, BaseShAmt);
9254     if (VT == MVT::v4i32)
9255       return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
9256                          DAG.getConstant(Intrinsic::x86_sse2_psrli_d, MVT::i32),
9257                          ValOp, BaseShAmt);
9258     if (VT ==  MVT::v8i16)
9259       return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
9260                          DAG.getConstant(Intrinsic::x86_sse2_psrli_w, MVT::i32),
9261                          ValOp, BaseShAmt);
9262     break;
9263   }
9264   return SDValue();
9265 }
9266
9267 static SDValue PerformOrCombine(SDNode *N, SelectionDAG &DAG,
9268                                 const X86Subtarget *Subtarget) {
9269   EVT VT = N->getValueType(0);
9270   if (VT != MVT::i64 || !Subtarget->is64Bit())
9271     return SDValue();
9272
9273   // fold (or (x << c) | (y >> (64 - c))) ==> (shld64 x, y, c)
9274   SDValue N0 = N->getOperand(0);
9275   SDValue N1 = N->getOperand(1);
9276   if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL)
9277     std::swap(N0, N1);
9278   if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL)
9279     return SDValue();
9280
9281   SDValue ShAmt0 = N0.getOperand(1);
9282   if (ShAmt0.getValueType() != MVT::i8)
9283     return SDValue();
9284   SDValue ShAmt1 = N1.getOperand(1);
9285   if (ShAmt1.getValueType() != MVT::i8)
9286     return SDValue();
9287   if (ShAmt0.getOpcode() == ISD::TRUNCATE)
9288     ShAmt0 = ShAmt0.getOperand(0);
9289   if (ShAmt1.getOpcode() == ISD::TRUNCATE)
9290     ShAmt1 = ShAmt1.getOperand(0);
9291
9292   DebugLoc DL = N->getDebugLoc();
9293   unsigned Opc = X86ISD::SHLD;
9294   SDValue Op0 = N0.getOperand(0);
9295   SDValue Op1 = N1.getOperand(0);
9296   if (ShAmt0.getOpcode() == ISD::SUB) {
9297     Opc = X86ISD::SHRD;
9298     std::swap(Op0, Op1);
9299     std::swap(ShAmt0, ShAmt1);
9300   }
9301
9302   if (ShAmt1.getOpcode() == ISD::SUB) {
9303     SDValue Sum = ShAmt1.getOperand(0);
9304     if (ConstantSDNode *SumC = dyn_cast<ConstantSDNode>(Sum)) {
9305       if (SumC->getSExtValue() == 64 &&
9306           ShAmt1.getOperand(1) == ShAmt0)
9307         return DAG.getNode(Opc, DL, VT,
9308                            Op0, Op1,
9309                            DAG.getNode(ISD::TRUNCATE, DL,
9310                                        MVT::i8, ShAmt0));
9311     }
9312   } else if (ConstantSDNode *ShAmt1C = dyn_cast<ConstantSDNode>(ShAmt1)) {
9313     ConstantSDNode *ShAmt0C = dyn_cast<ConstantSDNode>(ShAmt0);
9314     if (ShAmt0C &&
9315         ShAmt0C->getSExtValue() + ShAmt1C->getSExtValue() == 64)
9316       return DAG.getNode(Opc, DL, VT,
9317                          N0.getOperand(0), N1.getOperand(0),
9318                          DAG.getNode(ISD::TRUNCATE, DL,
9319                                        MVT::i8, ShAmt0));
9320   }
9321
9322   return SDValue();
9323 }
9324
9325 /// PerformSTORECombine - Do target-specific dag combines on STORE nodes.
9326 static SDValue PerformSTORECombine(SDNode *N, SelectionDAG &DAG,
9327                                    const X86Subtarget *Subtarget) {
9328   // Turn load->store of MMX types into GPR load/stores.  This avoids clobbering
9329   // the FP state in cases where an emms may be missing.
9330   // A preferable solution to the general problem is to figure out the right
9331   // places to insert EMMS.  This qualifies as a quick hack.
9332
9333   // Similarly, turn load->store of i64 into double load/stores in 32-bit mode.
9334   StoreSDNode *St = cast<StoreSDNode>(N);
9335   EVT VT = St->getValue().getValueType();
9336   if (VT.getSizeInBits() != 64)
9337     return SDValue();
9338
9339   const Function *F = DAG.getMachineFunction().getFunction();
9340   bool NoImplicitFloatOps = F->hasFnAttr(Attribute::NoImplicitFloat);
9341   bool F64IsLegal = !UseSoftFloat && !NoImplicitFloatOps
9342     && Subtarget->hasSSE2();
9343   if ((VT.isVector() ||
9344        (VT == MVT::i64 && F64IsLegal && !Subtarget->is64Bit())) &&
9345       isa<LoadSDNode>(St->getValue()) &&
9346       !cast<LoadSDNode>(St->getValue())->isVolatile() &&
9347       St->getChain().hasOneUse() && !St->isVolatile()) {
9348     SDNode* LdVal = St->getValue().getNode();
9349     LoadSDNode *Ld = 0;
9350     int TokenFactorIndex = -1;
9351     SmallVector<SDValue, 8> Ops;
9352     SDNode* ChainVal = St->getChain().getNode();
9353     // Must be a store of a load.  We currently handle two cases:  the load
9354     // is a direct child, and it's under an intervening TokenFactor.  It is
9355     // possible to dig deeper under nested TokenFactors.
9356     if (ChainVal == LdVal)
9357       Ld = cast<LoadSDNode>(St->getChain());
9358     else if (St->getValue().hasOneUse() &&
9359              ChainVal->getOpcode() == ISD::TokenFactor) {
9360       for (unsigned i=0, e = ChainVal->getNumOperands(); i != e; ++i) {
9361         if (ChainVal->getOperand(i).getNode() == LdVal) {
9362           TokenFactorIndex = i;
9363           Ld = cast<LoadSDNode>(St->getValue());
9364         } else
9365           Ops.push_back(ChainVal->getOperand(i));
9366       }
9367     }
9368
9369     if (!Ld || !ISD::isNormalLoad(Ld))
9370       return SDValue();
9371
9372     // If this is not the MMX case, i.e. we are just turning i64 load/store
9373     // into f64 load/store, avoid the transformation if there are multiple
9374     // uses of the loaded value.
9375     if (!VT.isVector() && !Ld->hasNUsesOfValue(1, 0))
9376       return SDValue();
9377
9378     DebugLoc LdDL = Ld->getDebugLoc();
9379     DebugLoc StDL = N->getDebugLoc();
9380     // If we are a 64-bit capable x86, lower to a single movq load/store pair.
9381     // Otherwise, if it's legal to use f64 SSE instructions, use f64 load/store
9382     // pair instead.
9383     if (Subtarget->is64Bit() || F64IsLegal) {
9384       EVT LdVT = Subtarget->is64Bit() ? MVT::i64 : MVT::f64;
9385       SDValue NewLd = DAG.getLoad(LdVT, LdDL, Ld->getChain(),
9386                                   Ld->getBasePtr(), Ld->getSrcValue(),
9387                                   Ld->getSrcValueOffset(), Ld->isVolatile(),
9388                                   Ld->getAlignment());
9389       SDValue NewChain = NewLd.getValue(1);
9390       if (TokenFactorIndex != -1) {
9391         Ops.push_back(NewChain);
9392         NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, &Ops[0],
9393                                Ops.size());
9394       }
9395       return DAG.getStore(NewChain, StDL, NewLd, St->getBasePtr(),
9396                           St->getSrcValue(), St->getSrcValueOffset(),
9397                           St->isVolatile(), St->getAlignment());
9398     }
9399
9400     // Otherwise, lower to two pairs of 32-bit loads / stores.
9401     SDValue LoAddr = Ld->getBasePtr();
9402     SDValue HiAddr = DAG.getNode(ISD::ADD, LdDL, MVT::i32, LoAddr,
9403                                  DAG.getConstant(4, MVT::i32));
9404
9405     SDValue LoLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), LoAddr,
9406                                Ld->getSrcValue(), Ld->getSrcValueOffset(),
9407                                Ld->isVolatile(), Ld->getAlignment());
9408     SDValue HiLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), HiAddr,
9409                                Ld->getSrcValue(), Ld->getSrcValueOffset()+4,
9410                                Ld->isVolatile(),
9411                                MinAlign(Ld->getAlignment(), 4));
9412
9413     SDValue NewChain = LoLd.getValue(1);
9414     if (TokenFactorIndex != -1) {
9415       Ops.push_back(LoLd);
9416       Ops.push_back(HiLd);
9417       NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, &Ops[0],
9418                              Ops.size());
9419     }
9420
9421     LoAddr = St->getBasePtr();
9422     HiAddr = DAG.getNode(ISD::ADD, StDL, MVT::i32, LoAddr,
9423                          DAG.getConstant(4, MVT::i32));
9424
9425     SDValue LoSt = DAG.getStore(NewChain, StDL, LoLd, LoAddr,
9426                                 St->getSrcValue(), St->getSrcValueOffset(),
9427                                 St->isVolatile(), St->getAlignment());
9428     SDValue HiSt = DAG.getStore(NewChain, StDL, HiLd, HiAddr,
9429                                 St->getSrcValue(),
9430                                 St->getSrcValueOffset() + 4,
9431                                 St->isVolatile(),
9432                                 MinAlign(St->getAlignment(), 4));
9433     return DAG.getNode(ISD::TokenFactor, StDL, MVT::Other, LoSt, HiSt);
9434   }
9435   return SDValue();
9436 }
9437
9438 /// PerformFORCombine - Do target-specific dag combines on X86ISD::FOR and
9439 /// X86ISD::FXOR nodes.
9440 static SDValue PerformFORCombine(SDNode *N, SelectionDAG &DAG) {
9441   assert(N->getOpcode() == X86ISD::FOR || N->getOpcode() == X86ISD::FXOR);
9442   // F[X]OR(0.0, x) -> x
9443   // F[X]OR(x, 0.0) -> x
9444   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
9445     if (C->getValueAPF().isPosZero())
9446       return N->getOperand(1);
9447   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
9448     if (C->getValueAPF().isPosZero())
9449       return N->getOperand(0);
9450   return SDValue();
9451 }
9452
9453 /// PerformFANDCombine - Do target-specific dag combines on X86ISD::FAND nodes.
9454 static SDValue PerformFANDCombine(SDNode *N, SelectionDAG &DAG) {
9455   // FAND(0.0, x) -> 0.0
9456   // FAND(x, 0.0) -> 0.0
9457   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
9458     if (C->getValueAPF().isPosZero())
9459       return N->getOperand(0);
9460   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
9461     if (C->getValueAPF().isPosZero())
9462       return N->getOperand(1);
9463   return SDValue();
9464 }
9465
9466 static SDValue PerformBTCombine(SDNode *N,
9467                                 SelectionDAG &DAG,
9468                                 TargetLowering::DAGCombinerInfo &DCI) {
9469   // BT ignores high bits in the bit index operand.
9470   SDValue Op1 = N->getOperand(1);
9471   if (Op1.hasOneUse()) {
9472     unsigned BitWidth = Op1.getValueSizeInBits();
9473     APInt DemandedMask = APInt::getLowBitsSet(BitWidth, Log2_32(BitWidth));
9474     APInt KnownZero, KnownOne;
9475     TargetLowering::TargetLoweringOpt TLO(DAG);
9476     TargetLowering &TLI = DAG.getTargetLoweringInfo();
9477     if (TLO.ShrinkDemandedConstant(Op1, DemandedMask) ||
9478         TLI.SimplifyDemandedBits(Op1, DemandedMask, KnownZero, KnownOne, TLO))
9479       DCI.CommitTargetLoweringOpt(TLO);
9480   }
9481   return SDValue();
9482 }
9483
9484 static SDValue PerformVZEXT_MOVLCombine(SDNode *N, SelectionDAG &DAG) {
9485   SDValue Op = N->getOperand(0);
9486   if (Op.getOpcode() == ISD::BIT_CONVERT)
9487     Op = Op.getOperand(0);
9488   EVT VT = N->getValueType(0), OpVT = Op.getValueType();
9489   if (Op.getOpcode() == X86ISD::VZEXT_LOAD &&
9490       VT.getVectorElementType().getSizeInBits() ==
9491       OpVT.getVectorElementType().getSizeInBits()) {
9492     return DAG.getNode(ISD::BIT_CONVERT, N->getDebugLoc(), VT, Op);
9493   }
9494   return SDValue();
9495 }
9496
9497 // On X86 and X86-64, atomic operations are lowered to locked instructions.
9498 // Locked instructions, in turn, have implicit fence semantics (all memory
9499 // operations are flushed before issuing the locked instruction, and the
9500 // are not buffered), so we can fold away the common pattern of
9501 // fence-atomic-fence.
9502 static SDValue PerformMEMBARRIERCombine(SDNode* N, SelectionDAG &DAG) {
9503   SDValue atomic = N->getOperand(0);
9504   switch (atomic.getOpcode()) {
9505     case ISD::ATOMIC_CMP_SWAP:
9506     case ISD::ATOMIC_SWAP:
9507     case ISD::ATOMIC_LOAD_ADD:
9508     case ISD::ATOMIC_LOAD_SUB:
9509     case ISD::ATOMIC_LOAD_AND:
9510     case ISD::ATOMIC_LOAD_OR:
9511     case ISD::ATOMIC_LOAD_XOR:
9512     case ISD::ATOMIC_LOAD_NAND:
9513     case ISD::ATOMIC_LOAD_MIN:
9514     case ISD::ATOMIC_LOAD_MAX:
9515     case ISD::ATOMIC_LOAD_UMIN:
9516     case ISD::ATOMIC_LOAD_UMAX:
9517       break;
9518     default:
9519       return SDValue();
9520   }
9521
9522   SDValue fence = atomic.getOperand(0);
9523   if (fence.getOpcode() != ISD::MEMBARRIER)
9524     return SDValue();
9525
9526   switch (atomic.getOpcode()) {
9527     case ISD::ATOMIC_CMP_SWAP:
9528       return DAG.UpdateNodeOperands(atomic, fence.getOperand(0),
9529                                     atomic.getOperand(1), atomic.getOperand(2),
9530                                     atomic.getOperand(3));
9531     case ISD::ATOMIC_SWAP:
9532     case ISD::ATOMIC_LOAD_ADD:
9533     case ISD::ATOMIC_LOAD_SUB:
9534     case ISD::ATOMIC_LOAD_AND:
9535     case ISD::ATOMIC_LOAD_OR:
9536     case ISD::ATOMIC_LOAD_XOR:
9537     case ISD::ATOMIC_LOAD_NAND:
9538     case ISD::ATOMIC_LOAD_MIN:
9539     case ISD::ATOMIC_LOAD_MAX:
9540     case ISD::ATOMIC_LOAD_UMIN:
9541     case ISD::ATOMIC_LOAD_UMAX:
9542       return DAG.UpdateNodeOperands(atomic, fence.getOperand(0),
9543                                     atomic.getOperand(1), atomic.getOperand(2));
9544     default:
9545       return SDValue();
9546   }
9547 }
9548
9549 static SDValue PerformZExtCombine(SDNode *N, SelectionDAG &DAG) {
9550   // (i32 zext (and (i8  x86isd::setcc_carry), 1)) ->
9551   //           (and (i32 x86isd::setcc_carry), 1)
9552   // This eliminates the zext. This transformation is necessary because
9553   // ISD::SETCC is always legalized to i8.
9554   DebugLoc dl = N->getDebugLoc();
9555   SDValue N0 = N->getOperand(0);
9556   EVT VT = N->getValueType(0);
9557   if (N0.getOpcode() == ISD::AND &&
9558       N0.hasOneUse() &&
9559       N0.getOperand(0).hasOneUse()) {
9560     SDValue N00 = N0.getOperand(0);
9561     if (N00.getOpcode() != X86ISD::SETCC_CARRY)
9562       return SDValue();
9563     ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
9564     if (!C || C->getZExtValue() != 1)
9565       return SDValue();
9566     return DAG.getNode(ISD::AND, dl, VT,
9567                        DAG.getNode(X86ISD::SETCC_CARRY, dl, VT,
9568                                    N00.getOperand(0), N00.getOperand(1)),
9569                        DAG.getConstant(1, VT));
9570   }
9571
9572   return SDValue();
9573 }
9574
9575 SDValue X86TargetLowering::PerformDAGCombine(SDNode *N,
9576                                              DAGCombinerInfo &DCI) const {
9577   SelectionDAG &DAG = DCI.DAG;
9578   switch (N->getOpcode()) {
9579   default: break;
9580   case ISD::VECTOR_SHUFFLE: return PerformShuffleCombine(N, DAG, *this);
9581   case ISD::SELECT:         return PerformSELECTCombine(N, DAG, Subtarget);
9582   case X86ISD::CMOV:        return PerformCMOVCombine(N, DAG, DCI);
9583   case ISD::MUL:            return PerformMulCombine(N, DAG, DCI);
9584   case ISD::SHL:
9585   case ISD::SRA:
9586   case ISD::SRL:            return PerformShiftCombine(N, DAG, Subtarget);
9587   case ISD::OR:             return PerformOrCombine(N, DAG, Subtarget);
9588   case ISD::STORE:          return PerformSTORECombine(N, DAG, Subtarget);
9589   case X86ISD::FXOR:
9590   case X86ISD::FOR:         return PerformFORCombine(N, DAG);
9591   case X86ISD::FAND:        return PerformFANDCombine(N, DAG);
9592   case X86ISD::BT:          return PerformBTCombine(N, DAG, DCI);
9593   case X86ISD::VZEXT_MOVL:  return PerformVZEXT_MOVLCombine(N, DAG);
9594   case ISD::MEMBARRIER:     return PerformMEMBARRIERCombine(N, DAG);
9595   case ISD::ZERO_EXTEND:    return PerformZExtCombine(N, DAG);
9596   }
9597
9598   return SDValue();
9599 }
9600
9601 //===----------------------------------------------------------------------===//
9602 //                           X86 Inline Assembly Support
9603 //===----------------------------------------------------------------------===//
9604
9605 static bool LowerToBSwap(CallInst *CI) {
9606   // FIXME: this should verify that we are targetting a 486 or better.  If not,
9607   // we will turn this bswap into something that will be lowered to logical ops
9608   // instead of emitting the bswap asm.  For now, we don't support 486 or lower
9609   // so don't worry about this.
9610
9611   // Verify this is a simple bswap.
9612   if (CI->getNumOperands() != 2 ||
9613       CI->getType() != CI->getOperand(1)->getType() ||
9614       !CI->getType()->isInteger())
9615     return false;
9616
9617   const IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
9618   if (!Ty || Ty->getBitWidth() % 16 != 0)
9619     return false;
9620
9621   // Okay, we can do this xform, do so now.
9622   const Type *Tys[] = { Ty };
9623   Module *M = CI->getParent()->getParent()->getParent();
9624   Constant *Int = Intrinsic::getDeclaration(M, Intrinsic::bswap, Tys, 1);
9625
9626   Value *Op = CI->getOperand(1);
9627   Op = CallInst::Create(Int, Op, CI->getName(), CI);
9628
9629   CI->replaceAllUsesWith(Op);
9630   CI->eraseFromParent();
9631   return true;
9632 }
9633
9634 bool X86TargetLowering::ExpandInlineAsm(CallInst *CI) const {
9635   InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue());
9636   std::vector<InlineAsm::ConstraintInfo> Constraints = IA->ParseConstraints();
9637
9638   std::string AsmStr = IA->getAsmString();
9639
9640   // TODO: should remove alternatives from the asmstring: "foo {a|b}" -> "foo a"
9641   SmallVector<StringRef, 4> AsmPieces;
9642   SplitString(AsmStr, AsmPieces, "\n");  // ; as separator?
9643
9644   switch (AsmPieces.size()) {
9645   default: return false;
9646   case 1:
9647     AsmStr = AsmPieces[0];
9648     AsmPieces.clear();
9649     SplitString(AsmStr, AsmPieces, " \t");  // Split with whitespace.
9650
9651     // bswap $0
9652     if (AsmPieces.size() == 2 &&
9653         (AsmPieces[0] == "bswap" ||
9654          AsmPieces[0] == "bswapq" ||
9655          AsmPieces[0] == "bswapl") &&
9656         (AsmPieces[1] == "$0" ||
9657          AsmPieces[1] == "${0:q}")) {
9658       // No need to check constraints, nothing other than the equivalent of
9659       // "=r,0" would be valid here.
9660       return LowerToBSwap(CI);
9661     }
9662     // rorw $$8, ${0:w}  -->  llvm.bswap.i16
9663     if (CI->getType()->isInteger(16) &&
9664         AsmPieces.size() == 3 &&
9665         AsmPieces[0] == "rorw" &&
9666         AsmPieces[1] == "$$8," &&
9667         AsmPieces[2] == "${0:w}" &&
9668         IA->getConstraintString() == "=r,0,~{dirflag},~{fpsr},~{flags},~{cc}") {
9669       return LowerToBSwap(CI);
9670     }
9671     break;
9672   case 3:
9673     if (CI->getType()->isInteger(64) &&
9674         Constraints.size() >= 2 &&
9675         Constraints[0].Codes.size() == 1 && Constraints[0].Codes[0] == "A" &&
9676         Constraints[1].Codes.size() == 1 && Constraints[1].Codes[0] == "0") {
9677       // bswap %eax / bswap %edx / xchgl %eax, %edx  -> llvm.bswap.i64
9678       SmallVector<StringRef, 4> Words;
9679       SplitString(AsmPieces[0], Words, " \t");
9680       if (Words.size() == 2 && Words[0] == "bswap" && Words[1] == "%eax") {
9681         Words.clear();
9682         SplitString(AsmPieces[1], Words, " \t");
9683         if (Words.size() == 2 && Words[0] == "bswap" && Words[1] == "%edx") {
9684           Words.clear();
9685           SplitString(AsmPieces[2], Words, " \t,");
9686           if (Words.size() == 3 && Words[0] == "xchgl" && Words[1] == "%eax" &&
9687               Words[2] == "%edx") {
9688             return LowerToBSwap(CI);
9689           }
9690         }
9691       }
9692     }
9693     break;
9694   }
9695   return false;
9696 }
9697
9698
9699
9700 /// getConstraintType - Given a constraint letter, return the type of
9701 /// constraint it is for this target.
9702 X86TargetLowering::ConstraintType
9703 X86TargetLowering::getConstraintType(const std::string &Constraint) const {
9704   if (Constraint.size() == 1) {
9705     switch (Constraint[0]) {
9706     case 'A':
9707       return C_Register;
9708     case 'f':
9709     case 'r':
9710     case 'R':
9711     case 'l':
9712     case 'q':
9713     case 'Q':
9714     case 'x':
9715     case 'y':
9716     case 'Y':
9717       return C_RegisterClass;
9718     case 'e':
9719     case 'Z':
9720       return C_Other;
9721     default:
9722       break;
9723     }
9724   }
9725   return TargetLowering::getConstraintType(Constraint);
9726 }
9727
9728 /// LowerXConstraint - try to replace an X constraint, which matches anything,
9729 /// with another that has more specific requirements based on the type of the
9730 /// corresponding operand.
9731 const char *X86TargetLowering::
9732 LowerXConstraint(EVT ConstraintVT) const {
9733   // FP X constraints get lowered to SSE1/2 registers if available, otherwise
9734   // 'f' like normal targets.
9735   if (ConstraintVT.isFloatingPoint()) {
9736     if (Subtarget->hasSSE2())
9737       return "Y";
9738     if (Subtarget->hasSSE1())
9739       return "x";
9740   }
9741
9742   return TargetLowering::LowerXConstraint(ConstraintVT);
9743 }
9744
9745 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
9746 /// vector.  If it is invalid, don't add anything to Ops.
9747 void X86TargetLowering::LowerAsmOperandForConstraint(SDValue Op,
9748                                                      char Constraint,
9749                                                      bool hasMemory,
9750                                                      std::vector<SDValue>&Ops,
9751                                                      SelectionDAG &DAG) const {
9752   SDValue Result(0, 0);
9753
9754   switch (Constraint) {
9755   default: break;
9756   case 'I':
9757     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
9758       if (C->getZExtValue() <= 31) {
9759         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
9760         break;
9761       }
9762     }
9763     return;
9764   case 'J':
9765     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
9766       if (C->getZExtValue() <= 63) {
9767         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
9768         break;
9769       }
9770     }
9771     return;
9772   case 'K':
9773     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
9774       if ((int8_t)C->getSExtValue() == C->getSExtValue()) {
9775         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
9776         break;
9777       }
9778     }
9779     return;
9780   case 'N':
9781     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
9782       if (C->getZExtValue() <= 255) {
9783         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
9784         break;
9785       }
9786     }
9787     return;
9788   case 'e': {
9789     // 32-bit signed value
9790     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
9791       const ConstantInt *CI = C->getConstantIntValue();
9792       if (CI->isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
9793                                   C->getSExtValue())) {
9794         // Widen to 64 bits here to get it sign extended.
9795         Result = DAG.getTargetConstant(C->getSExtValue(), MVT::i64);
9796         break;
9797       }
9798     // FIXME gcc accepts some relocatable values here too, but only in certain
9799     // memory models; it's complicated.
9800     }
9801     return;
9802   }
9803   case 'Z': {
9804     // 32-bit unsigned value
9805     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
9806       const ConstantInt *CI = C->getConstantIntValue();
9807       if (CI->isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
9808                                   C->getZExtValue())) {
9809         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
9810         break;
9811       }
9812     }
9813     // FIXME gcc accepts some relocatable values here too, but only in certain
9814     // memory models; it's complicated.
9815     return;
9816   }
9817   case 'i': {
9818     // Literal immediates are always ok.
9819     if (ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op)) {
9820       // Widen to 64 bits here to get it sign extended.
9821       Result = DAG.getTargetConstant(CST->getSExtValue(), MVT::i64);
9822       break;
9823     }
9824
9825     // If we are in non-pic codegen mode, we allow the address of a global (with
9826     // an optional displacement) to be used with 'i'.
9827     GlobalAddressSDNode *GA = 0;
9828     int64_t Offset = 0;
9829
9830     // Match either (GA), (GA+C), (GA+C1+C2), etc.
9831     while (1) {
9832       if ((GA = dyn_cast<GlobalAddressSDNode>(Op))) {
9833         Offset += GA->getOffset();
9834         break;
9835       } else if (Op.getOpcode() == ISD::ADD) {
9836         if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
9837           Offset += C->getZExtValue();
9838           Op = Op.getOperand(0);
9839           continue;
9840         }
9841       } else if (Op.getOpcode() == ISD::SUB) {
9842         if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
9843           Offset += -C->getZExtValue();
9844           Op = Op.getOperand(0);
9845           continue;
9846         }
9847       }
9848
9849       // Otherwise, this isn't something we can handle, reject it.
9850       return;
9851     }
9852
9853     GlobalValue *GV = GA->getGlobal();
9854     // If we require an extra load to get this address, as in PIC mode, we
9855     // can't accept it.
9856     if (isGlobalStubReference(Subtarget->ClassifyGlobalReference(GV,
9857                                                         getTargetMachine())))
9858       return;
9859
9860     if (hasMemory)
9861       Op = LowerGlobalAddress(GV, Op.getDebugLoc(), Offset, DAG);
9862     else
9863       Op = DAG.getTargetGlobalAddress(GV, GA->getValueType(0), Offset);
9864     Result = Op;
9865     break;
9866   }
9867   }
9868
9869   if (Result.getNode()) {
9870     Ops.push_back(Result);
9871     return;
9872   }
9873   return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, hasMemory,
9874                                                       Ops, DAG);
9875 }
9876
9877 std::vector<unsigned> X86TargetLowering::
9878 getRegClassForInlineAsmConstraint(const std::string &Constraint,
9879                                   EVT VT) const {
9880   if (Constraint.size() == 1) {
9881     // FIXME: not handling fp-stack yet!
9882     switch (Constraint[0]) {      // GCC X86 Constraint Letters
9883     default: break;  // Unknown constraint letter
9884     case 'q':   // GENERAL_REGS in 64-bit mode, Q_REGS in 32-bit mode.
9885       if (Subtarget->is64Bit()) {
9886         if (VT == MVT::i32)
9887           return make_vector<unsigned>(X86::EAX, X86::EDX, X86::ECX, X86::EBX,
9888                                        X86::ESI, X86::EDI, X86::R8D, X86::R9D,
9889                                        X86::R10D,X86::R11D,X86::R12D,
9890                                        X86::R13D,X86::R14D,X86::R15D,
9891                                        X86::EBP, X86::ESP, 0);
9892         else if (VT == MVT::i16)
9893           return make_vector<unsigned>(X86::AX,  X86::DX,  X86::CX, X86::BX,
9894                                        X86::SI,  X86::DI,  X86::R8W,X86::R9W,
9895                                        X86::R10W,X86::R11W,X86::R12W,
9896                                        X86::R13W,X86::R14W,X86::R15W,
9897                                        X86::BP,  X86::SP, 0);
9898         else if (VT == MVT::i8)
9899           return make_vector<unsigned>(X86::AL,  X86::DL,  X86::CL, X86::BL,
9900                                        X86::SIL, X86::DIL, X86::R8B,X86::R9B,
9901                                        X86::R10B,X86::R11B,X86::R12B,
9902                                        X86::R13B,X86::R14B,X86::R15B,
9903                                        X86::BPL, X86::SPL, 0);
9904
9905         else if (VT == MVT::i64)
9906           return make_vector<unsigned>(X86::RAX, X86::RDX, X86::RCX, X86::RBX,
9907                                        X86::RSI, X86::RDI, X86::R8,  X86::R9,
9908                                        X86::R10, X86::R11, X86::R12,
9909                                        X86::R13, X86::R14, X86::R15,
9910                                        X86::RBP, X86::RSP, 0);
9911
9912         break;
9913       }
9914       // 32-bit fallthrough
9915     case 'Q':   // Q_REGS
9916       if (VT == MVT::i32)
9917         return make_vector<unsigned>(X86::EAX, X86::EDX, X86::ECX, X86::EBX, 0);
9918       else if (VT == MVT::i16)
9919         return make_vector<unsigned>(X86::AX, X86::DX, X86::CX, X86::BX, 0);
9920       else if (VT == MVT::i8)
9921         return make_vector<unsigned>(X86::AL, X86::DL, X86::CL, X86::BL, 0);
9922       else if (VT == MVT::i64)
9923         return make_vector<unsigned>(X86::RAX, X86::RDX, X86::RCX, X86::RBX, 0);
9924       break;
9925     }
9926   }
9927
9928   return std::vector<unsigned>();
9929 }
9930
9931 std::pair<unsigned, const TargetRegisterClass*>
9932 X86TargetLowering::getRegForInlineAsmConstraint(const std::string &Constraint,
9933                                                 EVT VT) const {
9934   // First, see if this is a constraint that directly corresponds to an LLVM
9935   // register class.
9936   if (Constraint.size() == 1) {
9937     // GCC Constraint Letters
9938     switch (Constraint[0]) {
9939     default: break;
9940     case 'r':   // GENERAL_REGS
9941     case 'l':   // INDEX_REGS
9942       if (VT == MVT::i8)
9943         return std::make_pair(0U, X86::GR8RegisterClass);
9944       if (VT == MVT::i16)
9945         return std::make_pair(0U, X86::GR16RegisterClass);
9946       if (VT == MVT::i32 || !Subtarget->is64Bit())
9947         return std::make_pair(0U, X86::GR32RegisterClass);
9948       return std::make_pair(0U, X86::GR64RegisterClass);
9949     case 'R':   // LEGACY_REGS
9950       if (VT == MVT::i8)
9951         return std::make_pair(0U, X86::GR8_NOREXRegisterClass);
9952       if (VT == MVT::i16)
9953         return std::make_pair(0U, X86::GR16_NOREXRegisterClass);
9954       if (VT == MVT::i32 || !Subtarget->is64Bit())
9955         return std::make_pair(0U, X86::GR32_NOREXRegisterClass);
9956       return std::make_pair(0U, X86::GR64_NOREXRegisterClass);
9957     case 'f':  // FP Stack registers.
9958       // If SSE is enabled for this VT, use f80 to ensure the isel moves the
9959       // value to the correct fpstack register class.
9960       if (VT == MVT::f32 && !isScalarFPTypeInSSEReg(VT))
9961         return std::make_pair(0U, X86::RFP32RegisterClass);
9962       if (VT == MVT::f64 && !isScalarFPTypeInSSEReg(VT))
9963         return std::make_pair(0U, X86::RFP64RegisterClass);
9964       return std::make_pair(0U, X86::RFP80RegisterClass);
9965     case 'y':   // MMX_REGS if MMX allowed.
9966       if (!Subtarget->hasMMX()) break;
9967       return std::make_pair(0U, X86::VR64RegisterClass);
9968     case 'Y':   // SSE_REGS if SSE2 allowed
9969       if (!Subtarget->hasSSE2()) break;
9970       // FALL THROUGH.
9971     case 'x':   // SSE_REGS if SSE1 allowed
9972       if (!Subtarget->hasSSE1()) break;
9973
9974       switch (VT.getSimpleVT().SimpleTy) {
9975       default: break;
9976       // Scalar SSE types.
9977       case MVT::f32:
9978       case MVT::i32:
9979         return std::make_pair(0U, X86::FR32RegisterClass);
9980       case MVT::f64:
9981       case MVT::i64:
9982         return std::make_pair(0U, X86::FR64RegisterClass);
9983       // Vector types.
9984       case MVT::v16i8:
9985       case MVT::v8i16:
9986       case MVT::v4i32:
9987       case MVT::v2i64:
9988       case MVT::v4f32:
9989       case MVT::v2f64:
9990         return std::make_pair(0U, X86::VR128RegisterClass);
9991       }
9992       break;
9993     }
9994   }
9995
9996   // Use the default implementation in TargetLowering to convert the register
9997   // constraint into a member of a register class.
9998   std::pair<unsigned, const TargetRegisterClass*> Res;
9999   Res = TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
10000
10001   // Not found as a standard register?
10002   if (Res.second == 0) {
10003     // Map st(0) -> st(7) -> ST0
10004     if (Constraint.size() == 7 && Constraint[0] == '{' &&
10005         tolower(Constraint[1]) == 's' &&
10006         tolower(Constraint[2]) == 't' &&
10007         Constraint[3] == '(' &&
10008         (Constraint[4] >= '0' && Constraint[4] <= '7') &&
10009         Constraint[5] == ')' &&
10010         Constraint[6] == '}') {
10011
10012       Res.first = X86::ST0+Constraint[4]-'0';
10013       Res.second = X86::RFP80RegisterClass;
10014       return Res;
10015     }
10016
10017     // GCC allows "st(0)" to be called just plain "st".
10018     if (StringRef("{st}").equals_lower(Constraint)) {
10019       Res.first = X86::ST0;
10020       Res.second = X86::RFP80RegisterClass;
10021       return Res;
10022     }
10023
10024     // flags -> EFLAGS
10025     if (StringRef("{flags}").equals_lower(Constraint)) {
10026       Res.first = X86::EFLAGS;
10027       Res.second = X86::CCRRegisterClass;
10028       return Res;
10029     }
10030
10031     // 'A' means EAX + EDX.
10032     if (Constraint == "A") {
10033       Res.first = X86::EAX;
10034       Res.second = X86::GR32_ADRegisterClass;
10035       return Res;
10036     }
10037     return Res;
10038   }
10039
10040   // Otherwise, check to see if this is a register class of the wrong value
10041   // type.  For example, we want to map "{ax},i32" -> {eax}, we don't want it to
10042   // turn into {ax},{dx}.
10043   if (Res.second->hasType(VT))
10044     return Res;   // Correct type already, nothing to do.
10045
10046   // All of the single-register GCC register classes map their values onto
10047   // 16-bit register pieces "ax","dx","cx","bx","si","di","bp","sp".  If we
10048   // really want an 8-bit or 32-bit register, map to the appropriate register
10049   // class and return the appropriate register.
10050   if (Res.second == X86::GR16RegisterClass) {
10051     if (VT == MVT::i8) {
10052       unsigned DestReg = 0;
10053       switch (Res.first) {
10054       default: break;
10055       case X86::AX: DestReg = X86::AL; break;
10056       case X86::DX: DestReg = X86::DL; break;
10057       case X86::CX: DestReg = X86::CL; break;
10058       case X86::BX: DestReg = X86::BL; break;
10059       }
10060       if (DestReg) {
10061         Res.first = DestReg;
10062         Res.second = X86::GR8RegisterClass;
10063       }
10064     } else if (VT == MVT::i32) {
10065       unsigned DestReg = 0;
10066       switch (Res.first) {
10067       default: break;
10068       case X86::AX: DestReg = X86::EAX; break;
10069       case X86::DX: DestReg = X86::EDX; break;
10070       case X86::CX: DestReg = X86::ECX; break;
10071       case X86::BX: DestReg = X86::EBX; break;
10072       case X86::SI: DestReg = X86::ESI; break;
10073       case X86::DI: DestReg = X86::EDI; break;
10074       case X86::BP: DestReg = X86::EBP; break;
10075       case X86::SP: DestReg = X86::ESP; break;
10076       }
10077       if (DestReg) {
10078         Res.first = DestReg;
10079         Res.second = X86::GR32RegisterClass;
10080       }
10081     } else if (VT == MVT::i64) {
10082       unsigned DestReg = 0;
10083       switch (Res.first) {
10084       default: break;
10085       case X86::AX: DestReg = X86::RAX; break;
10086       case X86::DX: DestReg = X86::RDX; break;
10087       case X86::CX: DestReg = X86::RCX; break;
10088       case X86::BX: DestReg = X86::RBX; break;
10089       case X86::SI: DestReg = X86::RSI; break;
10090       case X86::DI: DestReg = X86::RDI; break;
10091       case X86::BP: DestReg = X86::RBP; break;
10092       case X86::SP: DestReg = X86::RSP; break;
10093       }
10094       if (DestReg) {
10095         Res.first = DestReg;
10096         Res.second = X86::GR64RegisterClass;
10097       }
10098     }
10099   } else if (Res.second == X86::FR32RegisterClass ||
10100              Res.second == X86::FR64RegisterClass ||
10101              Res.second == X86::VR128RegisterClass) {
10102     // Handle references to XMM physical registers that got mapped into the
10103     // wrong class.  This can happen with constraints like {xmm0} where the
10104     // target independent register mapper will just pick the first match it can
10105     // find, ignoring the required type.
10106     if (VT == MVT::f32)
10107       Res.second = X86::FR32RegisterClass;
10108     else if (VT == MVT::f64)
10109       Res.second = X86::FR64RegisterClass;
10110     else if (X86::VR128RegisterClass->hasType(VT))
10111       Res.second = X86::VR128RegisterClass;
10112   }
10113
10114   return Res;
10115 }
10116
10117 //===----------------------------------------------------------------------===//
10118 //                           X86 Widen vector type
10119 //===----------------------------------------------------------------------===//
10120
10121 /// getWidenVectorType: given a vector type, returns the type to widen
10122 /// to (e.g., v7i8 to v8i8). If the vector type is legal, it returns itself.
10123 /// If there is no vector type that we want to widen to, returns MVT::Other
10124 /// When and where to widen is target dependent based on the cost of
10125 /// scalarizing vs using the wider vector type.
10126
10127 EVT X86TargetLowering::getWidenVectorType(EVT VT) const {
10128   assert(VT.isVector());
10129   if (isTypeLegal(VT))
10130     return VT;
10131
10132   // TODO: In computeRegisterProperty, we can compute the list of legal vector
10133   //       type based on element type.  This would speed up our search (though
10134   //       it may not be worth it since the size of the list is relatively
10135   //       small).
10136   EVT EltVT = VT.getVectorElementType();
10137   unsigned NElts = VT.getVectorNumElements();
10138
10139   // On X86, it make sense to widen any vector wider than 1
10140   if (NElts <= 1)
10141     return MVT::Other;
10142
10143   for (unsigned nVT = MVT::FIRST_VECTOR_VALUETYPE;
10144        nVT <= MVT::LAST_VECTOR_VALUETYPE; ++nVT) {
10145     EVT SVT = (MVT::SimpleValueType)nVT;
10146
10147     if (isTypeLegal(SVT) &&
10148         SVT.getVectorElementType() == EltVT &&
10149         SVT.getVectorNumElements() > NElts)
10150       return SVT;
10151   }
10152   return MVT::Other;
10153 }