Delete dead code.
[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   } else {
1700     BytesToPopOnReturn  = 0; // Callee pops nothing.
1701     // If this is an sret function, the return should pop the hidden pointer.
1702     if (!Is64Bit && CallConv != CallingConv::Fast && ArgsAreStructReturn(Ins))
1703       BytesToPopOnReturn = 4;
1704   }
1705
1706   if (!Is64Bit) {
1707     RegSaveFrameIndex = 0xAAAAAAA;   // RegSaveFrameIndex is X86-64 only.
1708     if (CallConv == CallingConv::X86_FastCall)
1709       VarArgsFrameIndex = 0xAAAAAAA;   // fastcc functions can't have varargs.
1710   }
1711
1712   FuncInfo->setBytesToPopOnReturn(BytesToPopOnReturn);
1713
1714   return Chain;
1715 }
1716
1717 SDValue
1718 X86TargetLowering::LowerMemOpCallTo(SDValue Chain,
1719                                     SDValue StackPtr, SDValue Arg,
1720                                     DebugLoc dl, SelectionDAG &DAG,
1721                                     const CCValAssign &VA,
1722                                     ISD::ArgFlagsTy Flags) {
1723   const unsigned FirstStackArgOffset = (Subtarget->isTargetWin64() ? 32 : 0);
1724   unsigned LocMemOffset = FirstStackArgOffset + VA.getLocMemOffset();
1725   SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset);
1726   PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, PtrOff);
1727   if (Flags.isByVal()) {
1728     return CreateCopyOfByValArgument(Arg, PtrOff, Chain, Flags, DAG, dl);
1729   }
1730   return DAG.getStore(Chain, dl, Arg, PtrOff,
1731                       PseudoSourceValue::getStack(), LocMemOffset);
1732 }
1733
1734 /// EmitTailCallLoadRetAddr - Emit a load of return address if tail call
1735 /// optimization is performed and it is required.
1736 SDValue
1737 X86TargetLowering::EmitTailCallLoadRetAddr(SelectionDAG &DAG,
1738                                            SDValue &OutRetAddr, SDValue Chain,
1739                                            bool IsTailCall, bool Is64Bit,
1740                                            int FPDiff, DebugLoc dl) {
1741   if (!IsTailCall || FPDiff==0) return Chain;
1742
1743   // Adjust the Return address stack slot.
1744   EVT VT = getPointerTy();
1745   OutRetAddr = getReturnAddressFrameIndex(DAG);
1746
1747   // Load the "old" Return address.
1748   OutRetAddr = DAG.getLoad(VT, dl, Chain, OutRetAddr, NULL, 0);
1749   return SDValue(OutRetAddr.getNode(), 1);
1750 }
1751
1752 /// EmitTailCallStoreRetAddr - Emit a store of the return adress if tail call
1753 /// optimization is performed and it is required (FPDiff!=0).
1754 static SDValue
1755 EmitTailCallStoreRetAddr(SelectionDAG & DAG, MachineFunction &MF,
1756                          SDValue Chain, SDValue RetAddrFrIdx,
1757                          bool Is64Bit, int FPDiff, DebugLoc dl) {
1758   // Store the return address to the appropriate stack slot.
1759   if (!FPDiff) return Chain;
1760   // Calculate the new stack slot for the return address.
1761   int SlotSize = Is64Bit ? 8 : 4;
1762   int NewReturnAddrFI =
1763     MF.getFrameInfo()->CreateFixedObject(SlotSize, FPDiff-SlotSize, true,false);
1764   EVT VT = Is64Bit ? MVT::i64 : MVT::i32;
1765   SDValue NewRetAddrFrIdx = DAG.getFrameIndex(NewReturnAddrFI, VT);
1766   Chain = DAG.getStore(Chain, dl, RetAddrFrIdx, NewRetAddrFrIdx,
1767                        PseudoSourceValue::getFixedStack(NewReturnAddrFI), 0);
1768   return Chain;
1769 }
1770
1771 SDValue
1772 X86TargetLowering::LowerCall(SDValue Chain, SDValue Callee,
1773                              CallingConv::ID CallConv, bool isVarArg,
1774                              bool isTailCall,
1775                              const SmallVectorImpl<ISD::OutputArg> &Outs,
1776                              const SmallVectorImpl<ISD::InputArg> &Ins,
1777                              DebugLoc dl, SelectionDAG &DAG,
1778                              SmallVectorImpl<SDValue> &InVals) {
1779
1780   MachineFunction &MF = DAG.getMachineFunction();
1781   bool Is64Bit        = Subtarget->is64Bit();
1782   bool IsStructRet    = CallIsStructReturn(Outs);
1783
1784   assert((!isTailCall || X86::IsEligibleForTailCallOpt(CallConv)) &&
1785          "Call is not eligible for tail call optimization!");
1786   assert(!(isVarArg && CallConv == CallingConv::Fast) &&
1787          "Var args not supported with calling convention fastcc");
1788
1789   // Analyze operands of the call, assigning locations to each operand.
1790   SmallVector<CCValAssign, 16> ArgLocs;
1791   CCState CCInfo(CallConv, isVarArg, getTargetMachine(),
1792                  ArgLocs, *DAG.getContext());
1793   CCInfo.AnalyzeCallOperands(Outs, CCAssignFnForNode(CallConv));
1794
1795   // Get a count of how many bytes are to be pushed on the stack.
1796   unsigned NumBytes = CCInfo.getNextStackOffset();
1797   if (X86::IsEligibleForTailCallOpt(CallConv))
1798     NumBytes = GetAlignedArgumentStackSize(NumBytes, DAG);
1799
1800   int FPDiff = 0;
1801   if (isTailCall) {
1802     // Lower arguments at fp - stackoffset + fpdiff.
1803     unsigned NumBytesCallerPushed =
1804       MF.getInfo<X86MachineFunctionInfo>()->getBytesToPopOnReturn();
1805     FPDiff = NumBytesCallerPushed - NumBytes;
1806
1807     // Set the delta of movement of the returnaddr stackslot.
1808     // But only set if delta is greater than previous delta.
1809     if (FPDiff < (MF.getInfo<X86MachineFunctionInfo>()->getTCReturnAddrDelta()))
1810       MF.getInfo<X86MachineFunctionInfo>()->setTCReturnAddrDelta(FPDiff);
1811   }
1812
1813   Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes, true));
1814
1815   SDValue RetAddrFrIdx;
1816   // Load return adress for tail calls.
1817   Chain = EmitTailCallLoadRetAddr(DAG, RetAddrFrIdx, Chain, isTailCall, Is64Bit,
1818                                   FPDiff, dl);
1819
1820   SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
1821   SmallVector<SDValue, 8> MemOpChains;
1822   SDValue StackPtr;
1823
1824   // Walk the register/memloc assignments, inserting copies/loads.  In the case
1825   // of tail call optimization arguments are handle later.
1826   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
1827     CCValAssign &VA = ArgLocs[i];
1828     EVT RegVT = VA.getLocVT();
1829     SDValue Arg = Outs[i].Val;
1830     ISD::ArgFlagsTy Flags = Outs[i].Flags;
1831     bool isByVal = Flags.isByVal();
1832
1833     // Promote the value if needed.
1834     switch (VA.getLocInfo()) {
1835     default: llvm_unreachable("Unknown loc info!");
1836     case CCValAssign::Full: break;
1837     case CCValAssign::SExt:
1838       Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, RegVT, Arg);
1839       break;
1840     case CCValAssign::ZExt:
1841       Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, RegVT, Arg);
1842       break;
1843     case CCValAssign::AExt:
1844       if (RegVT.isVector() && RegVT.getSizeInBits() == 128) {
1845         // Special case: passing MMX values in XMM registers.
1846         Arg = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::i64, Arg);
1847         Arg = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64, Arg);
1848         Arg = getMOVL(DAG, dl, MVT::v2i64, DAG.getUNDEF(MVT::v2i64), Arg);
1849       } else
1850         Arg = DAG.getNode(ISD::ANY_EXTEND, dl, RegVT, Arg);
1851       break;
1852     case CCValAssign::BCvt:
1853       Arg = DAG.getNode(ISD::BIT_CONVERT, dl, RegVT, Arg);
1854       break;
1855     case CCValAssign::Indirect: {
1856       // Store the argument.
1857       SDValue SpillSlot = DAG.CreateStackTemporary(VA.getValVT());
1858       int FI = cast<FrameIndexSDNode>(SpillSlot)->getIndex();
1859       Chain = DAG.getStore(Chain, dl, Arg, SpillSlot,
1860                            PseudoSourceValue::getFixedStack(FI), 0);
1861       Arg = SpillSlot;
1862       break;
1863     }
1864     }
1865
1866     if (VA.isRegLoc()) {
1867       RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
1868     } else {
1869       if (!isTailCall || (isTailCall && isByVal)) {
1870         assert(VA.isMemLoc());
1871         if (StackPtr.getNode() == 0)
1872           StackPtr = DAG.getCopyFromReg(Chain, dl, X86StackPtr, getPointerTy());
1873
1874         MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg,
1875                                                dl, DAG, VA, Flags));
1876       }
1877     }
1878   }
1879
1880   if (!MemOpChains.empty())
1881     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
1882                         &MemOpChains[0], MemOpChains.size());
1883
1884   // Build a sequence of copy-to-reg nodes chained together with token chain
1885   // and flag operands which copy the outgoing args into registers.
1886   SDValue InFlag;
1887   // Tail call byval lowering might overwrite argument registers so in case of
1888   // tail call optimization the copies to registers are lowered later.
1889   if (!isTailCall)
1890     for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
1891       Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
1892                                RegsToPass[i].second, InFlag);
1893       InFlag = Chain.getValue(1);
1894     }
1895
1896
1897   if (Subtarget->isPICStyleGOT()) {
1898     // ELF / PIC requires GOT in the EBX register before function calls via PLT
1899     // GOT pointer.
1900     if (!isTailCall) {
1901       Chain = DAG.getCopyToReg(Chain, dl, X86::EBX,
1902                                DAG.getNode(X86ISD::GlobalBaseReg,
1903                                            DebugLoc::getUnknownLoc(),
1904                                            getPointerTy()),
1905                                InFlag);
1906       InFlag = Chain.getValue(1);
1907     } else {
1908       // If we are tail calling and generating PIC/GOT style code load the
1909       // address of the callee into ECX. The value in ecx is used as target of
1910       // the tail jump. This is done to circumvent the ebx/callee-saved problem
1911       // for tail calls on PIC/GOT architectures. Normally we would just put the
1912       // address of GOT into ebx and then call target@PLT. But for tail calls
1913       // ebx would be restored (since ebx is callee saved) before jumping to the
1914       // target@PLT.
1915
1916       // Note: The actual moving to ECX is done further down.
1917       GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee);
1918       if (G && !G->getGlobal()->hasHiddenVisibility() &&
1919           !G->getGlobal()->hasProtectedVisibility())
1920         Callee = LowerGlobalAddress(Callee, DAG);
1921       else if (isa<ExternalSymbolSDNode>(Callee))
1922         Callee = LowerExternalSymbol(Callee, DAG);
1923     }
1924   }
1925
1926   if (Is64Bit && isVarArg) {
1927     // From AMD64 ABI document:
1928     // For calls that may call functions that use varargs or stdargs
1929     // (prototype-less calls or calls to functions containing ellipsis (...) in
1930     // the declaration) %al is used as hidden argument to specify the number
1931     // of SSE registers used. The contents of %al do not need to match exactly
1932     // the number of registers, but must be an ubound on the number of SSE
1933     // registers used and is in the range 0 - 8 inclusive.
1934
1935     // FIXME: Verify this on Win64
1936     // Count the number of XMM registers allocated.
1937     static const unsigned XMMArgRegs[] = {
1938       X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
1939       X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
1940     };
1941     unsigned NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs, 8);
1942     assert((Subtarget->hasSSE1() || !NumXMMRegs)
1943            && "SSE registers cannot be used when SSE is disabled");
1944
1945     Chain = DAG.getCopyToReg(Chain, dl, X86::AL,
1946                              DAG.getConstant(NumXMMRegs, MVT::i8), InFlag);
1947     InFlag = Chain.getValue(1);
1948   }
1949
1950
1951   // For tail calls lower the arguments to the 'real' stack slot.
1952   if (isTailCall) {
1953     // Force all the incoming stack arguments to be loaded from the stack
1954     // before any new outgoing arguments are stored to the stack, because the
1955     // outgoing stack slots may alias the incoming argument stack slots, and
1956     // the alias isn't otherwise explicit. This is slightly more conservative
1957     // than necessary, because it means that each store effectively depends
1958     // on every argument instead of just those arguments it would clobber.
1959     SDValue ArgChain = DAG.getStackArgumentTokenFactor(Chain);
1960
1961     SmallVector<SDValue, 8> MemOpChains2;
1962     SDValue FIN;
1963     int FI = 0;
1964     // Do not flag preceeding copytoreg stuff together with the following stuff.
1965     InFlag = SDValue();
1966     for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
1967       CCValAssign &VA = ArgLocs[i];
1968       if (!VA.isRegLoc()) {
1969         assert(VA.isMemLoc());
1970         SDValue Arg = Outs[i].Val;
1971         ISD::ArgFlagsTy Flags = Outs[i].Flags;
1972         // Create frame index.
1973         int32_t Offset = VA.getLocMemOffset()+FPDiff;
1974         uint32_t OpSize = (VA.getLocVT().getSizeInBits()+7)/8;
1975         FI = MF.getFrameInfo()->CreateFixedObject(OpSize, Offset, true, false);
1976         FIN = DAG.getFrameIndex(FI, getPointerTy());
1977
1978         if (Flags.isByVal()) {
1979           // Copy relative to framepointer.
1980           SDValue Source = DAG.getIntPtrConstant(VA.getLocMemOffset());
1981           if (StackPtr.getNode() == 0)
1982             StackPtr = DAG.getCopyFromReg(Chain, dl, X86StackPtr,
1983                                           getPointerTy());
1984           Source = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, Source);
1985
1986           MemOpChains2.push_back(CreateCopyOfByValArgument(Source, FIN,
1987                                                            ArgChain,
1988                                                            Flags, DAG, dl));
1989         } else {
1990           // Store relative to framepointer.
1991           MemOpChains2.push_back(
1992             DAG.getStore(ArgChain, dl, Arg, FIN,
1993                          PseudoSourceValue::getFixedStack(FI), 0));
1994         }
1995       }
1996     }
1997
1998     if (!MemOpChains2.empty())
1999       Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
2000                           &MemOpChains2[0], MemOpChains2.size());
2001
2002     // Copy arguments to their registers.
2003     for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
2004       Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
2005                                RegsToPass[i].second, InFlag);
2006       InFlag = Chain.getValue(1);
2007     }
2008     InFlag =SDValue();
2009
2010     // Store the return address to the appropriate stack slot.
2011     Chain = EmitTailCallStoreRetAddr(DAG, MF, Chain, RetAddrFrIdx, Is64Bit,
2012                                      FPDiff, dl);
2013   }
2014
2015   bool WasGlobalOrExternal = false;
2016   if (getTargetMachine().getCodeModel() == CodeModel::Large) {
2017     assert(Is64Bit && "Large code model is only legal in 64-bit mode.");
2018     // In the 64-bit large code model, we have to make all calls
2019     // through a register, since the call instruction's 32-bit
2020     // pc-relative offset may not be large enough to hold the whole
2021     // address.
2022   } else if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
2023     WasGlobalOrExternal = true;
2024     // If the callee is a GlobalAddress node (quite common, every direct call
2025     // is) turn it into a TargetGlobalAddress node so that legalize doesn't hack
2026     // it.
2027
2028     // We should use extra load for direct calls to dllimported functions in
2029     // non-JIT mode.
2030     GlobalValue *GV = G->getGlobal();
2031     if (!GV->hasDLLImportLinkage()) {
2032       unsigned char OpFlags = 0;
2033
2034       // On ELF targets, in both X86-64 and X86-32 mode, direct calls to
2035       // external symbols most go through the PLT in PIC mode.  If the symbol
2036       // has hidden or protected visibility, or if it is static or local, then
2037       // we don't need to use the PLT - we can directly call it.
2038       if (Subtarget->isTargetELF() &&
2039           getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
2040           GV->hasDefaultVisibility() && !GV->hasLocalLinkage()) {
2041         OpFlags = X86II::MO_PLT;
2042       } else if (Subtarget->isPICStyleStubAny() &&
2043                (GV->isDeclaration() || GV->isWeakForLinker()) &&
2044                Subtarget->getDarwinVers() < 9) {
2045         // PC-relative references to external symbols should go through $stub,
2046         // unless we're building with the leopard linker or later, which
2047         // automatically synthesizes these stubs.
2048         OpFlags = X86II::MO_DARWIN_STUB;
2049       }
2050
2051       Callee = DAG.getTargetGlobalAddress(GV, getPointerTy(),
2052                                           G->getOffset(), OpFlags);
2053     }
2054   } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
2055     WasGlobalOrExternal = true;
2056     unsigned char OpFlags = 0;
2057
2058     // On ELF targets, in either X86-64 or X86-32 mode, direct calls to external
2059     // symbols should go through the PLT.
2060     if (Subtarget->isTargetELF() &&
2061         getTargetMachine().getRelocationModel() == Reloc::PIC_) {
2062       OpFlags = X86II::MO_PLT;
2063     } else if (Subtarget->isPICStyleStubAny() &&
2064              Subtarget->getDarwinVers() < 9) {
2065       // PC-relative references to external symbols should go through $stub,
2066       // unless we're building with the leopard linker or later, which
2067       // automatically synthesizes these stubs.
2068       OpFlags = X86II::MO_DARWIN_STUB;
2069     }
2070
2071     Callee = DAG.getTargetExternalSymbol(S->getSymbol(), getPointerTy(),
2072                                          OpFlags);
2073   }
2074
2075   if (isTailCall && !WasGlobalOrExternal) {
2076     unsigned Opc = Is64Bit ? X86::R11 : X86::EAX;
2077
2078     Chain = DAG.getCopyToReg(Chain,  dl,
2079                              DAG.getRegister(Opc, getPointerTy()),
2080                              Callee,InFlag);
2081     Callee = DAG.getRegister(Opc, getPointerTy());
2082     // Add register as live out.
2083     MF.getRegInfo().addLiveOut(Opc);
2084   }
2085
2086   // Returns a chain & a flag for retval copy to use.
2087   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Flag);
2088   SmallVector<SDValue, 8> Ops;
2089
2090   if (isTailCall) {
2091     Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, true),
2092                            DAG.getIntPtrConstant(0, true), InFlag);
2093     InFlag = Chain.getValue(1);
2094   }
2095
2096   Ops.push_back(Chain);
2097   Ops.push_back(Callee);
2098
2099   if (isTailCall)
2100     Ops.push_back(DAG.getConstant(FPDiff, MVT::i32));
2101
2102   // Add argument registers to the end of the list so that they are known live
2103   // into the call.
2104   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
2105     Ops.push_back(DAG.getRegister(RegsToPass[i].first,
2106                                   RegsToPass[i].second.getValueType()));
2107
2108   // Add an implicit use GOT pointer in EBX.
2109   if (!isTailCall && Subtarget->isPICStyleGOT())
2110     Ops.push_back(DAG.getRegister(X86::EBX, getPointerTy()));
2111
2112   // Add an implicit use of AL for x86 vararg functions.
2113   if (Is64Bit && isVarArg)
2114     Ops.push_back(DAG.getRegister(X86::AL, MVT::i8));
2115
2116   if (InFlag.getNode())
2117     Ops.push_back(InFlag);
2118
2119   if (isTailCall) {
2120     // If this is the first return lowered for this function, add the regs
2121     // to the liveout set for the function.
2122     if (MF.getRegInfo().liveout_empty()) {
2123       SmallVector<CCValAssign, 16> RVLocs;
2124       CCState CCInfo(CallConv, isVarArg, getTargetMachine(), RVLocs,
2125                      *DAG.getContext());
2126       CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
2127       for (unsigned i = 0; i != RVLocs.size(); ++i)
2128         if (RVLocs[i].isRegLoc())
2129           MF.getRegInfo().addLiveOut(RVLocs[i].getLocReg());
2130     }
2131
2132     assert(((Callee.getOpcode() == ISD::Register &&
2133                (cast<RegisterSDNode>(Callee)->getReg() == X86::EAX ||
2134                 cast<RegisterSDNode>(Callee)->getReg() == X86::R11)) ||
2135               Callee.getOpcode() == ISD::TargetExternalSymbol ||
2136               Callee.getOpcode() == ISD::TargetGlobalAddress) &&
2137            "Expecting a global address, external symbol, or scratch register");
2138
2139     return DAG.getNode(X86ISD::TC_RETURN, dl,
2140                        NodeTys, &Ops[0], Ops.size());
2141   }
2142
2143   Chain = DAG.getNode(X86ISD::CALL, dl, NodeTys, &Ops[0], Ops.size());
2144   InFlag = Chain.getValue(1);
2145
2146   // Create the CALLSEQ_END node.
2147   unsigned NumBytesForCalleeToPush;
2148   if (IsCalleePop(isVarArg, CallConv))
2149     NumBytesForCalleeToPush = NumBytes;    // Callee pops everything
2150   else if (!Is64Bit && CallConv != CallingConv::Fast && IsStructRet)
2151     // If this is is a call to a struct-return function, the callee
2152     // pops the hidden struct pointer, so we have to push it back.
2153     // This is common for Darwin/X86, Linux & Mingw32 targets.
2154     NumBytesForCalleeToPush = 4;
2155   else
2156     NumBytesForCalleeToPush = 0;  // Callee pops nothing.
2157
2158   // Returns a flag for retval copy to use.
2159   Chain = DAG.getCALLSEQ_END(Chain,
2160                              DAG.getIntPtrConstant(NumBytes, true),
2161                              DAG.getIntPtrConstant(NumBytesForCalleeToPush,
2162                                                    true),
2163                              InFlag);
2164   InFlag = Chain.getValue(1);
2165
2166   // Handle result values, copying them out of physregs into vregs that we
2167   // return.
2168   return LowerCallResult(Chain, InFlag, CallConv, isVarArg,
2169                          Ins, dl, DAG, InVals);
2170 }
2171
2172
2173 //===----------------------------------------------------------------------===//
2174 //                Fast Calling Convention (tail call) implementation
2175 //===----------------------------------------------------------------------===//
2176
2177 //  Like std call, callee cleans arguments, convention except that ECX is
2178 //  reserved for storing the tail called function address. Only 2 registers are
2179 //  free for argument passing (inreg). Tail call optimization is performed
2180 //  provided:
2181 //                * tailcallopt is enabled
2182 //                * caller/callee are fastcc
2183 //  On X86_64 architecture with GOT-style position independent code only local
2184 //  (within module) calls are supported at the moment.
2185 //  To keep the stack aligned according to platform abi the function
2186 //  GetAlignedArgumentStackSize ensures that argument delta is always multiples
2187 //  of stack alignment. (Dynamic linkers need this - darwin's dyld for example)
2188 //  If a tail called function callee has more arguments than the caller the
2189 //  caller needs to make sure that there is room to move the RETADDR to. This is
2190 //  achieved by reserving an area the size of the argument delta right after the
2191 //  original REtADDR, but before the saved framepointer or the spilled registers
2192 //  e.g. caller(arg1, arg2) calls callee(arg1, arg2,arg3,arg4)
2193 //  stack layout:
2194 //    arg1
2195 //    arg2
2196 //    RETADDR
2197 //    [ new RETADDR
2198 //      move area ]
2199 //    (possible EBP)
2200 //    ESI
2201 //    EDI
2202 //    local1 ..
2203
2204 /// GetAlignedArgumentStackSize - Make the stack size align e.g 16n + 12 aligned
2205 /// for a 16 byte align requirement.
2206 unsigned X86TargetLowering::GetAlignedArgumentStackSize(unsigned StackSize,
2207                                                         SelectionDAG& DAG) {
2208   MachineFunction &MF = DAG.getMachineFunction();
2209   const TargetMachine &TM = MF.getTarget();
2210   const TargetFrameInfo &TFI = *TM.getFrameInfo();
2211   unsigned StackAlignment = TFI.getStackAlignment();
2212   uint64_t AlignMask = StackAlignment - 1;
2213   int64_t Offset = StackSize;
2214   uint64_t SlotSize = TD->getPointerSize();
2215   if ( (Offset & AlignMask) <= (StackAlignment - SlotSize) ) {
2216     // Number smaller than 12 so just add the difference.
2217     Offset += ((StackAlignment - SlotSize) - (Offset & AlignMask));
2218   } else {
2219     // Mask out lower bits, add stackalignment once plus the 12 bytes.
2220     Offset = ((~AlignMask) & Offset) + StackAlignment +
2221       (StackAlignment-SlotSize);
2222   }
2223   return Offset;
2224 }
2225
2226 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
2227 /// for tail call optimization. Targets which want to do tail call
2228 /// optimization should implement this function.
2229 bool
2230 X86TargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
2231                                                      CallingConv::ID CalleeCC,
2232                                                      bool isVarArg,
2233                                       const SmallVectorImpl<ISD::InputArg> &Ins,
2234                                                      SelectionDAG& DAG) const {
2235   return X86::IsEligibleForTailCallOpt(CalleeCC) &&
2236     DAG.getMachineFunction().getFunction()->getCallingConv() == CalleeCC;
2237 }
2238
2239 FastISel *
2240 X86TargetLowering::createFastISel(MachineFunction &mf, MachineModuleInfo *mmo,
2241                             DwarfWriter *dw,
2242                             DenseMap<const Value *, unsigned> &vm,
2243                             DenseMap<const BasicBlock*, MachineBasicBlock*> &bm,
2244                             DenseMap<const AllocaInst *, int> &am
2245 #ifndef NDEBUG
2246                           , SmallSet<Instruction*, 8> &cil
2247 #endif
2248                                   ) {
2249   return X86::createFastISel(mf, mmo, dw, vm, bm, am
2250 #ifndef NDEBUG
2251                              , cil
2252 #endif
2253                              );
2254 }
2255
2256
2257 //===----------------------------------------------------------------------===//
2258 //                           Other Lowering Hooks
2259 //===----------------------------------------------------------------------===//
2260
2261
2262 SDValue X86TargetLowering::getReturnAddressFrameIndex(SelectionDAG &DAG) {
2263   MachineFunction &MF = DAG.getMachineFunction();
2264   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
2265   int ReturnAddrIndex = FuncInfo->getRAIndex();
2266
2267   if (ReturnAddrIndex == 0) {
2268     // Set up a frame object for the return address.
2269     uint64_t SlotSize = TD->getPointerSize();
2270     ReturnAddrIndex = MF.getFrameInfo()->CreateFixedObject(SlotSize, -SlotSize,
2271                                                            true, false);
2272     FuncInfo->setRAIndex(ReturnAddrIndex);
2273   }
2274
2275   return DAG.getFrameIndex(ReturnAddrIndex, getPointerTy());
2276 }
2277
2278
2279 bool X86::isOffsetSuitableForCodeModel(int64_t Offset, CodeModel::Model M,
2280                                        bool hasSymbolicDisplacement) {
2281   // Offset should fit into 32 bit immediate field.
2282   if (!isInt32(Offset))
2283     return false;
2284
2285   // If we don't have a symbolic displacement - we don't have any extra
2286   // restrictions.
2287   if (!hasSymbolicDisplacement)
2288     return true;
2289
2290   // FIXME: Some tweaks might be needed for medium code model.
2291   if (M != CodeModel::Small && M != CodeModel::Kernel)
2292     return false;
2293
2294   // For small code model we assume that latest object is 16MB before end of 31
2295   // bits boundary. We may also accept pretty large negative constants knowing
2296   // that all objects are in the positive half of address space.
2297   if (M == CodeModel::Small && Offset < 16*1024*1024)
2298     return true;
2299
2300   // For kernel code model we know that all object resist in the negative half
2301   // of 32bits address space. We may not accept negative offsets, since they may
2302   // be just off and we may accept pretty large positive ones.
2303   if (M == CodeModel::Kernel && Offset > 0)
2304     return true;
2305
2306   return false;
2307 }
2308
2309 bool X86::IsEligibleForTailCallOpt(CallingConv::ID CC) {
2310   return PerformTailCallOpt && CC == CallingConv::Fast;
2311 }
2312
2313 /// TranslateX86CC - do a one to one translation of a ISD::CondCode to the X86
2314 /// specific condition code, returning the condition code and the LHS/RHS of the
2315 /// comparison to make.
2316 static unsigned TranslateX86CC(ISD::CondCode SetCCOpcode, bool isFP,
2317                                SDValue &LHS, SDValue &RHS, SelectionDAG &DAG) {
2318   if (!isFP) {
2319     if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) {
2320       if (SetCCOpcode == ISD::SETGT && RHSC->isAllOnesValue()) {
2321         // X > -1   -> X == 0, jump !sign.
2322         RHS = DAG.getConstant(0, RHS.getValueType());
2323         return X86::COND_NS;
2324       } else if (SetCCOpcode == ISD::SETLT && RHSC->isNullValue()) {
2325         // X < 0   -> X == 0, jump on sign.
2326         return X86::COND_S;
2327       } else if (SetCCOpcode == ISD::SETLT && RHSC->getZExtValue() == 1) {
2328         // X < 1   -> X <= 0
2329         RHS = DAG.getConstant(0, RHS.getValueType());
2330         return X86::COND_LE;
2331       }
2332     }
2333
2334     switch (SetCCOpcode) {
2335     default: llvm_unreachable("Invalid integer condition!");
2336     case ISD::SETEQ:  return X86::COND_E;
2337     case ISD::SETGT:  return X86::COND_G;
2338     case ISD::SETGE:  return X86::COND_GE;
2339     case ISD::SETLT:  return X86::COND_L;
2340     case ISD::SETLE:  return X86::COND_LE;
2341     case ISD::SETNE:  return X86::COND_NE;
2342     case ISD::SETULT: return X86::COND_B;
2343     case ISD::SETUGT: return X86::COND_A;
2344     case ISD::SETULE: return X86::COND_BE;
2345     case ISD::SETUGE: return X86::COND_AE;
2346     }
2347   }
2348
2349   // First determine if it is required or is profitable to flip the operands.
2350
2351   // If LHS is a foldable load, but RHS is not, flip the condition.
2352   if ((ISD::isNON_EXTLoad(LHS.getNode()) && LHS.hasOneUse()) &&
2353       !(ISD::isNON_EXTLoad(RHS.getNode()) && RHS.hasOneUse())) {
2354     SetCCOpcode = getSetCCSwappedOperands(SetCCOpcode);
2355     std::swap(LHS, RHS);
2356   }
2357
2358   switch (SetCCOpcode) {
2359   default: break;
2360   case ISD::SETOLT:
2361   case ISD::SETOLE:
2362   case ISD::SETUGT:
2363   case ISD::SETUGE:
2364     std::swap(LHS, RHS);
2365     break;
2366   }
2367
2368   // On a floating point condition, the flags are set as follows:
2369   // ZF  PF  CF   op
2370   //  0 | 0 | 0 | X > Y
2371   //  0 | 0 | 1 | X < Y
2372   //  1 | 0 | 0 | X == Y
2373   //  1 | 1 | 1 | unordered
2374   switch (SetCCOpcode) {
2375   default: llvm_unreachable("Condcode should be pre-legalized away");
2376   case ISD::SETUEQ:
2377   case ISD::SETEQ:   return X86::COND_E;
2378   case ISD::SETOLT:              // flipped
2379   case ISD::SETOGT:
2380   case ISD::SETGT:   return X86::COND_A;
2381   case ISD::SETOLE:              // flipped
2382   case ISD::SETOGE:
2383   case ISD::SETGE:   return X86::COND_AE;
2384   case ISD::SETUGT:              // flipped
2385   case ISD::SETULT:
2386   case ISD::SETLT:   return X86::COND_B;
2387   case ISD::SETUGE:              // flipped
2388   case ISD::SETULE:
2389   case ISD::SETLE:   return X86::COND_BE;
2390   case ISD::SETONE:
2391   case ISD::SETNE:   return X86::COND_NE;
2392   case ISD::SETUO:   return X86::COND_P;
2393   case ISD::SETO:    return X86::COND_NP;
2394   case ISD::SETOEQ:
2395   case ISD::SETUNE:  return X86::COND_INVALID;
2396   }
2397 }
2398
2399 /// hasFPCMov - is there a floating point cmov for the specific X86 condition
2400 /// code. Current x86 isa includes the following FP cmov instructions:
2401 /// fcmovb, fcomvbe, fcomve, fcmovu, fcmovae, fcmova, fcmovne, fcmovnu.
2402 static bool hasFPCMov(unsigned X86CC) {
2403   switch (X86CC) {
2404   default:
2405     return false;
2406   case X86::COND_B:
2407   case X86::COND_BE:
2408   case X86::COND_E:
2409   case X86::COND_P:
2410   case X86::COND_A:
2411   case X86::COND_AE:
2412   case X86::COND_NE:
2413   case X86::COND_NP:
2414     return true;
2415   }
2416 }
2417
2418 /// isFPImmLegal - Returns true if the target can instruction select the
2419 /// specified FP immediate natively. If false, the legalizer will
2420 /// materialize the FP immediate as a load from a constant pool.
2421 bool X86TargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
2422   for (unsigned i = 0, e = LegalFPImmediates.size(); i != e; ++i) {
2423     if (Imm.bitwiseIsEqual(LegalFPImmediates[i]))
2424       return true;
2425   }
2426   return false;
2427 }
2428
2429 /// isUndefOrInRange - Return true if Val is undef or if its value falls within
2430 /// the specified range (L, H].
2431 static bool isUndefOrInRange(int Val, int Low, int Hi) {
2432   return (Val < 0) || (Val >= Low && Val < Hi);
2433 }
2434
2435 /// isUndefOrEqual - Val is either less than zero (undef) or equal to the
2436 /// specified value.
2437 static bool isUndefOrEqual(int Val, int CmpVal) {
2438   if (Val < 0 || Val == CmpVal)
2439     return true;
2440   return false;
2441 }
2442
2443 /// isPSHUFDMask - Return true if the node specifies a shuffle of elements that
2444 /// is suitable for input to PSHUFD or PSHUFW.  That is, it doesn't reference
2445 /// the second operand.
2446 static bool isPSHUFDMask(const SmallVectorImpl<int> &Mask, EVT VT) {
2447   if (VT == MVT::v4f32 || VT == MVT::v4i32 || VT == MVT::v4i16)
2448     return (Mask[0] < 4 && Mask[1] < 4 && Mask[2] < 4 && Mask[3] < 4);
2449   if (VT == MVT::v2f64 || VT == MVT::v2i64)
2450     return (Mask[0] < 2 && Mask[1] < 2);
2451   return false;
2452 }
2453
2454 bool X86::isPSHUFDMask(ShuffleVectorSDNode *N) {
2455   SmallVector<int, 8> M;
2456   N->getMask(M);
2457   return ::isPSHUFDMask(M, N->getValueType(0));
2458 }
2459
2460 /// isPSHUFHWMask - Return true if the node specifies a shuffle of elements that
2461 /// is suitable for input to PSHUFHW.
2462 static bool isPSHUFHWMask(const SmallVectorImpl<int> &Mask, EVT VT) {
2463   if (VT != MVT::v8i16)
2464     return false;
2465
2466   // Lower quadword copied in order or undef.
2467   for (int i = 0; i != 4; ++i)
2468     if (Mask[i] >= 0 && Mask[i] != i)
2469       return false;
2470
2471   // Upper quadword shuffled.
2472   for (int i = 4; i != 8; ++i)
2473     if (Mask[i] >= 0 && (Mask[i] < 4 || Mask[i] > 7))
2474       return false;
2475
2476   return true;
2477 }
2478
2479 bool X86::isPSHUFHWMask(ShuffleVectorSDNode *N) {
2480   SmallVector<int, 8> M;
2481   N->getMask(M);
2482   return ::isPSHUFHWMask(M, N->getValueType(0));
2483 }
2484
2485 /// isPSHUFLWMask - Return true if the node specifies a shuffle of elements that
2486 /// is suitable for input to PSHUFLW.
2487 static bool isPSHUFLWMask(const SmallVectorImpl<int> &Mask, EVT VT) {
2488   if (VT != MVT::v8i16)
2489     return false;
2490
2491   // Upper quadword copied in order.
2492   for (int i = 4; i != 8; ++i)
2493     if (Mask[i] >= 0 && Mask[i] != i)
2494       return false;
2495
2496   // Lower quadword shuffled.
2497   for (int i = 0; i != 4; ++i)
2498     if (Mask[i] >= 4)
2499       return false;
2500
2501   return true;
2502 }
2503
2504 bool X86::isPSHUFLWMask(ShuffleVectorSDNode *N) {
2505   SmallVector<int, 8> M;
2506   N->getMask(M);
2507   return ::isPSHUFLWMask(M, N->getValueType(0));
2508 }
2509
2510 /// isPALIGNRMask - Return true if the node specifies a shuffle of elements that
2511 /// is suitable for input to PALIGNR.
2512 static bool isPALIGNRMask(const SmallVectorImpl<int> &Mask, EVT VT,
2513                           bool hasSSSE3) {
2514   int i, e = VT.getVectorNumElements();
2515   
2516   // Do not handle v2i64 / v2f64 shuffles with palignr.
2517   if (e < 4 || !hasSSSE3)
2518     return false;
2519   
2520   for (i = 0; i != e; ++i)
2521     if (Mask[i] >= 0)
2522       break;
2523   
2524   // All undef, not a palignr.
2525   if (i == e)
2526     return false;
2527
2528   // Determine if it's ok to perform a palignr with only the LHS, since we
2529   // don't have access to the actual shuffle elements to see if RHS is undef.
2530   bool Unary = Mask[i] < (int)e;
2531   bool NeedsUnary = false;
2532
2533   int s = Mask[i] - i;
2534   
2535   // Check the rest of the elements to see if they are consecutive.
2536   for (++i; i != e; ++i) {
2537     int m = Mask[i];
2538     if (m < 0) 
2539       continue;
2540     
2541     Unary = Unary && (m < (int)e);
2542     NeedsUnary = NeedsUnary || (m < s);
2543
2544     if (NeedsUnary && !Unary)
2545       return false;
2546     if (Unary && m != ((s+i) & (e-1)))
2547       return false;
2548     if (!Unary && m != (s+i))
2549       return false;
2550   }
2551   return true;
2552 }
2553
2554 bool X86::isPALIGNRMask(ShuffleVectorSDNode *N) {
2555   SmallVector<int, 8> M;
2556   N->getMask(M);
2557   return ::isPALIGNRMask(M, N->getValueType(0), true);
2558 }
2559
2560 /// isSHUFPMask - Return true if the specified VECTOR_SHUFFLE operand
2561 /// specifies a shuffle of elements that is suitable for input to SHUFP*.
2562 static bool isSHUFPMask(const SmallVectorImpl<int> &Mask, EVT VT) {
2563   int NumElems = VT.getVectorNumElements();
2564   if (NumElems != 2 && NumElems != 4)
2565     return false;
2566
2567   int Half = NumElems / 2;
2568   for (int i = 0; i < Half; ++i)
2569     if (!isUndefOrInRange(Mask[i], 0, NumElems))
2570       return false;
2571   for (int i = Half; i < NumElems; ++i)
2572     if (!isUndefOrInRange(Mask[i], NumElems, NumElems*2))
2573       return false;
2574
2575   return true;
2576 }
2577
2578 bool X86::isSHUFPMask(ShuffleVectorSDNode *N) {
2579   SmallVector<int, 8> M;
2580   N->getMask(M);
2581   return ::isSHUFPMask(M, N->getValueType(0));
2582 }
2583
2584 /// isCommutedSHUFP - Returns true if the shuffle mask is exactly
2585 /// the reverse of what x86 shuffles want. x86 shuffles requires the lower
2586 /// half elements to come from vector 1 (which would equal the dest.) and
2587 /// the upper half to come from vector 2.
2588 static bool isCommutedSHUFPMask(const SmallVectorImpl<int> &Mask, EVT VT) {
2589   int NumElems = VT.getVectorNumElements();
2590
2591   if (NumElems != 2 && NumElems != 4)
2592     return false;
2593
2594   int Half = NumElems / 2;
2595   for (int i = 0; i < Half; ++i)
2596     if (!isUndefOrInRange(Mask[i], NumElems, NumElems*2))
2597       return false;
2598   for (int i = Half; i < NumElems; ++i)
2599     if (!isUndefOrInRange(Mask[i], 0, NumElems))
2600       return false;
2601   return true;
2602 }
2603
2604 static bool isCommutedSHUFP(ShuffleVectorSDNode *N) {
2605   SmallVector<int, 8> M;
2606   N->getMask(M);
2607   return isCommutedSHUFPMask(M, N->getValueType(0));
2608 }
2609
2610 /// isMOVHLPSMask - Return true if the specified VECTOR_SHUFFLE operand
2611 /// specifies a shuffle of elements that is suitable for input to MOVHLPS.
2612 bool X86::isMOVHLPSMask(ShuffleVectorSDNode *N) {
2613   if (N->getValueType(0).getVectorNumElements() != 4)
2614     return false;
2615
2616   // Expect bit0 == 6, bit1 == 7, bit2 == 2, bit3 == 3
2617   return isUndefOrEqual(N->getMaskElt(0), 6) &&
2618          isUndefOrEqual(N->getMaskElt(1), 7) &&
2619          isUndefOrEqual(N->getMaskElt(2), 2) &&
2620          isUndefOrEqual(N->getMaskElt(3), 3);
2621 }
2622
2623 /// isMOVHLPS_v_undef_Mask - Special case of isMOVHLPSMask for canonical form
2624 /// of vector_shuffle v, v, <2, 3, 2, 3>, i.e. vector_shuffle v, undef,
2625 /// <2, 3, 2, 3>
2626 bool X86::isMOVHLPS_v_undef_Mask(ShuffleVectorSDNode *N) {
2627   unsigned NumElems = N->getValueType(0).getVectorNumElements();
2628   
2629   if (NumElems != 4)
2630     return false;
2631   
2632   return isUndefOrEqual(N->getMaskElt(0), 2) &&
2633   isUndefOrEqual(N->getMaskElt(1), 3) &&
2634   isUndefOrEqual(N->getMaskElt(2), 2) &&
2635   isUndefOrEqual(N->getMaskElt(3), 3);
2636 }
2637
2638 /// isMOVLPMask - Return true if the specified VECTOR_SHUFFLE operand
2639 /// specifies a shuffle of elements that is suitable for input to MOVLP{S|D}.
2640 bool X86::isMOVLPMask(ShuffleVectorSDNode *N) {
2641   unsigned NumElems = N->getValueType(0).getVectorNumElements();
2642
2643   if (NumElems != 2 && NumElems != 4)
2644     return false;
2645
2646   for (unsigned i = 0; i < NumElems/2; ++i)
2647     if (!isUndefOrEqual(N->getMaskElt(i), i + NumElems))
2648       return false;
2649
2650   for (unsigned i = NumElems/2; i < NumElems; ++i)
2651     if (!isUndefOrEqual(N->getMaskElt(i), i))
2652       return false;
2653
2654   return true;
2655 }
2656
2657 /// isMOVLHPSMask - Return true if the specified VECTOR_SHUFFLE operand
2658 /// specifies a shuffle of elements that is suitable for input to MOVLHPS.
2659 bool X86::isMOVLHPSMask(ShuffleVectorSDNode *N) {
2660   unsigned NumElems = N->getValueType(0).getVectorNumElements();
2661
2662   if (NumElems != 2 && NumElems != 4)
2663     return false;
2664
2665   for (unsigned i = 0; i < NumElems/2; ++i)
2666     if (!isUndefOrEqual(N->getMaskElt(i), i))
2667       return false;
2668
2669   for (unsigned i = 0; i < NumElems/2; ++i)
2670     if (!isUndefOrEqual(N->getMaskElt(i + NumElems/2), i + NumElems))
2671       return false;
2672
2673   return true;
2674 }
2675
2676 /// isUNPCKLMask - Return true if the specified VECTOR_SHUFFLE operand
2677 /// specifies a shuffle of elements that is suitable for input to UNPCKL.
2678 static bool isUNPCKLMask(const SmallVectorImpl<int> &Mask, EVT VT,
2679                          bool V2IsSplat = false) {
2680   int NumElts = VT.getVectorNumElements();
2681   if (NumElts != 2 && NumElts != 4 && NumElts != 8 && NumElts != 16)
2682     return false;
2683
2684   for (int i = 0, j = 0; i != NumElts; i += 2, ++j) {
2685     int BitI  = Mask[i];
2686     int BitI1 = Mask[i+1];
2687     if (!isUndefOrEqual(BitI, j))
2688       return false;
2689     if (V2IsSplat) {
2690       if (!isUndefOrEqual(BitI1, NumElts))
2691         return false;
2692     } else {
2693       if (!isUndefOrEqual(BitI1, j + NumElts))
2694         return false;
2695     }
2696   }
2697   return true;
2698 }
2699
2700 bool X86::isUNPCKLMask(ShuffleVectorSDNode *N, bool V2IsSplat) {
2701   SmallVector<int, 8> M;
2702   N->getMask(M);
2703   return ::isUNPCKLMask(M, N->getValueType(0), V2IsSplat);
2704 }
2705
2706 /// isUNPCKHMask - Return true if the specified VECTOR_SHUFFLE operand
2707 /// specifies a shuffle of elements that is suitable for input to UNPCKH.
2708 static bool isUNPCKHMask(const SmallVectorImpl<int> &Mask, EVT VT,
2709                          bool V2IsSplat = false) {
2710   int NumElts = VT.getVectorNumElements();
2711   if (NumElts != 2 && NumElts != 4 && NumElts != 8 && NumElts != 16)
2712     return false;
2713
2714   for (int i = 0, j = 0; i != NumElts; i += 2, ++j) {
2715     int BitI  = Mask[i];
2716     int BitI1 = Mask[i+1];
2717     if (!isUndefOrEqual(BitI, j + NumElts/2))
2718       return false;
2719     if (V2IsSplat) {
2720       if (isUndefOrEqual(BitI1, NumElts))
2721         return false;
2722     } else {
2723       if (!isUndefOrEqual(BitI1, j + NumElts/2 + NumElts))
2724         return false;
2725     }
2726   }
2727   return true;
2728 }
2729
2730 bool X86::isUNPCKHMask(ShuffleVectorSDNode *N, bool V2IsSplat) {
2731   SmallVector<int, 8> M;
2732   N->getMask(M);
2733   return ::isUNPCKHMask(M, N->getValueType(0), V2IsSplat);
2734 }
2735
2736 /// isUNPCKL_v_undef_Mask - Special case of isUNPCKLMask for canonical form
2737 /// of vector_shuffle v, v, <0, 4, 1, 5>, i.e. vector_shuffle v, undef,
2738 /// <0, 0, 1, 1>
2739 static bool isUNPCKL_v_undef_Mask(const SmallVectorImpl<int> &Mask, EVT VT) {
2740   int NumElems = VT.getVectorNumElements();
2741   if (NumElems != 2 && NumElems != 4 && NumElems != 8 && NumElems != 16)
2742     return false;
2743
2744   for (int i = 0, j = 0; i != NumElems; i += 2, ++j) {
2745     int BitI  = Mask[i];
2746     int BitI1 = Mask[i+1];
2747     if (!isUndefOrEqual(BitI, j))
2748       return false;
2749     if (!isUndefOrEqual(BitI1, j))
2750       return false;
2751   }
2752   return true;
2753 }
2754
2755 bool X86::isUNPCKL_v_undef_Mask(ShuffleVectorSDNode *N) {
2756   SmallVector<int, 8> M;
2757   N->getMask(M);
2758   return ::isUNPCKL_v_undef_Mask(M, N->getValueType(0));
2759 }
2760
2761 /// isUNPCKH_v_undef_Mask - Special case of isUNPCKHMask for canonical form
2762 /// of vector_shuffle v, v, <2, 6, 3, 7>, i.e. vector_shuffle v, undef,
2763 /// <2, 2, 3, 3>
2764 static bool isUNPCKH_v_undef_Mask(const SmallVectorImpl<int> &Mask, EVT VT) {
2765   int NumElems = VT.getVectorNumElements();
2766   if (NumElems != 2 && NumElems != 4 && NumElems != 8 && NumElems != 16)
2767     return false;
2768
2769   for (int i = 0, j = NumElems / 2; i != NumElems; i += 2, ++j) {
2770     int BitI  = Mask[i];
2771     int BitI1 = Mask[i+1];
2772     if (!isUndefOrEqual(BitI, j))
2773       return false;
2774     if (!isUndefOrEqual(BitI1, j))
2775       return false;
2776   }
2777   return true;
2778 }
2779
2780 bool X86::isUNPCKH_v_undef_Mask(ShuffleVectorSDNode *N) {
2781   SmallVector<int, 8> M;
2782   N->getMask(M);
2783   return ::isUNPCKH_v_undef_Mask(M, N->getValueType(0));
2784 }
2785
2786 /// isMOVLMask - Return true if the specified VECTOR_SHUFFLE operand
2787 /// specifies a shuffle of elements that is suitable for input to MOVSS,
2788 /// MOVSD, and MOVD, i.e. setting the lowest element.
2789 static bool isMOVLMask(const SmallVectorImpl<int> &Mask, EVT VT) {
2790   if (VT.getVectorElementType().getSizeInBits() < 32)
2791     return false;
2792
2793   int NumElts = VT.getVectorNumElements();
2794
2795   if (!isUndefOrEqual(Mask[0], NumElts))
2796     return false;
2797
2798   for (int i = 1; i < NumElts; ++i)
2799     if (!isUndefOrEqual(Mask[i], i))
2800       return false;
2801
2802   return true;
2803 }
2804
2805 bool X86::isMOVLMask(ShuffleVectorSDNode *N) {
2806   SmallVector<int, 8> M;
2807   N->getMask(M);
2808   return ::isMOVLMask(M, N->getValueType(0));
2809 }
2810
2811 /// isCommutedMOVL - Returns true if the shuffle mask is except the reverse
2812 /// of what x86 movss want. X86 movs requires the lowest  element to be lowest
2813 /// element of vector 2 and the other elements to come from vector 1 in order.
2814 static bool isCommutedMOVLMask(const SmallVectorImpl<int> &Mask, EVT VT,
2815                                bool V2IsSplat = false, bool V2IsUndef = false) {
2816   int NumOps = VT.getVectorNumElements();
2817   if (NumOps != 2 && NumOps != 4 && NumOps != 8 && NumOps != 16)
2818     return false;
2819
2820   if (!isUndefOrEqual(Mask[0], 0))
2821     return false;
2822
2823   for (int i = 1; i < NumOps; ++i)
2824     if (!(isUndefOrEqual(Mask[i], i+NumOps) ||
2825           (V2IsUndef && isUndefOrInRange(Mask[i], NumOps, NumOps*2)) ||
2826           (V2IsSplat && isUndefOrEqual(Mask[i], NumOps))))
2827       return false;
2828
2829   return true;
2830 }
2831
2832 static bool isCommutedMOVL(ShuffleVectorSDNode *N, bool V2IsSplat = false,
2833                            bool V2IsUndef = false) {
2834   SmallVector<int, 8> M;
2835   N->getMask(M);
2836   return isCommutedMOVLMask(M, N->getValueType(0), V2IsSplat, V2IsUndef);
2837 }
2838
2839 /// isMOVSHDUPMask - Return true if the specified VECTOR_SHUFFLE operand
2840 /// specifies a shuffle of elements that is suitable for input to MOVSHDUP.
2841 bool X86::isMOVSHDUPMask(ShuffleVectorSDNode *N) {
2842   if (N->getValueType(0).getVectorNumElements() != 4)
2843     return false;
2844
2845   // Expect 1, 1, 3, 3
2846   for (unsigned i = 0; i < 2; ++i) {
2847     int Elt = N->getMaskElt(i);
2848     if (Elt >= 0 && Elt != 1)
2849       return false;
2850   }
2851
2852   bool HasHi = false;
2853   for (unsigned i = 2; i < 4; ++i) {
2854     int Elt = N->getMaskElt(i);
2855     if (Elt >= 0 && Elt != 3)
2856       return false;
2857     if (Elt == 3)
2858       HasHi = true;
2859   }
2860   // Don't use movshdup if it can be done with a shufps.
2861   // FIXME: verify that matching u, u, 3, 3 is what we want.
2862   return HasHi;
2863 }
2864
2865 /// isMOVSLDUPMask - Return true if the specified VECTOR_SHUFFLE operand
2866 /// specifies a shuffle of elements that is suitable for input to MOVSLDUP.
2867 bool X86::isMOVSLDUPMask(ShuffleVectorSDNode *N) {
2868   if (N->getValueType(0).getVectorNumElements() != 4)
2869     return false;
2870
2871   // Expect 0, 0, 2, 2
2872   for (unsigned i = 0; i < 2; ++i)
2873     if (N->getMaskElt(i) > 0)
2874       return false;
2875
2876   bool HasHi = false;
2877   for (unsigned i = 2; i < 4; ++i) {
2878     int Elt = N->getMaskElt(i);
2879     if (Elt >= 0 && Elt != 2)
2880       return false;
2881     if (Elt == 2)
2882       HasHi = true;
2883   }
2884   // Don't use movsldup if it can be done with a shufps.
2885   return HasHi;
2886 }
2887
2888 /// isMOVDDUPMask - Return true if the specified VECTOR_SHUFFLE operand
2889 /// specifies a shuffle of elements that is suitable for input to MOVDDUP.
2890 bool X86::isMOVDDUPMask(ShuffleVectorSDNode *N) {
2891   int e = N->getValueType(0).getVectorNumElements() / 2;
2892
2893   for (int i = 0; i < e; ++i)
2894     if (!isUndefOrEqual(N->getMaskElt(i), i))
2895       return false;
2896   for (int i = 0; i < e; ++i)
2897     if (!isUndefOrEqual(N->getMaskElt(e+i), i))
2898       return false;
2899   return true;
2900 }
2901
2902 /// getShuffleSHUFImmediate - Return the appropriate immediate to shuffle
2903 /// the specified VECTOR_SHUFFLE mask with PSHUF* and SHUFP* instructions.
2904 unsigned X86::getShuffleSHUFImmediate(SDNode *N) {
2905   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
2906   int NumOperands = SVOp->getValueType(0).getVectorNumElements();
2907
2908   unsigned Shift = (NumOperands == 4) ? 2 : 1;
2909   unsigned Mask = 0;
2910   for (int i = 0; i < NumOperands; ++i) {
2911     int Val = SVOp->getMaskElt(NumOperands-i-1);
2912     if (Val < 0) Val = 0;
2913     if (Val >= NumOperands) Val -= NumOperands;
2914     Mask |= Val;
2915     if (i != NumOperands - 1)
2916       Mask <<= Shift;
2917   }
2918   return Mask;
2919 }
2920
2921 /// getShufflePSHUFHWImmediate - Return the appropriate immediate to shuffle
2922 /// the specified VECTOR_SHUFFLE mask with the PSHUFHW instruction.
2923 unsigned X86::getShufflePSHUFHWImmediate(SDNode *N) {
2924   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
2925   unsigned Mask = 0;
2926   // 8 nodes, but we only care about the last 4.
2927   for (unsigned i = 7; i >= 4; --i) {
2928     int Val = SVOp->getMaskElt(i);
2929     if (Val >= 0)
2930       Mask |= (Val - 4);
2931     if (i != 4)
2932       Mask <<= 2;
2933   }
2934   return Mask;
2935 }
2936
2937 /// getShufflePSHUFLWImmediate - Return the appropriate immediate to shuffle
2938 /// the specified VECTOR_SHUFFLE mask with the PSHUFLW instruction.
2939 unsigned X86::getShufflePSHUFLWImmediate(SDNode *N) {
2940   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
2941   unsigned Mask = 0;
2942   // 8 nodes, but we only care about the first 4.
2943   for (int i = 3; i >= 0; --i) {
2944     int Val = SVOp->getMaskElt(i);
2945     if (Val >= 0)
2946       Mask |= Val;
2947     if (i != 0)
2948       Mask <<= 2;
2949   }
2950   return Mask;
2951 }
2952
2953 /// getShufflePALIGNRImmediate - Return the appropriate immediate to shuffle
2954 /// the specified VECTOR_SHUFFLE mask with the PALIGNR instruction.
2955 unsigned X86::getShufflePALIGNRImmediate(SDNode *N) {
2956   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
2957   EVT VVT = N->getValueType(0);
2958   unsigned EltSize = VVT.getVectorElementType().getSizeInBits() >> 3;
2959   int Val = 0;
2960
2961   unsigned i, e;
2962   for (i = 0, e = VVT.getVectorNumElements(); i != e; ++i) {
2963     Val = SVOp->getMaskElt(i);
2964     if (Val >= 0)
2965       break;
2966   }
2967   return (Val - i) * EltSize;
2968 }
2969
2970 /// isZeroNode - Returns true if Elt is a constant zero or a floating point
2971 /// constant +0.0.
2972 bool X86::isZeroNode(SDValue Elt) {
2973   return ((isa<ConstantSDNode>(Elt) &&
2974            cast<ConstantSDNode>(Elt)->getZExtValue() == 0) ||
2975           (isa<ConstantFPSDNode>(Elt) &&
2976            cast<ConstantFPSDNode>(Elt)->getValueAPF().isPosZero()));
2977 }
2978
2979 /// CommuteVectorShuffle - Swap vector_shuffle operands as well as values in
2980 /// their permute mask.
2981 static SDValue CommuteVectorShuffle(ShuffleVectorSDNode *SVOp,
2982                                     SelectionDAG &DAG) {
2983   EVT VT = SVOp->getValueType(0);
2984   unsigned NumElems = VT.getVectorNumElements();
2985   SmallVector<int, 8> MaskVec;
2986
2987   for (unsigned i = 0; i != NumElems; ++i) {
2988     int idx = SVOp->getMaskElt(i);
2989     if (idx < 0)
2990       MaskVec.push_back(idx);
2991     else if (idx < (int)NumElems)
2992       MaskVec.push_back(idx + NumElems);
2993     else
2994       MaskVec.push_back(idx - NumElems);
2995   }
2996   return DAG.getVectorShuffle(VT, SVOp->getDebugLoc(), SVOp->getOperand(1),
2997                               SVOp->getOperand(0), &MaskVec[0]);
2998 }
2999
3000 /// CommuteVectorShuffleMask - Change values in a shuffle permute mask assuming
3001 /// the two vector operands have swapped position.
3002 static void CommuteVectorShuffleMask(SmallVectorImpl<int> &Mask, EVT VT) {
3003   unsigned NumElems = VT.getVectorNumElements();
3004   for (unsigned i = 0; i != NumElems; ++i) {
3005     int idx = Mask[i];
3006     if (idx < 0)
3007       continue;
3008     else if (idx < (int)NumElems)
3009       Mask[i] = idx + NumElems;
3010     else
3011       Mask[i] = idx - NumElems;
3012   }
3013 }
3014
3015 /// ShouldXformToMOVHLPS - Return true if the node should be transformed to
3016 /// match movhlps. The lower half elements should come from upper half of
3017 /// V1 (and in order), and the upper half elements should come from the upper
3018 /// half of V2 (and in order).
3019 static bool ShouldXformToMOVHLPS(ShuffleVectorSDNode *Op) {
3020   if (Op->getValueType(0).getVectorNumElements() != 4)
3021     return false;
3022   for (unsigned i = 0, e = 2; i != e; ++i)
3023     if (!isUndefOrEqual(Op->getMaskElt(i), i+2))
3024       return false;
3025   for (unsigned i = 2; i != 4; ++i)
3026     if (!isUndefOrEqual(Op->getMaskElt(i), i+4))
3027       return false;
3028   return true;
3029 }
3030
3031 /// isScalarLoadToVector - Returns true if the node is a scalar load that
3032 /// is promoted to a vector. It also returns the LoadSDNode by reference if
3033 /// required.
3034 static bool isScalarLoadToVector(SDNode *N, LoadSDNode **LD = NULL) {
3035   if (N->getOpcode() != ISD::SCALAR_TO_VECTOR)
3036     return false;
3037   N = N->getOperand(0).getNode();
3038   if (!ISD::isNON_EXTLoad(N))
3039     return false;
3040   if (LD)
3041     *LD = cast<LoadSDNode>(N);
3042   return true;
3043 }
3044
3045 /// ShouldXformToMOVLP{S|D} - Return true if the node should be transformed to
3046 /// match movlp{s|d}. The lower half elements should come from lower half of
3047 /// V1 (and in order), and the upper half elements should come from the upper
3048 /// half of V2 (and in order). And since V1 will become the source of the
3049 /// MOVLP, it must be either a vector load or a scalar load to vector.
3050 static bool ShouldXformToMOVLP(SDNode *V1, SDNode *V2,
3051                                ShuffleVectorSDNode *Op) {
3052   if (!ISD::isNON_EXTLoad(V1) && !isScalarLoadToVector(V1))
3053     return false;
3054   // Is V2 is a vector load, don't do this transformation. We will try to use
3055   // load folding shufps op.
3056   if (ISD::isNON_EXTLoad(V2))
3057     return false;
3058
3059   unsigned NumElems = Op->getValueType(0).getVectorNumElements();
3060
3061   if (NumElems != 2 && NumElems != 4)
3062     return false;
3063   for (unsigned i = 0, e = NumElems/2; i != e; ++i)
3064     if (!isUndefOrEqual(Op->getMaskElt(i), i))
3065       return false;
3066   for (unsigned i = NumElems/2; i != NumElems; ++i)
3067     if (!isUndefOrEqual(Op->getMaskElt(i), i+NumElems))
3068       return false;
3069   return true;
3070 }
3071
3072 /// isSplatVector - Returns true if N is a BUILD_VECTOR node whose elements are
3073 /// all the same.
3074 static bool isSplatVector(SDNode *N) {
3075   if (N->getOpcode() != ISD::BUILD_VECTOR)
3076     return false;
3077
3078   SDValue SplatValue = N->getOperand(0);
3079   for (unsigned i = 1, e = N->getNumOperands(); i != e; ++i)
3080     if (N->getOperand(i) != SplatValue)
3081       return false;
3082   return true;
3083 }
3084
3085 /// isZeroShuffle - Returns true if N is a VECTOR_SHUFFLE that can be resolved
3086 /// to an zero vector.
3087 /// FIXME: move to dag combiner / method on ShuffleVectorSDNode
3088 static bool isZeroShuffle(ShuffleVectorSDNode *N) {
3089   SDValue V1 = N->getOperand(0);
3090   SDValue V2 = N->getOperand(1);
3091   unsigned NumElems = N->getValueType(0).getVectorNumElements();
3092   for (unsigned i = 0; i != NumElems; ++i) {
3093     int Idx = N->getMaskElt(i);
3094     if (Idx >= (int)NumElems) {
3095       unsigned Opc = V2.getOpcode();
3096       if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V2.getNode()))
3097         continue;
3098       if (Opc != ISD::BUILD_VECTOR ||
3099           !X86::isZeroNode(V2.getOperand(Idx-NumElems)))
3100         return false;
3101     } else if (Idx >= 0) {
3102       unsigned Opc = V1.getOpcode();
3103       if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V1.getNode()))
3104         continue;
3105       if (Opc != ISD::BUILD_VECTOR ||
3106           !X86::isZeroNode(V1.getOperand(Idx)))
3107         return false;
3108     }
3109   }
3110   return true;
3111 }
3112
3113 /// getZeroVector - Returns a vector of specified type with all zero elements.
3114 ///
3115 static SDValue getZeroVector(EVT VT, bool HasSSE2, SelectionDAG &DAG,
3116                              DebugLoc dl) {
3117   assert(VT.isVector() && "Expected a vector type");
3118
3119   // Always build zero vectors as <4 x i32> or <2 x i32> bitcasted to their dest
3120   // type.  This ensures they get CSE'd.
3121   SDValue Vec;
3122   if (VT.getSizeInBits() == 64) { // MMX
3123     SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
3124     Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v2i32, Cst, Cst);
3125   } else if (HasSSE2) {  // SSE2
3126     SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
3127     Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
3128   } else { // SSE1
3129     SDValue Cst = DAG.getTargetConstantFP(+0.0, MVT::f32);
3130     Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4f32, Cst, Cst, Cst, Cst);
3131   }
3132   return DAG.getNode(ISD::BIT_CONVERT, dl, VT, Vec);
3133 }
3134
3135 /// getOnesVector - Returns a vector of specified type with all bits set.
3136 ///
3137 static SDValue getOnesVector(EVT VT, SelectionDAG &DAG, DebugLoc dl) {
3138   assert(VT.isVector() && "Expected a vector type");
3139
3140   // Always build ones vectors as <4 x i32> or <2 x i32> bitcasted to their dest
3141   // type.  This ensures they get CSE'd.
3142   SDValue Cst = DAG.getTargetConstant(~0U, MVT::i32);
3143   SDValue Vec;
3144   if (VT.getSizeInBits() == 64)  // MMX
3145     Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v2i32, Cst, Cst);
3146   else                                              // SSE
3147     Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
3148   return DAG.getNode(ISD::BIT_CONVERT, dl, VT, Vec);
3149 }
3150
3151
3152 /// NormalizeMask - V2 is a splat, modify the mask (if needed) so all elements
3153 /// that point to V2 points to its first element.
3154 static SDValue NormalizeMask(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
3155   EVT VT = SVOp->getValueType(0);
3156   unsigned NumElems = VT.getVectorNumElements();
3157
3158   bool Changed = false;
3159   SmallVector<int, 8> MaskVec;
3160   SVOp->getMask(MaskVec);
3161
3162   for (unsigned i = 0; i != NumElems; ++i) {
3163     if (MaskVec[i] > (int)NumElems) {
3164       MaskVec[i] = NumElems;
3165       Changed = true;
3166     }
3167   }
3168   if (Changed)
3169     return DAG.getVectorShuffle(VT, SVOp->getDebugLoc(), SVOp->getOperand(0),
3170                                 SVOp->getOperand(1), &MaskVec[0]);
3171   return SDValue(SVOp, 0);
3172 }
3173
3174 /// getMOVLMask - Returns a vector_shuffle mask for an movs{s|d}, movd
3175 /// operation of specified width.
3176 static SDValue getMOVL(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
3177                        SDValue V2) {
3178   unsigned NumElems = VT.getVectorNumElements();
3179   SmallVector<int, 8> Mask;
3180   Mask.push_back(NumElems);
3181   for (unsigned i = 1; i != NumElems; ++i)
3182     Mask.push_back(i);
3183   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
3184 }
3185
3186 /// getUnpackl - Returns a vector_shuffle node for an unpackl operation.
3187 static SDValue getUnpackl(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
3188                           SDValue V2) {
3189   unsigned NumElems = VT.getVectorNumElements();
3190   SmallVector<int, 8> Mask;
3191   for (unsigned i = 0, e = NumElems/2; i != e; ++i) {
3192     Mask.push_back(i);
3193     Mask.push_back(i + NumElems);
3194   }
3195   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
3196 }
3197
3198 /// getUnpackhMask - Returns a vector_shuffle node for an unpackh operation.
3199 static SDValue getUnpackh(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
3200                           SDValue V2) {
3201   unsigned NumElems = VT.getVectorNumElements();
3202   unsigned Half = NumElems/2;
3203   SmallVector<int, 8> Mask;
3204   for (unsigned i = 0; i != Half; ++i) {
3205     Mask.push_back(i + Half);
3206     Mask.push_back(i + NumElems + Half);
3207   }
3208   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
3209 }
3210
3211 /// PromoteSplat - Promote a splat of v4f32, v8i16 or v16i8 to v4i32.
3212 static SDValue PromoteSplat(ShuffleVectorSDNode *SV, SelectionDAG &DAG,
3213                             bool HasSSE2) {
3214   if (SV->getValueType(0).getVectorNumElements() <= 4)
3215     return SDValue(SV, 0);
3216
3217   EVT PVT = MVT::v4f32;
3218   EVT VT = SV->getValueType(0);
3219   DebugLoc dl = SV->getDebugLoc();
3220   SDValue V1 = SV->getOperand(0);
3221   int NumElems = VT.getVectorNumElements();
3222   int EltNo = SV->getSplatIndex();
3223
3224   // unpack elements to the correct location
3225   while (NumElems > 4) {
3226     if (EltNo < NumElems/2) {
3227       V1 = getUnpackl(DAG, dl, VT, V1, V1);
3228     } else {
3229       V1 = getUnpackh(DAG, dl, VT, V1, V1);
3230       EltNo -= NumElems/2;
3231     }
3232     NumElems >>= 1;
3233   }
3234
3235   // Perform the splat.
3236   int SplatMask[4] = { EltNo, EltNo, EltNo, EltNo };
3237   V1 = DAG.getNode(ISD::BIT_CONVERT, dl, PVT, V1);
3238   V1 = DAG.getVectorShuffle(PVT, dl, V1, DAG.getUNDEF(PVT), &SplatMask[0]);
3239   return DAG.getNode(ISD::BIT_CONVERT, dl, VT, V1);
3240 }
3241
3242 /// getShuffleVectorZeroOrUndef - Return a vector_shuffle of the specified
3243 /// vector of zero or undef vector.  This produces a shuffle where the low
3244 /// element of V2 is swizzled into the zero/undef vector, landing at element
3245 /// Idx.  This produces a shuffle mask like 4,1,2,3 (idx=0) or  0,1,2,4 (idx=3).
3246 static SDValue getShuffleVectorZeroOrUndef(SDValue V2, unsigned Idx,
3247                                              bool isZero, bool HasSSE2,
3248                                              SelectionDAG &DAG) {
3249   EVT VT = V2.getValueType();
3250   SDValue V1 = isZero
3251     ? getZeroVector(VT, HasSSE2, DAG, V2.getDebugLoc()) : DAG.getUNDEF(VT);
3252   unsigned NumElems = VT.getVectorNumElements();
3253   SmallVector<int, 16> MaskVec;
3254   for (unsigned i = 0; i != NumElems; ++i)
3255     // If this is the insertion idx, put the low elt of V2 here.
3256     MaskVec.push_back(i == Idx ? NumElems : i);
3257   return DAG.getVectorShuffle(VT, V2.getDebugLoc(), V1, V2, &MaskVec[0]);
3258 }
3259
3260 /// getNumOfConsecutiveZeros - Return the number of elements in a result of
3261 /// a shuffle that is zero.
3262 static
3263 unsigned getNumOfConsecutiveZeros(ShuffleVectorSDNode *SVOp, int NumElems,
3264                                   bool Low, SelectionDAG &DAG) {
3265   unsigned NumZeros = 0;
3266   for (int i = 0; i < NumElems; ++i) {
3267     unsigned Index = Low ? i : NumElems-i-1;
3268     int Idx = SVOp->getMaskElt(Index);
3269     if (Idx < 0) {
3270       ++NumZeros;
3271       continue;
3272     }
3273     SDValue Elt = DAG.getShuffleScalarElt(SVOp, Index);
3274     if (Elt.getNode() && X86::isZeroNode(Elt))
3275       ++NumZeros;
3276     else
3277       break;
3278   }
3279   return NumZeros;
3280 }
3281
3282 /// isVectorShift - Returns true if the shuffle can be implemented as a
3283 /// logical left or right shift of a vector.
3284 /// FIXME: split into pslldqi, psrldqi, palignr variants.
3285 static bool isVectorShift(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
3286                           bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
3287   int NumElems = SVOp->getValueType(0).getVectorNumElements();
3288
3289   isLeft = true;
3290   unsigned NumZeros = getNumOfConsecutiveZeros(SVOp, NumElems, true, DAG);
3291   if (!NumZeros) {
3292     isLeft = false;
3293     NumZeros = getNumOfConsecutiveZeros(SVOp, NumElems, false, DAG);
3294     if (!NumZeros)
3295       return false;
3296   }
3297   bool SeenV1 = false;
3298   bool SeenV2 = false;
3299   for (int i = NumZeros; i < NumElems; ++i) {
3300     int Val = isLeft ? (i - NumZeros) : i;
3301     int Idx = SVOp->getMaskElt(isLeft ? i : (i - NumZeros));
3302     if (Idx < 0)
3303       continue;
3304     if (Idx < NumElems)
3305       SeenV1 = true;
3306     else {
3307       Idx -= NumElems;
3308       SeenV2 = true;
3309     }
3310     if (Idx != Val)
3311       return false;
3312   }
3313   if (SeenV1 && SeenV2)
3314     return false;
3315
3316   ShVal = SeenV1 ? SVOp->getOperand(0) : SVOp->getOperand(1);
3317   ShAmt = NumZeros;
3318   return true;
3319 }
3320
3321
3322 /// LowerBuildVectorv16i8 - Custom lower build_vector of v16i8.
3323 ///
3324 static SDValue LowerBuildVectorv16i8(SDValue Op, unsigned NonZeros,
3325                                        unsigned NumNonZero, unsigned NumZero,
3326                                        SelectionDAG &DAG, TargetLowering &TLI) {
3327   if (NumNonZero > 8)
3328     return SDValue();
3329
3330   DebugLoc dl = Op.getDebugLoc();
3331   SDValue V(0, 0);
3332   bool First = true;
3333   for (unsigned i = 0; i < 16; ++i) {
3334     bool ThisIsNonZero = (NonZeros & (1 << i)) != 0;
3335     if (ThisIsNonZero && First) {
3336       if (NumZero)
3337         V = getZeroVector(MVT::v8i16, true, DAG, dl);
3338       else
3339         V = DAG.getUNDEF(MVT::v8i16);
3340       First = false;
3341     }
3342
3343     if ((i & 1) != 0) {
3344       SDValue ThisElt(0, 0), LastElt(0, 0);
3345       bool LastIsNonZero = (NonZeros & (1 << (i-1))) != 0;
3346       if (LastIsNonZero) {
3347         LastElt = DAG.getNode(ISD::ZERO_EXTEND, dl,
3348                               MVT::i16, Op.getOperand(i-1));
3349       }
3350       if (ThisIsNonZero) {
3351         ThisElt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i16, Op.getOperand(i));
3352         ThisElt = DAG.getNode(ISD::SHL, dl, MVT::i16,
3353                               ThisElt, DAG.getConstant(8, MVT::i8));
3354         if (LastIsNonZero)
3355           ThisElt = DAG.getNode(ISD::OR, dl, MVT::i16, ThisElt, LastElt);
3356       } else
3357         ThisElt = LastElt;
3358
3359       if (ThisElt.getNode())
3360         V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, V, ThisElt,
3361                         DAG.getIntPtrConstant(i/2));
3362     }
3363   }
3364
3365   return DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v16i8, V);
3366 }
3367
3368 /// LowerBuildVectorv8i16 - Custom lower build_vector of v8i16.
3369 ///
3370 static SDValue LowerBuildVectorv8i16(SDValue Op, unsigned NonZeros,
3371                                        unsigned NumNonZero, unsigned NumZero,
3372                                        SelectionDAG &DAG, TargetLowering &TLI) {
3373   if (NumNonZero > 4)
3374     return SDValue();
3375
3376   DebugLoc dl = Op.getDebugLoc();
3377   SDValue V(0, 0);
3378   bool First = true;
3379   for (unsigned i = 0; i < 8; ++i) {
3380     bool isNonZero = (NonZeros & (1 << i)) != 0;
3381     if (isNonZero) {
3382       if (First) {
3383         if (NumZero)
3384           V = getZeroVector(MVT::v8i16, true, DAG, dl);
3385         else
3386           V = DAG.getUNDEF(MVT::v8i16);
3387         First = false;
3388       }
3389       V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl,
3390                       MVT::v8i16, V, Op.getOperand(i),
3391                       DAG.getIntPtrConstant(i));
3392     }
3393   }
3394
3395   return V;
3396 }
3397
3398 /// getVShift - Return a vector logical shift node.
3399 ///
3400 static SDValue getVShift(bool isLeft, EVT VT, SDValue SrcOp,
3401                          unsigned NumBits, SelectionDAG &DAG,
3402                          const TargetLowering &TLI, DebugLoc dl) {
3403   bool isMMX = VT.getSizeInBits() == 64;
3404   EVT ShVT = isMMX ? MVT::v1i64 : MVT::v2i64;
3405   unsigned Opc = isLeft ? X86ISD::VSHL : X86ISD::VSRL;
3406   SrcOp = DAG.getNode(ISD::BIT_CONVERT, dl, ShVT, SrcOp);
3407   return DAG.getNode(ISD::BIT_CONVERT, dl, VT,
3408                      DAG.getNode(Opc, dl, ShVT, SrcOp,
3409                              DAG.getConstant(NumBits, TLI.getShiftAmountTy())));
3410 }
3411
3412 SDValue
3413 X86TargetLowering::LowerAsSplatVectorLoad(SDValue SrcOp, EVT VT, DebugLoc dl,
3414                                           SelectionDAG &DAG) {
3415   
3416   // Check if the scalar load can be widened into a vector load. And if
3417   // the address is "base + cst" see if the cst can be "absorbed" into
3418   // the shuffle mask.
3419   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(SrcOp)) {
3420     SDValue Ptr = LD->getBasePtr();
3421     if (!ISD::isNormalLoad(LD) || LD->isVolatile())
3422       return SDValue();
3423     EVT PVT = LD->getValueType(0);
3424     if (PVT != MVT::i32 && PVT != MVT::f32)
3425       return SDValue();
3426
3427     int FI = -1;
3428     int64_t Offset = 0;
3429     if (FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr)) {
3430       FI = FINode->getIndex();
3431       Offset = 0;
3432     } else if (Ptr.getOpcode() == ISD::ADD &&
3433                isa<ConstantSDNode>(Ptr.getOperand(1)) &&
3434                isa<FrameIndexSDNode>(Ptr.getOperand(0))) {
3435       FI = cast<FrameIndexSDNode>(Ptr.getOperand(0))->getIndex();
3436       Offset = Ptr.getConstantOperandVal(1);
3437       Ptr = Ptr.getOperand(0);
3438     } else {
3439       return SDValue();
3440     }
3441
3442     SDValue Chain = LD->getChain();
3443     // Make sure the stack object alignment is at least 16.
3444     MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
3445     if (DAG.InferPtrAlignment(Ptr) < 16) {
3446       if (MFI->isFixedObjectIndex(FI)) {
3447         // Can't change the alignment. FIXME: It's possible to compute
3448         // the exact stack offset and reference FI + adjust offset instead.
3449         // If someone *really* cares about this. That's the way to implement it.
3450         return SDValue();
3451       } else {
3452         MFI->setObjectAlignment(FI, 16);
3453       }
3454     }
3455
3456     // (Offset % 16) must be multiple of 4. Then address is then
3457     // Ptr + (Offset & ~15).
3458     if (Offset < 0)
3459       return SDValue();
3460     if ((Offset % 16) & 3)
3461       return SDValue();
3462     int64_t StartOffset = Offset & ~15;
3463     if (StartOffset)
3464       Ptr = DAG.getNode(ISD::ADD, Ptr.getDebugLoc(), Ptr.getValueType(),
3465                         Ptr,DAG.getConstant(StartOffset, Ptr.getValueType()));
3466
3467     int EltNo = (Offset - StartOffset) >> 2;
3468     int Mask[4] = { EltNo, EltNo, EltNo, EltNo };
3469     EVT VT = (PVT == MVT::i32) ? MVT::v4i32 : MVT::v4f32;
3470     SDValue V1 = DAG.getLoad(VT, dl, Chain, Ptr,LD->getSrcValue(),0);
3471     // Canonicalize it to a v4i32 shuffle.
3472     V1 = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v4i32, V1);
3473     return DAG.getNode(ISD::BIT_CONVERT, dl, VT,
3474                        DAG.getVectorShuffle(MVT::v4i32, dl, V1,
3475                                             DAG.getUNDEF(MVT::v4i32), &Mask[0]));
3476   }
3477
3478   return SDValue();
3479 }
3480
3481 SDValue
3482 X86TargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG) {
3483   DebugLoc dl = Op.getDebugLoc();
3484   // All zero's are handled with pxor, all one's are handled with pcmpeqd.
3485   if (ISD::isBuildVectorAllZeros(Op.getNode())
3486       || ISD::isBuildVectorAllOnes(Op.getNode())) {
3487     // Canonicalize this to either <4 x i32> or <2 x i32> (SSE vs MMX) to
3488     // 1) ensure the zero vectors are CSE'd, and 2) ensure that i64 scalars are
3489     // eliminated on x86-32 hosts.
3490     if (Op.getValueType() == MVT::v4i32 || Op.getValueType() == MVT::v2i32)
3491       return Op;
3492
3493     if (ISD::isBuildVectorAllOnes(Op.getNode()))
3494       return getOnesVector(Op.getValueType(), DAG, dl);
3495     return getZeroVector(Op.getValueType(), Subtarget->hasSSE2(), DAG, dl);
3496   }
3497
3498   EVT VT = Op.getValueType();
3499   EVT ExtVT = VT.getVectorElementType();
3500   unsigned EVTBits = ExtVT.getSizeInBits();
3501
3502   unsigned NumElems = Op.getNumOperands();
3503   unsigned NumZero  = 0;
3504   unsigned NumNonZero = 0;
3505   unsigned NonZeros = 0;
3506   bool IsAllConstants = true;
3507   SmallSet<SDValue, 8> Values;
3508   for (unsigned i = 0; i < NumElems; ++i) {
3509     SDValue Elt = Op.getOperand(i);
3510     if (Elt.getOpcode() == ISD::UNDEF)
3511       continue;
3512     Values.insert(Elt);
3513     if (Elt.getOpcode() != ISD::Constant &&
3514         Elt.getOpcode() != ISD::ConstantFP)
3515       IsAllConstants = false;
3516     if (X86::isZeroNode(Elt))
3517       NumZero++;
3518     else {
3519       NonZeros |= (1 << i);
3520       NumNonZero++;
3521     }
3522   }
3523
3524   if (NumNonZero == 0) {
3525     // All undef vector. Return an UNDEF.  All zero vectors were handled above.
3526     return DAG.getUNDEF(VT);
3527   }
3528
3529   // Special case for single non-zero, non-undef, element.
3530   if (NumNonZero == 1) {
3531     unsigned Idx = CountTrailingZeros_32(NonZeros);
3532     SDValue Item = Op.getOperand(Idx);
3533
3534     // If this is an insertion of an i64 value on x86-32, and if the top bits of
3535     // the value are obviously zero, truncate the value to i32 and do the
3536     // insertion that way.  Only do this if the value is non-constant or if the
3537     // value is a constant being inserted into element 0.  It is cheaper to do
3538     // a constant pool load than it is to do a movd + shuffle.
3539     if (ExtVT == MVT::i64 && !Subtarget->is64Bit() &&
3540         (!IsAllConstants || Idx == 0)) {
3541       if (DAG.MaskedValueIsZero(Item, APInt::getBitsSet(64, 32, 64))) {
3542         // Handle MMX and SSE both.
3543         EVT VecVT = VT == MVT::v2i64 ? MVT::v4i32 : MVT::v2i32;
3544         unsigned VecElts = VT == MVT::v2i64 ? 4 : 2;
3545
3546         // Truncate the value (which may itself be a constant) to i32, and
3547         // convert it to a vector with movd (S2V+shuffle to zero extend).
3548         Item = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Item);
3549         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VecVT, Item);
3550         Item = getShuffleVectorZeroOrUndef(Item, 0, true,
3551                                            Subtarget->hasSSE2(), DAG);
3552
3553         // Now we have our 32-bit value zero extended in the low element of
3554         // a vector.  If Idx != 0, swizzle it into place.
3555         if (Idx != 0) {
3556           SmallVector<int, 4> Mask;
3557           Mask.push_back(Idx);
3558           for (unsigned i = 1; i != VecElts; ++i)
3559             Mask.push_back(i);
3560           Item = DAG.getVectorShuffle(VecVT, dl, Item,
3561                                       DAG.getUNDEF(Item.getValueType()),
3562                                       &Mask[0]);
3563         }
3564         return DAG.getNode(ISD::BIT_CONVERT, dl, Op.getValueType(), Item);
3565       }
3566     }
3567
3568     // If we have a constant or non-constant insertion into the low element of
3569     // a vector, we can do this with SCALAR_TO_VECTOR + shuffle of zero into
3570     // the rest of the elements.  This will be matched as movd/movq/movss/movsd
3571     // depending on what the source datatype is.
3572     if (Idx == 0) {
3573       if (NumZero == 0) {
3574         return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
3575       } else if (ExtVT == MVT::i32 || ExtVT == MVT::f32 || ExtVT == MVT::f64 ||
3576           (ExtVT == MVT::i64 && Subtarget->is64Bit())) {
3577         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
3578         // Turn it into a MOVL (i.e. movss, movsd, or movd) to a zero vector.
3579         return getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget->hasSSE2(),
3580                                            DAG);
3581       } else if (ExtVT == MVT::i16 || ExtVT == MVT::i8) {
3582         Item = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, Item);
3583         EVT MiddleVT = VT.getSizeInBits() == 64 ? MVT::v2i32 : MVT::v4i32;
3584         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MiddleVT, Item);
3585         Item = getShuffleVectorZeroOrUndef(Item, 0, true,
3586                                            Subtarget->hasSSE2(), DAG);
3587         return DAG.getNode(ISD::BIT_CONVERT, dl, VT, Item);
3588       }
3589     }
3590
3591     // Is it a vector logical left shift?
3592     if (NumElems == 2 && Idx == 1 &&
3593         X86::isZeroNode(Op.getOperand(0)) &&
3594         !X86::isZeroNode(Op.getOperand(1))) {
3595       unsigned NumBits = VT.getSizeInBits();
3596       return getVShift(true, VT,
3597                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
3598                                    VT, Op.getOperand(1)),
3599                        NumBits/2, DAG, *this, dl);
3600     }
3601
3602     if (IsAllConstants) // Otherwise, it's better to do a constpool load.
3603       return SDValue();
3604
3605     // Otherwise, if this is a vector with i32 or f32 elements, and the element
3606     // is a non-constant being inserted into an element other than the low one,
3607     // we can't use a constant pool load.  Instead, use SCALAR_TO_VECTOR (aka
3608     // movd/movss) to move this into the low element, then shuffle it into
3609     // place.
3610     if (EVTBits == 32) {
3611       Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
3612
3613       // Turn it into a shuffle of zero and zero-extended scalar to vector.
3614       Item = getShuffleVectorZeroOrUndef(Item, 0, NumZero > 0,
3615                                          Subtarget->hasSSE2(), DAG);
3616       SmallVector<int, 8> MaskVec;
3617       for (unsigned i = 0; i < NumElems; i++)
3618         MaskVec.push_back(i == Idx ? 0 : 1);
3619       return DAG.getVectorShuffle(VT, dl, Item, DAG.getUNDEF(VT), &MaskVec[0]);
3620     }
3621   }
3622
3623   // Splat is obviously ok. Let legalizer expand it to a shuffle.
3624   if (Values.size() == 1) {
3625     if (EVTBits == 32) {
3626       // Instead of a shuffle like this:
3627       // shuffle (scalar_to_vector (load (ptr + 4))), undef, <0, 0, 0, 0>
3628       // Check if it's possible to issue this instead.
3629       // shuffle (vload ptr)), undef, <1, 1, 1, 1>
3630       unsigned Idx = CountTrailingZeros_32(NonZeros);
3631       SDValue Item = Op.getOperand(Idx);
3632       if (Op.getNode()->isOnlyUserOf(Item.getNode()))
3633         return LowerAsSplatVectorLoad(Item, VT, dl, DAG);
3634     }
3635     return SDValue();
3636   }
3637
3638   // A vector full of immediates; various special cases are already
3639   // handled, so this is best done with a single constant-pool load.
3640   if (IsAllConstants)
3641     return SDValue();
3642
3643   // Let legalizer expand 2-wide build_vectors.
3644   if (EVTBits == 64) {
3645     if (NumNonZero == 1) {
3646       // One half is zero or undef.
3647       unsigned Idx = CountTrailingZeros_32(NonZeros);
3648       SDValue V2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT,
3649                                  Op.getOperand(Idx));
3650       return getShuffleVectorZeroOrUndef(V2, Idx, true,
3651                                          Subtarget->hasSSE2(), DAG);
3652     }
3653     return SDValue();
3654   }
3655
3656   // If element VT is < 32 bits, convert it to inserts into a zero vector.
3657   if (EVTBits == 8 && NumElems == 16) {
3658     SDValue V = LowerBuildVectorv16i8(Op, NonZeros,NumNonZero,NumZero, DAG,
3659                                         *this);
3660     if (V.getNode()) return V;
3661   }
3662
3663   if (EVTBits == 16 && NumElems == 8) {
3664     SDValue V = LowerBuildVectorv8i16(Op, NonZeros,NumNonZero,NumZero, DAG,
3665                                         *this);
3666     if (V.getNode()) return V;
3667   }
3668
3669   // If element VT is == 32 bits, turn it into a number of shuffles.
3670   SmallVector<SDValue, 8> V;
3671   V.resize(NumElems);
3672   if (NumElems == 4 && NumZero > 0) {
3673     for (unsigned i = 0; i < 4; ++i) {
3674       bool isZero = !(NonZeros & (1 << i));
3675       if (isZero)
3676         V[i] = getZeroVector(VT, Subtarget->hasSSE2(), DAG, dl);
3677       else
3678         V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
3679     }
3680
3681     for (unsigned i = 0; i < 2; ++i) {
3682       switch ((NonZeros & (0x3 << i*2)) >> (i*2)) {
3683         default: break;
3684         case 0:
3685           V[i] = V[i*2];  // Must be a zero vector.
3686           break;
3687         case 1:
3688           V[i] = getMOVL(DAG, dl, VT, V[i*2+1], V[i*2]);
3689           break;
3690         case 2:
3691           V[i] = getMOVL(DAG, dl, VT, V[i*2], V[i*2+1]);
3692           break;
3693         case 3:
3694           V[i] = getUnpackl(DAG, dl, VT, V[i*2], V[i*2+1]);
3695           break;
3696       }
3697     }
3698
3699     SmallVector<int, 8> MaskVec;
3700     bool Reverse = (NonZeros & 0x3) == 2;
3701     for (unsigned i = 0; i < 2; ++i)
3702       MaskVec.push_back(Reverse ? 1-i : i);
3703     Reverse = ((NonZeros & (0x3 << 2)) >> 2) == 2;
3704     for (unsigned i = 0; i < 2; ++i)
3705       MaskVec.push_back(Reverse ? 1-i+NumElems : i+NumElems);
3706     return DAG.getVectorShuffle(VT, dl, V[0], V[1], &MaskVec[0]);
3707   }
3708
3709   if (Values.size() > 2) {
3710     // If we have SSE 4.1, Expand into a number of inserts unless the number of
3711     // values to be inserted is equal to the number of elements, in which case
3712     // use the unpack code below in the hopes of matching the consecutive elts
3713     // load merge pattern for shuffles.
3714     // FIXME: We could probably just check that here directly.
3715     if (Values.size() < NumElems && VT.getSizeInBits() == 128 &&
3716         getSubtarget()->hasSSE41()) {
3717       V[0] = DAG.getUNDEF(VT);
3718       for (unsigned i = 0; i < NumElems; ++i)
3719         if (Op.getOperand(i).getOpcode() != ISD::UNDEF)
3720           V[0] = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, V[0],
3721                              Op.getOperand(i), DAG.getIntPtrConstant(i));
3722       return V[0];
3723     }
3724     // Expand into a number of unpckl*.
3725     // e.g. for v4f32
3726     //   Step 1: unpcklps 0, 2 ==> X: <?, ?, 2, 0>
3727     //         : unpcklps 1, 3 ==> Y: <?, ?, 3, 1>
3728     //   Step 2: unpcklps X, Y ==>    <3, 2, 1, 0>
3729     for (unsigned i = 0; i < NumElems; ++i)
3730       V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
3731     NumElems >>= 1;
3732     while (NumElems != 0) {
3733       for (unsigned i = 0; i < NumElems; ++i)
3734         V[i] = getUnpackl(DAG, dl, VT, V[i], V[i + NumElems]);
3735       NumElems >>= 1;
3736     }
3737     return V[0];
3738   }
3739
3740   return SDValue();
3741 }
3742
3743 SDValue
3744 X86TargetLowering::LowerCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
3745   // We support concatenate two MMX registers and place them in a MMX
3746   // register.  This is better than doing a stack convert.
3747   DebugLoc dl = Op.getDebugLoc();
3748   EVT ResVT = Op.getValueType();
3749   assert(Op.getNumOperands() == 2);
3750   assert(ResVT == MVT::v2i64 || ResVT == MVT::v4i32 ||
3751          ResVT == MVT::v8i16 || ResVT == MVT::v16i8);
3752   int Mask[2];
3753   SDValue InVec = DAG.getNode(ISD::BIT_CONVERT,dl, MVT::v1i64, Op.getOperand(0));
3754   SDValue VecOp = DAG.getNode(X86ISD::MOVQ2DQ, dl, MVT::v2i64, InVec);
3755   InVec = Op.getOperand(1);
3756   if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR) {
3757     unsigned NumElts = ResVT.getVectorNumElements();
3758     VecOp = DAG.getNode(ISD::BIT_CONVERT, dl, ResVT, VecOp);
3759     VecOp = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, ResVT, VecOp,
3760                        InVec.getOperand(0), DAG.getIntPtrConstant(NumElts/2+1));
3761   } else {
3762     InVec = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v1i64, InVec);
3763     SDValue VecOp2 = DAG.getNode(X86ISD::MOVQ2DQ, dl, MVT::v2i64, InVec);
3764     Mask[0] = 0; Mask[1] = 2;
3765     VecOp = DAG.getVectorShuffle(MVT::v2i64, dl, VecOp, VecOp2, Mask);
3766   }
3767   return DAG.getNode(ISD::BIT_CONVERT, dl, ResVT, VecOp);
3768 }
3769
3770 // v8i16 shuffles - Prefer shuffles in the following order:
3771 // 1. [all]   pshuflw, pshufhw, optional move
3772 // 2. [ssse3] 1 x pshufb
3773 // 3. [ssse3] 2 x pshufb + 1 x por
3774 // 4. [all]   mov + pshuflw + pshufhw + N x (pextrw + pinsrw)
3775 static
3776 SDValue LowerVECTOR_SHUFFLEv8i16(ShuffleVectorSDNode *SVOp,
3777                                  SelectionDAG &DAG, X86TargetLowering &TLI) {
3778   SDValue V1 = SVOp->getOperand(0);
3779   SDValue V2 = SVOp->getOperand(1);
3780   DebugLoc dl = SVOp->getDebugLoc();
3781   SmallVector<int, 8> MaskVals;
3782
3783   // Determine if more than 1 of the words in each of the low and high quadwords
3784   // of the result come from the same quadword of one of the two inputs.  Undef
3785   // mask values count as coming from any quadword, for better codegen.
3786   SmallVector<unsigned, 4> LoQuad(4);
3787   SmallVector<unsigned, 4> HiQuad(4);
3788   BitVector InputQuads(4);
3789   for (unsigned i = 0; i < 8; ++i) {
3790     SmallVectorImpl<unsigned> &Quad = i < 4 ? LoQuad : HiQuad;
3791     int EltIdx = SVOp->getMaskElt(i);
3792     MaskVals.push_back(EltIdx);
3793     if (EltIdx < 0) {
3794       ++Quad[0];
3795       ++Quad[1];
3796       ++Quad[2];
3797       ++Quad[3];
3798       continue;
3799     }
3800     ++Quad[EltIdx / 4];
3801     InputQuads.set(EltIdx / 4);
3802   }
3803
3804   int BestLoQuad = -1;
3805   unsigned MaxQuad = 1;
3806   for (unsigned i = 0; i < 4; ++i) {
3807     if (LoQuad[i] > MaxQuad) {
3808       BestLoQuad = i;
3809       MaxQuad = LoQuad[i];
3810     }
3811   }
3812
3813   int BestHiQuad = -1;
3814   MaxQuad = 1;
3815   for (unsigned i = 0; i < 4; ++i) {
3816     if (HiQuad[i] > MaxQuad) {
3817       BestHiQuad = i;
3818       MaxQuad = HiQuad[i];
3819     }
3820   }
3821
3822   // For SSSE3, If all 8 words of the result come from only 1 quadword of each
3823   // of the two input vectors, shuffle them into one input vector so only a
3824   // single pshufb instruction is necessary. If There are more than 2 input
3825   // quads, disable the next transformation since it does not help SSSE3.
3826   bool V1Used = InputQuads[0] || InputQuads[1];
3827   bool V2Used = InputQuads[2] || InputQuads[3];
3828   if (TLI.getSubtarget()->hasSSSE3()) {
3829     if (InputQuads.count() == 2 && V1Used && V2Used) {
3830       BestLoQuad = InputQuads.find_first();
3831       BestHiQuad = InputQuads.find_next(BestLoQuad);
3832     }
3833     if (InputQuads.count() > 2) {
3834       BestLoQuad = -1;
3835       BestHiQuad = -1;
3836     }
3837   }
3838
3839   // If BestLoQuad or BestHiQuad are set, shuffle the quads together and update
3840   // the shuffle mask.  If a quad is scored as -1, that means that it contains
3841   // words from all 4 input quadwords.
3842   SDValue NewV;
3843   if (BestLoQuad >= 0 || BestHiQuad >= 0) {
3844     SmallVector<int, 8> MaskV;
3845     MaskV.push_back(BestLoQuad < 0 ? 0 : BestLoQuad);
3846     MaskV.push_back(BestHiQuad < 0 ? 1 : BestHiQuad);
3847     NewV = DAG.getVectorShuffle(MVT::v2i64, dl,
3848                   DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v2i64, V1),
3849                   DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v2i64, V2), &MaskV[0]);
3850     NewV = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v8i16, NewV);
3851
3852     // Rewrite the MaskVals and assign NewV to V1 if NewV now contains all the
3853     // source words for the shuffle, to aid later transformations.
3854     bool AllWordsInNewV = true;
3855     bool InOrder[2] = { true, true };
3856     for (unsigned i = 0; i != 8; ++i) {
3857       int idx = MaskVals[i];
3858       if (idx != (int)i)
3859         InOrder[i/4] = false;
3860       if (idx < 0 || (idx/4) == BestLoQuad || (idx/4) == BestHiQuad)
3861         continue;
3862       AllWordsInNewV = false;
3863       break;
3864     }
3865
3866     bool pshuflw = AllWordsInNewV, pshufhw = AllWordsInNewV;
3867     if (AllWordsInNewV) {
3868       for (int i = 0; i != 8; ++i) {
3869         int idx = MaskVals[i];
3870         if (idx < 0)
3871           continue;
3872         idx = MaskVals[i] = (idx / 4) == BestLoQuad ? (idx & 3) : (idx & 3) + 4;
3873         if ((idx != i) && idx < 4)
3874           pshufhw = false;
3875         if ((idx != i) && idx > 3)
3876           pshuflw = false;
3877       }
3878       V1 = NewV;
3879       V2Used = false;
3880       BestLoQuad = 0;
3881       BestHiQuad = 1;
3882     }
3883
3884     // If we've eliminated the use of V2, and the new mask is a pshuflw or
3885     // pshufhw, that's as cheap as it gets.  Return the new shuffle.
3886     if ((pshufhw && InOrder[0]) || (pshuflw && InOrder[1])) {
3887       return DAG.getVectorShuffle(MVT::v8i16, dl, NewV,
3888                                   DAG.getUNDEF(MVT::v8i16), &MaskVals[0]);
3889     }
3890   }
3891
3892   // If we have SSSE3, and all words of the result are from 1 input vector,
3893   // case 2 is generated, otherwise case 3 is generated.  If no SSSE3
3894   // is present, fall back to case 4.
3895   if (TLI.getSubtarget()->hasSSSE3()) {
3896     SmallVector<SDValue,16> pshufbMask;
3897
3898     // If we have elements from both input vectors, set the high bit of the
3899     // shuffle mask element to zero out elements that come from V2 in the V1
3900     // mask, and elements that come from V1 in the V2 mask, so that the two
3901     // results can be OR'd together.
3902     bool TwoInputs = V1Used && V2Used;
3903     for (unsigned i = 0; i != 8; ++i) {
3904       int EltIdx = MaskVals[i] * 2;
3905       if (TwoInputs && (EltIdx >= 16)) {
3906         pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
3907         pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
3908         continue;
3909       }
3910       pshufbMask.push_back(DAG.getConstant(EltIdx,   MVT::i8));
3911       pshufbMask.push_back(DAG.getConstant(EltIdx+1, MVT::i8));
3912     }
3913     V1 = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v16i8, V1);
3914     V1 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V1,
3915                      DAG.getNode(ISD::BUILD_VECTOR, dl,
3916                                  MVT::v16i8, &pshufbMask[0], 16));
3917     if (!TwoInputs)
3918       return DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v8i16, V1);
3919
3920     // Calculate the shuffle mask for the second input, shuffle it, and
3921     // OR it with the first shuffled input.
3922     pshufbMask.clear();
3923     for (unsigned i = 0; i != 8; ++i) {
3924       int EltIdx = MaskVals[i] * 2;
3925       if (EltIdx < 16) {
3926         pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
3927         pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
3928         continue;
3929       }
3930       pshufbMask.push_back(DAG.getConstant(EltIdx - 16, MVT::i8));
3931       pshufbMask.push_back(DAG.getConstant(EltIdx - 15, MVT::i8));
3932     }
3933     V2 = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v16i8, V2);
3934     V2 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V2,
3935                      DAG.getNode(ISD::BUILD_VECTOR, dl,
3936                                  MVT::v16i8, &pshufbMask[0], 16));
3937     V1 = DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2);
3938     return DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v8i16, V1);
3939   }
3940
3941   // If BestLoQuad >= 0, generate a pshuflw to put the low elements in order,
3942   // and update MaskVals with new element order.
3943   BitVector InOrder(8);
3944   if (BestLoQuad >= 0) {
3945     SmallVector<int, 8> MaskV;
3946     for (int i = 0; i != 4; ++i) {
3947       int idx = MaskVals[i];
3948       if (idx < 0) {
3949         MaskV.push_back(-1);
3950         InOrder.set(i);
3951       } else if ((idx / 4) == BestLoQuad) {
3952         MaskV.push_back(idx & 3);
3953         InOrder.set(i);
3954       } else {
3955         MaskV.push_back(-1);
3956       }
3957     }
3958     for (unsigned i = 4; i != 8; ++i)
3959       MaskV.push_back(i);
3960     NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::v8i16),
3961                                 &MaskV[0]);
3962   }
3963
3964   // If BestHi >= 0, generate a pshufhw to put the high elements in order,
3965   // and update MaskVals with the new element order.
3966   if (BestHiQuad >= 0) {
3967     SmallVector<int, 8> MaskV;
3968     for (unsigned i = 0; i != 4; ++i)
3969       MaskV.push_back(i);
3970     for (unsigned i = 4; i != 8; ++i) {
3971       int idx = MaskVals[i];
3972       if (idx < 0) {
3973         MaskV.push_back(-1);
3974         InOrder.set(i);
3975       } else if ((idx / 4) == BestHiQuad) {
3976         MaskV.push_back((idx & 3) + 4);
3977         InOrder.set(i);
3978       } else {
3979         MaskV.push_back(-1);
3980       }
3981     }
3982     NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::v8i16),
3983                                 &MaskV[0]);
3984   }
3985
3986   // In case BestHi & BestLo were both -1, which means each quadword has a word
3987   // from each of the four input quadwords, calculate the InOrder bitvector now
3988   // before falling through to the insert/extract cleanup.
3989   if (BestLoQuad == -1 && BestHiQuad == -1) {
3990     NewV = V1;
3991     for (int i = 0; i != 8; ++i)
3992       if (MaskVals[i] < 0 || MaskVals[i] == i)
3993         InOrder.set(i);
3994   }
3995
3996   // The other elements are put in the right place using pextrw and pinsrw.
3997   for (unsigned i = 0; i != 8; ++i) {
3998     if (InOrder[i])
3999       continue;
4000     int EltIdx = MaskVals[i];
4001     if (EltIdx < 0)
4002       continue;
4003     SDValue ExtOp = (EltIdx < 8)
4004     ? DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V1,
4005                   DAG.getIntPtrConstant(EltIdx))
4006     : DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V2,
4007                   DAG.getIntPtrConstant(EltIdx - 8));
4008     NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, ExtOp,
4009                        DAG.getIntPtrConstant(i));
4010   }
4011   return NewV;
4012 }
4013
4014 // v16i8 shuffles - Prefer shuffles in the following order:
4015 // 1. [ssse3] 1 x pshufb
4016 // 2. [ssse3] 2 x pshufb + 1 x por
4017 // 3. [all]   v8i16 shuffle + N x pextrw + rotate + pinsrw
4018 static
4019 SDValue LowerVECTOR_SHUFFLEv16i8(ShuffleVectorSDNode *SVOp,
4020                                  SelectionDAG &DAG, X86TargetLowering &TLI) {
4021   SDValue V1 = SVOp->getOperand(0);
4022   SDValue V2 = SVOp->getOperand(1);
4023   DebugLoc dl = SVOp->getDebugLoc();
4024   SmallVector<int, 16> MaskVals;
4025   SVOp->getMask(MaskVals);
4026
4027   // If we have SSSE3, case 1 is generated when all result bytes come from
4028   // one of  the inputs.  Otherwise, case 2 is generated.  If no SSSE3 is
4029   // present, fall back to case 3.
4030   // FIXME: kill V2Only once shuffles are canonizalized by getNode.
4031   bool V1Only = true;
4032   bool V2Only = true;
4033   for (unsigned i = 0; i < 16; ++i) {
4034     int EltIdx = MaskVals[i];
4035     if (EltIdx < 0)
4036       continue;
4037     if (EltIdx < 16)
4038       V2Only = false;
4039     else
4040       V1Only = false;
4041   }
4042
4043   // If SSSE3, use 1 pshufb instruction per vector with elements in the result.
4044   if (TLI.getSubtarget()->hasSSSE3()) {
4045     SmallVector<SDValue,16> pshufbMask;
4046
4047     // If all result elements are from one input vector, then only translate
4048     // undef mask values to 0x80 (zero out result) in the pshufb mask.
4049     //
4050     // Otherwise, we have elements from both input vectors, and must zero out
4051     // elements that come from V2 in the first mask, and V1 in the second mask
4052     // so that we can OR them together.
4053     bool TwoInputs = !(V1Only || V2Only);
4054     for (unsigned i = 0; i != 16; ++i) {
4055       int EltIdx = MaskVals[i];
4056       if (EltIdx < 0 || (TwoInputs && EltIdx >= 16)) {
4057         pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
4058         continue;
4059       }
4060       pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8));
4061     }
4062     // If all the elements are from V2, assign it to V1 and return after
4063     // building the first pshufb.
4064     if (V2Only)
4065       V1 = V2;
4066     V1 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V1,
4067                      DAG.getNode(ISD::BUILD_VECTOR, dl,
4068                                  MVT::v16i8, &pshufbMask[0], 16));
4069     if (!TwoInputs)
4070       return V1;
4071
4072     // Calculate the shuffle mask for the second input, shuffle it, and
4073     // OR it with the first shuffled input.
4074     pshufbMask.clear();
4075     for (unsigned i = 0; i != 16; ++i) {
4076       int EltIdx = MaskVals[i];
4077       if (EltIdx < 16) {
4078         pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
4079         continue;
4080       }
4081       pshufbMask.push_back(DAG.getConstant(EltIdx - 16, MVT::i8));
4082     }
4083     V2 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V2,
4084                      DAG.getNode(ISD::BUILD_VECTOR, dl,
4085                                  MVT::v16i8, &pshufbMask[0], 16));
4086     return DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2);
4087   }
4088
4089   // No SSSE3 - Calculate in place words and then fix all out of place words
4090   // With 0-16 extracts & inserts.  Worst case is 16 bytes out of order from
4091   // the 16 different words that comprise the two doublequadword input vectors.
4092   V1 = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v8i16, V1);
4093   V2 = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v8i16, V2);
4094   SDValue NewV = V2Only ? V2 : V1;
4095   for (int i = 0; i != 8; ++i) {
4096     int Elt0 = MaskVals[i*2];
4097     int Elt1 = MaskVals[i*2+1];
4098
4099     // This word of the result is all undef, skip it.
4100     if (Elt0 < 0 && Elt1 < 0)
4101       continue;
4102
4103     // This word of the result is already in the correct place, skip it.
4104     if (V1Only && (Elt0 == i*2) && (Elt1 == i*2+1))
4105       continue;
4106     if (V2Only && (Elt0 == i*2+16) && (Elt1 == i*2+17))
4107       continue;
4108
4109     SDValue Elt0Src = Elt0 < 16 ? V1 : V2;
4110     SDValue Elt1Src = Elt1 < 16 ? V1 : V2;
4111     SDValue InsElt;
4112
4113     // If Elt0 and Elt1 are defined, are consecutive, and can be load
4114     // using a single extract together, load it and store it.
4115     if ((Elt0 >= 0) && ((Elt0 + 1) == Elt1) && ((Elt0 & 1) == 0)) {
4116       InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src,
4117                            DAG.getIntPtrConstant(Elt1 / 2));
4118       NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt,
4119                         DAG.getIntPtrConstant(i));
4120       continue;
4121     }
4122
4123     // If Elt1 is defined, extract it from the appropriate source.  If the
4124     // source byte is not also odd, shift the extracted word left 8 bits
4125     // otherwise clear the bottom 8 bits if we need to do an or.
4126     if (Elt1 >= 0) {
4127       InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src,
4128                            DAG.getIntPtrConstant(Elt1 / 2));
4129       if ((Elt1 & 1) == 0)
4130         InsElt = DAG.getNode(ISD::SHL, dl, MVT::i16, InsElt,
4131                              DAG.getConstant(8, TLI.getShiftAmountTy()));
4132       else if (Elt0 >= 0)
4133         InsElt = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt,
4134                              DAG.getConstant(0xFF00, MVT::i16));
4135     }
4136     // If Elt0 is defined, extract it from the appropriate source.  If the
4137     // source byte is not also even, shift the extracted word right 8 bits. If
4138     // Elt1 was also defined, OR the extracted values together before
4139     // inserting them in the result.
4140     if (Elt0 >= 0) {
4141       SDValue InsElt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16,
4142                                     Elt0Src, DAG.getIntPtrConstant(Elt0 / 2));
4143       if ((Elt0 & 1) != 0)
4144         InsElt0 = DAG.getNode(ISD::SRL, dl, MVT::i16, InsElt0,
4145                               DAG.getConstant(8, TLI.getShiftAmountTy()));
4146       else if (Elt1 >= 0)
4147         InsElt0 = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt0,
4148                              DAG.getConstant(0x00FF, MVT::i16));
4149       InsElt = Elt1 >= 0 ? DAG.getNode(ISD::OR, dl, MVT::i16, InsElt, InsElt0)
4150                          : InsElt0;
4151     }
4152     NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt,
4153                        DAG.getIntPtrConstant(i));
4154   }
4155   return DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v16i8, NewV);
4156 }
4157
4158 /// RewriteAsNarrowerShuffle - Try rewriting v8i16 and v16i8 shuffles as 4 wide
4159 /// ones, or rewriting v4i32 / v2f32 as 2 wide ones if possible. This can be
4160 /// done when every pair / quad of shuffle mask elements point to elements in
4161 /// the right sequence. e.g.
4162 /// vector_shuffle <>, <>, < 3, 4, | 10, 11, | 0, 1, | 14, 15>
4163 static
4164 SDValue RewriteAsNarrowerShuffle(ShuffleVectorSDNode *SVOp,
4165                                  SelectionDAG &DAG,
4166                                  TargetLowering &TLI, DebugLoc dl) {
4167   EVT VT = SVOp->getValueType(0);
4168   SDValue V1 = SVOp->getOperand(0);
4169   SDValue V2 = SVOp->getOperand(1);
4170   unsigned NumElems = VT.getVectorNumElements();
4171   unsigned NewWidth = (NumElems == 4) ? 2 : 4;
4172   EVT MaskVT = MVT::getIntVectorWithNumElements(NewWidth);
4173   EVT MaskEltVT = MaskVT.getVectorElementType();
4174   EVT NewVT = MaskVT;
4175   switch (VT.getSimpleVT().SimpleTy) {
4176   default: assert(false && "Unexpected!");
4177   case MVT::v4f32: NewVT = MVT::v2f64; break;
4178   case MVT::v4i32: NewVT = MVT::v2i64; break;
4179   case MVT::v8i16: NewVT = MVT::v4i32; break;
4180   case MVT::v16i8: NewVT = MVT::v4i32; break;
4181   }
4182
4183   if (NewWidth == 2) {
4184     if (VT.isInteger())
4185       NewVT = MVT::v2i64;
4186     else
4187       NewVT = MVT::v2f64;
4188   }
4189   int Scale = NumElems / NewWidth;
4190   SmallVector<int, 8> MaskVec;
4191   for (unsigned i = 0; i < NumElems; i += Scale) {
4192     int StartIdx = -1;
4193     for (int j = 0; j < Scale; ++j) {
4194       int EltIdx = SVOp->getMaskElt(i+j);
4195       if (EltIdx < 0)
4196         continue;
4197       if (StartIdx == -1)
4198         StartIdx = EltIdx - (EltIdx % Scale);
4199       if (EltIdx != StartIdx + j)
4200         return SDValue();
4201     }
4202     if (StartIdx == -1)
4203       MaskVec.push_back(-1);
4204     else
4205       MaskVec.push_back(StartIdx / Scale);
4206   }
4207
4208   V1 = DAG.getNode(ISD::BIT_CONVERT, dl, NewVT, V1);
4209   V2 = DAG.getNode(ISD::BIT_CONVERT, dl, NewVT, V2);
4210   return DAG.getVectorShuffle(NewVT, dl, V1, V2, &MaskVec[0]);
4211 }
4212
4213 /// getVZextMovL - Return a zero-extending vector move low node.
4214 ///
4215 static SDValue getVZextMovL(EVT VT, EVT OpVT,
4216                             SDValue SrcOp, SelectionDAG &DAG,
4217                             const X86Subtarget *Subtarget, DebugLoc dl) {
4218   if (VT == MVT::v2f64 || VT == MVT::v4f32) {
4219     LoadSDNode *LD = NULL;
4220     if (!isScalarLoadToVector(SrcOp.getNode(), &LD))
4221       LD = dyn_cast<LoadSDNode>(SrcOp);
4222     if (!LD) {
4223       // movssrr and movsdrr do not clear top bits. Try to use movd, movq
4224       // instead.
4225       MVT ExtVT = (OpVT == MVT::v2f64) ? MVT::i64 : MVT::i32;
4226       if ((ExtVT.SimpleTy != MVT::i64 || Subtarget->is64Bit()) &&
4227           SrcOp.getOpcode() == ISD::SCALAR_TO_VECTOR &&
4228           SrcOp.getOperand(0).getOpcode() == ISD::BIT_CONVERT &&
4229           SrcOp.getOperand(0).getOperand(0).getValueType() == ExtVT) {
4230         // PR2108
4231         OpVT = (OpVT == MVT::v2f64) ? MVT::v2i64 : MVT::v4i32;
4232         return DAG.getNode(ISD::BIT_CONVERT, dl, VT,
4233                            DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT,
4234                                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
4235                                                    OpVT,
4236                                                    SrcOp.getOperand(0)
4237                                                           .getOperand(0))));
4238       }
4239     }
4240   }
4241
4242   return DAG.getNode(ISD::BIT_CONVERT, dl, VT,
4243                      DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT,
4244                                  DAG.getNode(ISD::BIT_CONVERT, dl,
4245                                              OpVT, SrcOp)));
4246 }
4247
4248 /// LowerVECTOR_SHUFFLE_4wide - Handle all 4 wide cases with a number of
4249 /// shuffles.
4250 static SDValue
4251 LowerVECTOR_SHUFFLE_4wide(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
4252   SDValue V1 = SVOp->getOperand(0);
4253   SDValue V2 = SVOp->getOperand(1);
4254   DebugLoc dl = SVOp->getDebugLoc();
4255   EVT VT = SVOp->getValueType(0);
4256
4257   SmallVector<std::pair<int, int>, 8> Locs;
4258   Locs.resize(4);
4259   SmallVector<int, 8> Mask1(4U, -1);
4260   SmallVector<int, 8> PermMask;
4261   SVOp->getMask(PermMask);
4262
4263   unsigned NumHi = 0;
4264   unsigned NumLo = 0;
4265   for (unsigned i = 0; i != 4; ++i) {
4266     int Idx = PermMask[i];
4267     if (Idx < 0) {
4268       Locs[i] = std::make_pair(-1, -1);
4269     } else {
4270       assert(Idx < 8 && "Invalid VECTOR_SHUFFLE index!");
4271       if (Idx < 4) {
4272         Locs[i] = std::make_pair(0, NumLo);
4273         Mask1[NumLo] = Idx;
4274         NumLo++;
4275       } else {
4276         Locs[i] = std::make_pair(1, NumHi);
4277         if (2+NumHi < 4)
4278           Mask1[2+NumHi] = Idx;
4279         NumHi++;
4280       }
4281     }
4282   }
4283
4284   if (NumLo <= 2 && NumHi <= 2) {
4285     // If no more than two elements come from either vector. This can be
4286     // implemented with two shuffles. First shuffle gather the elements.
4287     // The second shuffle, which takes the first shuffle as both of its
4288     // vector operands, put the elements into the right order.
4289     V1 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
4290
4291     SmallVector<int, 8> Mask2(4U, -1);
4292
4293     for (unsigned i = 0; i != 4; ++i) {
4294       if (Locs[i].first == -1)
4295         continue;
4296       else {
4297         unsigned Idx = (i < 2) ? 0 : 4;
4298         Idx += Locs[i].first * 2 + Locs[i].second;
4299         Mask2[i] = Idx;
4300       }
4301     }
4302
4303     return DAG.getVectorShuffle(VT, dl, V1, V1, &Mask2[0]);
4304   } else if (NumLo == 3 || NumHi == 3) {
4305     // Otherwise, we must have three elements from one vector, call it X, and
4306     // one element from the other, call it Y.  First, use a shufps to build an
4307     // intermediate vector with the one element from Y and the element from X
4308     // that will be in the same half in the final destination (the indexes don't
4309     // matter). Then, use a shufps to build the final vector, taking the half
4310     // containing the element from Y from the intermediate, and the other half
4311     // from X.
4312     if (NumHi == 3) {
4313       // Normalize it so the 3 elements come from V1.
4314       CommuteVectorShuffleMask(PermMask, VT);
4315       std::swap(V1, V2);
4316     }
4317
4318     // Find the element from V2.
4319     unsigned HiIndex;
4320     for (HiIndex = 0; HiIndex < 3; ++HiIndex) {
4321       int Val = PermMask[HiIndex];
4322       if (Val < 0)
4323         continue;
4324       if (Val >= 4)
4325         break;
4326     }
4327
4328     Mask1[0] = PermMask[HiIndex];
4329     Mask1[1] = -1;
4330     Mask1[2] = PermMask[HiIndex^1];
4331     Mask1[3] = -1;
4332     V2 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
4333
4334     if (HiIndex >= 2) {
4335       Mask1[0] = PermMask[0];
4336       Mask1[1] = PermMask[1];
4337       Mask1[2] = HiIndex & 1 ? 6 : 4;
4338       Mask1[3] = HiIndex & 1 ? 4 : 6;
4339       return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
4340     } else {
4341       Mask1[0] = HiIndex & 1 ? 2 : 0;
4342       Mask1[1] = HiIndex & 1 ? 0 : 2;
4343       Mask1[2] = PermMask[2];
4344       Mask1[3] = PermMask[3];
4345       if (Mask1[2] >= 0)
4346         Mask1[2] += 4;
4347       if (Mask1[3] >= 0)
4348         Mask1[3] += 4;
4349       return DAG.getVectorShuffle(VT, dl, V2, V1, &Mask1[0]);
4350     }
4351   }
4352
4353   // Break it into (shuffle shuffle_hi, shuffle_lo).
4354   Locs.clear();
4355   SmallVector<int,8> LoMask(4U, -1);
4356   SmallVector<int,8> HiMask(4U, -1);
4357
4358   SmallVector<int,8> *MaskPtr = &LoMask;
4359   unsigned MaskIdx = 0;
4360   unsigned LoIdx = 0;
4361   unsigned HiIdx = 2;
4362   for (unsigned i = 0; i != 4; ++i) {
4363     if (i == 2) {
4364       MaskPtr = &HiMask;
4365       MaskIdx = 1;
4366       LoIdx = 0;
4367       HiIdx = 2;
4368     }
4369     int Idx = PermMask[i];
4370     if (Idx < 0) {
4371       Locs[i] = std::make_pair(-1, -1);
4372     } else if (Idx < 4) {
4373       Locs[i] = std::make_pair(MaskIdx, LoIdx);
4374       (*MaskPtr)[LoIdx] = Idx;
4375       LoIdx++;
4376     } else {
4377       Locs[i] = std::make_pair(MaskIdx, HiIdx);
4378       (*MaskPtr)[HiIdx] = Idx;
4379       HiIdx++;
4380     }
4381   }
4382
4383   SDValue LoShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &LoMask[0]);
4384   SDValue HiShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &HiMask[0]);
4385   SmallVector<int, 8> MaskOps;
4386   for (unsigned i = 0; i != 4; ++i) {
4387     if (Locs[i].first == -1) {
4388       MaskOps.push_back(-1);
4389     } else {
4390       unsigned Idx = Locs[i].first * 4 + Locs[i].second;
4391       MaskOps.push_back(Idx);
4392     }
4393   }
4394   return DAG.getVectorShuffle(VT, dl, LoShuffle, HiShuffle, &MaskOps[0]);
4395 }
4396
4397 SDValue
4398 X86TargetLowering::LowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG) {
4399   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
4400   SDValue V1 = Op.getOperand(0);
4401   SDValue V2 = Op.getOperand(1);
4402   EVT VT = Op.getValueType();
4403   DebugLoc dl = Op.getDebugLoc();
4404   unsigned NumElems = VT.getVectorNumElements();
4405   bool isMMX = VT.getSizeInBits() == 64;
4406   bool V1IsUndef = V1.getOpcode() == ISD::UNDEF;
4407   bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
4408   bool V1IsSplat = false;
4409   bool V2IsSplat = false;
4410
4411   if (isZeroShuffle(SVOp))
4412     return getZeroVector(VT, Subtarget->hasSSE2(), DAG, dl);
4413
4414   // Promote splats to v4f32.
4415   if (SVOp->isSplat()) {
4416     if (isMMX || NumElems < 4)
4417       return Op;
4418     return PromoteSplat(SVOp, DAG, Subtarget->hasSSE2());
4419   }
4420
4421   // If the shuffle can be profitably rewritten as a narrower shuffle, then
4422   // do it!
4423   if (VT == MVT::v8i16 || VT == MVT::v16i8) {
4424     SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG, *this, dl);
4425     if (NewOp.getNode())
4426       return DAG.getNode(ISD::BIT_CONVERT, dl, VT,
4427                          LowerVECTOR_SHUFFLE(NewOp, DAG));
4428   } else if ((VT == MVT::v4i32 || (VT == MVT::v4f32 && Subtarget->hasSSE2()))) {
4429     // FIXME: Figure out a cleaner way to do this.
4430     // Try to make use of movq to zero out the top part.
4431     if (ISD::isBuildVectorAllZeros(V2.getNode())) {
4432       SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG, *this, dl);
4433       if (NewOp.getNode()) {
4434         if (isCommutedMOVL(cast<ShuffleVectorSDNode>(NewOp), true, false))
4435           return getVZextMovL(VT, NewOp.getValueType(), NewOp.getOperand(0),
4436                               DAG, Subtarget, dl);
4437       }
4438     } else if (ISD::isBuildVectorAllZeros(V1.getNode())) {
4439       SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG, *this, dl);
4440       if (NewOp.getNode() && X86::isMOVLMask(cast<ShuffleVectorSDNode>(NewOp)))
4441         return getVZextMovL(VT, NewOp.getValueType(), NewOp.getOperand(1),
4442                             DAG, Subtarget, dl);
4443     }
4444   }
4445
4446   if (X86::isPSHUFDMask(SVOp))
4447     return Op;
4448
4449   // Check if this can be converted into a logical shift.
4450   bool isLeft = false;
4451   unsigned ShAmt = 0;
4452   SDValue ShVal;
4453   bool isShift = getSubtarget()->hasSSE2() &&
4454     isVectorShift(SVOp, DAG, isLeft, ShVal, ShAmt);
4455   if (isShift && ShVal.hasOneUse()) {
4456     // If the shifted value has multiple uses, it may be cheaper to use
4457     // v_set0 + movlhps or movhlps, etc.
4458     EVT EltVT = VT.getVectorElementType();
4459     ShAmt *= EltVT.getSizeInBits();
4460     return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
4461   }
4462
4463   if (X86::isMOVLMask(SVOp)) {
4464     if (V1IsUndef)
4465       return V2;
4466     if (ISD::isBuildVectorAllZeros(V1.getNode()))
4467       return getVZextMovL(VT, VT, V2, DAG, Subtarget, dl);
4468     if (!isMMX)
4469       return Op;
4470   }
4471
4472   // FIXME: fold these into legal mask.
4473   if (!isMMX && (X86::isMOVSHDUPMask(SVOp) ||
4474                  X86::isMOVSLDUPMask(SVOp) ||
4475                  X86::isMOVHLPSMask(SVOp) ||
4476                  X86::isMOVLHPSMask(SVOp) ||
4477                  X86::isMOVLPMask(SVOp)))
4478     return Op;
4479
4480   if (ShouldXformToMOVHLPS(SVOp) ||
4481       ShouldXformToMOVLP(V1.getNode(), V2.getNode(), SVOp))
4482     return CommuteVectorShuffle(SVOp, DAG);
4483
4484   if (isShift) {
4485     // No better options. Use a vshl / vsrl.
4486     EVT EltVT = VT.getVectorElementType();
4487     ShAmt *= EltVT.getSizeInBits();
4488     return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
4489   }
4490
4491   bool Commuted = false;
4492   // FIXME: This should also accept a bitcast of a splat?  Be careful, not
4493   // 1,1,1,1 -> v8i16 though.
4494   V1IsSplat = isSplatVector(V1.getNode());
4495   V2IsSplat = isSplatVector(V2.getNode());
4496
4497   // Canonicalize the splat or undef, if present, to be on the RHS.
4498   if ((V1IsSplat || V1IsUndef) && !(V2IsSplat || V2IsUndef)) {
4499     Op = CommuteVectorShuffle(SVOp, DAG);
4500     SVOp = cast<ShuffleVectorSDNode>(Op);
4501     V1 = SVOp->getOperand(0);
4502     V2 = SVOp->getOperand(1);
4503     std::swap(V1IsSplat, V2IsSplat);
4504     std::swap(V1IsUndef, V2IsUndef);
4505     Commuted = true;
4506   }
4507
4508   if (isCommutedMOVL(SVOp, V2IsSplat, V2IsUndef)) {
4509     // Shuffling low element of v1 into undef, just return v1.
4510     if (V2IsUndef)
4511       return V1;
4512     // If V2 is a splat, the mask may be malformed such as <4,3,3,3>, which
4513     // the instruction selector will not match, so get a canonical MOVL with
4514     // swapped operands to undo the commute.
4515     return getMOVL(DAG, dl, VT, V2, V1);
4516   }
4517
4518   if (X86::isUNPCKL_v_undef_Mask(SVOp) ||
4519       X86::isUNPCKH_v_undef_Mask(SVOp) ||
4520       X86::isUNPCKLMask(SVOp) ||
4521       X86::isUNPCKHMask(SVOp))
4522     return Op;
4523
4524   if (V2IsSplat) {
4525     // Normalize mask so all entries that point to V2 points to its first
4526     // element then try to match unpck{h|l} again. If match, return a
4527     // new vector_shuffle with the corrected mask.
4528     SDValue NewMask = NormalizeMask(SVOp, DAG);
4529     ShuffleVectorSDNode *NSVOp = cast<ShuffleVectorSDNode>(NewMask);
4530     if (NSVOp != SVOp) {
4531       if (X86::isUNPCKLMask(NSVOp, true)) {
4532         return NewMask;
4533       } else if (X86::isUNPCKHMask(NSVOp, true)) {
4534         return NewMask;
4535       }
4536     }
4537   }
4538
4539   if (Commuted) {
4540     // Commute is back and try unpck* again.
4541     // FIXME: this seems wrong.
4542     SDValue NewOp = CommuteVectorShuffle(SVOp, DAG);
4543     ShuffleVectorSDNode *NewSVOp = cast<ShuffleVectorSDNode>(NewOp);
4544     if (X86::isUNPCKL_v_undef_Mask(NewSVOp) ||
4545         X86::isUNPCKH_v_undef_Mask(NewSVOp) ||
4546         X86::isUNPCKLMask(NewSVOp) ||
4547         X86::isUNPCKHMask(NewSVOp))
4548       return NewOp;
4549   }
4550
4551   // FIXME: for mmx, bitcast v2i32 to v4i16 for shuffle.
4552
4553   // Normalize the node to match x86 shuffle ops if needed
4554   if (!isMMX && V2.getOpcode() != ISD::UNDEF && isCommutedSHUFP(SVOp))
4555     return CommuteVectorShuffle(SVOp, DAG);
4556
4557   // Check for legal shuffle and return?
4558   SmallVector<int, 16> PermMask;
4559   SVOp->getMask(PermMask);
4560   if (isShuffleMaskLegal(PermMask, VT))
4561     return Op;
4562
4563   // Handle v8i16 specifically since SSE can do byte extraction and insertion.
4564   if (VT == MVT::v8i16) {
4565     SDValue NewOp = LowerVECTOR_SHUFFLEv8i16(SVOp, DAG, *this);
4566     if (NewOp.getNode())
4567       return NewOp;
4568   }
4569
4570   if (VT == MVT::v16i8) {
4571     SDValue NewOp = LowerVECTOR_SHUFFLEv16i8(SVOp, DAG, *this);
4572     if (NewOp.getNode())
4573       return NewOp;
4574   }
4575
4576   // Handle all 4 wide cases with a number of shuffles except for MMX.
4577   if (NumElems == 4 && !isMMX)
4578     return LowerVECTOR_SHUFFLE_4wide(SVOp, DAG);
4579
4580   return SDValue();
4581 }
4582
4583 SDValue
4584 X86TargetLowering::LowerEXTRACT_VECTOR_ELT_SSE4(SDValue Op,
4585                                                 SelectionDAG &DAG) {
4586   EVT VT = Op.getValueType();
4587   DebugLoc dl = Op.getDebugLoc();
4588   if (VT.getSizeInBits() == 8) {
4589     SDValue Extract = DAG.getNode(X86ISD::PEXTRB, dl, MVT::i32,
4590                                     Op.getOperand(0), Op.getOperand(1));
4591     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
4592                                     DAG.getValueType(VT));
4593     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
4594   } else if (VT.getSizeInBits() == 16) {
4595     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
4596     // If Idx is 0, it's cheaper to do a move instead of a pextrw.
4597     if (Idx == 0)
4598       return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
4599                          DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
4600                                      DAG.getNode(ISD::BIT_CONVERT, dl,
4601                                                  MVT::v4i32,
4602                                                  Op.getOperand(0)),
4603                                      Op.getOperand(1)));
4604     SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, MVT::i32,
4605                                     Op.getOperand(0), Op.getOperand(1));
4606     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
4607                                     DAG.getValueType(VT));
4608     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
4609   } else if (VT == MVT::f32) {
4610     // EXTRACTPS outputs to a GPR32 register which will require a movd to copy
4611     // the result back to FR32 register. It's only worth matching if the
4612     // result has a single use which is a store or a bitcast to i32.  And in
4613     // the case of a store, it's not worth it if the index is a constant 0,
4614     // because a MOVSSmr can be used instead, which is smaller and faster.
4615     if (!Op.hasOneUse())
4616       return SDValue();
4617     SDNode *User = *Op.getNode()->use_begin();
4618     if ((User->getOpcode() != ISD::STORE ||
4619          (isa<ConstantSDNode>(Op.getOperand(1)) &&
4620           cast<ConstantSDNode>(Op.getOperand(1))->isNullValue())) &&
4621         (User->getOpcode() != ISD::BIT_CONVERT ||
4622          User->getValueType(0) != MVT::i32))
4623       return SDValue();
4624     SDValue Extract = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
4625                                   DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v4i32,
4626                                               Op.getOperand(0)),
4627                                               Op.getOperand(1));
4628     return DAG.getNode(ISD::BIT_CONVERT, dl, MVT::f32, Extract);
4629   } else if (VT == MVT::i32) {
4630     // ExtractPS works with constant index.
4631     if (isa<ConstantSDNode>(Op.getOperand(1)))
4632       return Op;
4633   }
4634   return SDValue();
4635 }
4636
4637
4638 SDValue
4639 X86TargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) {
4640   if (!isa<ConstantSDNode>(Op.getOperand(1)))
4641     return SDValue();
4642
4643   if (Subtarget->hasSSE41()) {
4644     SDValue Res = LowerEXTRACT_VECTOR_ELT_SSE4(Op, DAG);
4645     if (Res.getNode())
4646       return Res;
4647   }
4648
4649   EVT VT = Op.getValueType();
4650   DebugLoc dl = Op.getDebugLoc();
4651   // TODO: handle v16i8.
4652   if (VT.getSizeInBits() == 16) {
4653     SDValue Vec = Op.getOperand(0);
4654     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
4655     if (Idx == 0)
4656       return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
4657                          DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
4658                                      DAG.getNode(ISD::BIT_CONVERT, dl,
4659                                                  MVT::v4i32, Vec),
4660                                      Op.getOperand(1)));
4661     // Transform it so it match pextrw which produces a 32-bit result.
4662     EVT EltVT = MVT::i32;
4663     SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, EltVT,
4664                                     Op.getOperand(0), Op.getOperand(1));
4665     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, EltVT, Extract,
4666                                     DAG.getValueType(VT));
4667     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
4668   } else if (VT.getSizeInBits() == 32) {
4669     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
4670     if (Idx == 0)
4671       return Op;
4672
4673     // SHUFPS the element to the lowest double word, then movss.
4674     int Mask[4] = { Idx, -1, -1, -1 };
4675     EVT VVT = Op.getOperand(0).getValueType();
4676     SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
4677                                        DAG.getUNDEF(VVT), Mask);
4678     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
4679                        DAG.getIntPtrConstant(0));
4680   } else if (VT.getSizeInBits() == 64) {
4681     // FIXME: .td only matches this for <2 x f64>, not <2 x i64> on 32b
4682     // FIXME: seems like this should be unnecessary if mov{h,l}pd were taught
4683     //        to match extract_elt for f64.
4684     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
4685     if (Idx == 0)
4686       return Op;
4687
4688     // UNPCKHPD the element to the lowest double word, then movsd.
4689     // Note if the lower 64 bits of the result of the UNPCKHPD is then stored
4690     // to a f64mem, the whole operation is folded into a single MOVHPDmr.
4691     int Mask[2] = { 1, -1 };
4692     EVT VVT = Op.getOperand(0).getValueType();
4693     SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
4694                                        DAG.getUNDEF(VVT), Mask);
4695     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
4696                        DAG.getIntPtrConstant(0));
4697   }
4698
4699   return SDValue();
4700 }
4701
4702 SDValue
4703 X86TargetLowering::LowerINSERT_VECTOR_ELT_SSE4(SDValue Op, SelectionDAG &DAG){
4704   EVT VT = Op.getValueType();
4705   EVT EltVT = VT.getVectorElementType();
4706   DebugLoc dl = Op.getDebugLoc();
4707
4708   SDValue N0 = Op.getOperand(0);
4709   SDValue N1 = Op.getOperand(1);
4710   SDValue N2 = Op.getOperand(2);
4711
4712   if ((EltVT.getSizeInBits() == 8 || EltVT.getSizeInBits() == 16) &&
4713       isa<ConstantSDNode>(N2)) {
4714     unsigned Opc = (EltVT.getSizeInBits() == 8) ? X86ISD::PINSRB
4715                                                 : X86ISD::PINSRW;
4716     // Transform it so it match pinsr{b,w} which expects a GR32 as its second
4717     // argument.
4718     if (N1.getValueType() != MVT::i32)
4719       N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
4720     if (N2.getValueType() != MVT::i32)
4721       N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue());
4722     return DAG.getNode(Opc, dl, VT, N0, N1, N2);
4723   } else if (EltVT == MVT::f32 && isa<ConstantSDNode>(N2)) {
4724     // Bits [7:6] of the constant are the source select.  This will always be
4725     //  zero here.  The DAG Combiner may combine an extract_elt index into these
4726     //  bits.  For example (insert (extract, 3), 2) could be matched by putting
4727     //  the '3' into bits [7:6] of X86ISD::INSERTPS.
4728     // Bits [5:4] of the constant are the destination select.  This is the
4729     //  value of the incoming immediate.
4730     // Bits [3:0] of the constant are the zero mask.  The DAG Combiner may
4731     //   combine either bitwise AND or insert of float 0.0 to set these bits.
4732     N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue() << 4);
4733     // Create this as a scalar to vector..
4734     N1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4f32, N1);
4735     return DAG.getNode(X86ISD::INSERTPS, dl, VT, N0, N1, N2);
4736   } else if (EltVT == MVT::i32 && isa<ConstantSDNode>(N2)) {
4737     // PINSR* works with constant index.
4738     return Op;
4739   }
4740   return SDValue();
4741 }
4742
4743 SDValue
4744 X86TargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) {
4745   EVT VT = Op.getValueType();
4746   EVT EltVT = VT.getVectorElementType();
4747
4748   if (Subtarget->hasSSE41())
4749     return LowerINSERT_VECTOR_ELT_SSE4(Op, DAG);
4750
4751   if (EltVT == MVT::i8)
4752     return SDValue();
4753
4754   DebugLoc dl = Op.getDebugLoc();
4755   SDValue N0 = Op.getOperand(0);
4756   SDValue N1 = Op.getOperand(1);
4757   SDValue N2 = Op.getOperand(2);
4758
4759   if (EltVT.getSizeInBits() == 16 && isa<ConstantSDNode>(N2)) {
4760     // Transform it so it match pinsrw which expects a 16-bit value in a GR32
4761     // as its second argument.
4762     if (N1.getValueType() != MVT::i32)
4763       N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
4764     if (N2.getValueType() != MVT::i32)
4765       N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue());
4766     return DAG.getNode(X86ISD::PINSRW, dl, VT, N0, N1, N2);
4767   }
4768   return SDValue();
4769 }
4770
4771 SDValue
4772 X86TargetLowering::LowerSCALAR_TO_VECTOR(SDValue Op, SelectionDAG &DAG) {
4773   DebugLoc dl = Op.getDebugLoc();
4774   if (Op.getValueType() == MVT::v2f32)
4775     return DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v2f32,
4776                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i32,
4777                                    DAG.getNode(ISD::BIT_CONVERT, dl, MVT::i32,
4778                                                Op.getOperand(0))));
4779
4780   if (Op.getValueType() == MVT::v1i64 && Op.getOperand(0).getValueType() == MVT::i64)
4781     return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v1i64, Op.getOperand(0));
4782
4783   SDValue AnyExt = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, Op.getOperand(0));
4784   EVT VT = MVT::v2i32;
4785   switch (Op.getValueType().getSimpleVT().SimpleTy) {
4786   default: break;
4787   case MVT::v16i8:
4788   case MVT::v8i16:
4789     VT = MVT::v4i32;
4790     break;
4791   }
4792   return DAG.getNode(ISD::BIT_CONVERT, dl, Op.getValueType(),
4793                      DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, AnyExt));
4794 }
4795
4796 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
4797 // their target countpart wrapped in the X86ISD::Wrapper node. Suppose N is
4798 // one of the above mentioned nodes. It has to be wrapped because otherwise
4799 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
4800 // be used to form addressing mode. These wrapped nodes will be selected
4801 // into MOV32ri.
4802 SDValue
4803 X86TargetLowering::LowerConstantPool(SDValue Op, SelectionDAG &DAG) {
4804   ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
4805
4806   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
4807   // global base reg.
4808   unsigned char OpFlag = 0;
4809   unsigned WrapperKind = X86ISD::Wrapper;
4810   CodeModel::Model M = getTargetMachine().getCodeModel();
4811
4812   if (Subtarget->isPICStyleRIPRel() &&
4813       (M == CodeModel::Small || M == CodeModel::Kernel))
4814     WrapperKind = X86ISD::WrapperRIP;
4815   else if (Subtarget->isPICStyleGOT())
4816     OpFlag = X86II::MO_GOTOFF;
4817   else if (Subtarget->isPICStyleStubPIC())
4818     OpFlag = X86II::MO_PIC_BASE_OFFSET;
4819
4820   SDValue Result = DAG.getTargetConstantPool(CP->getConstVal(), getPointerTy(),
4821                                              CP->getAlignment(),
4822                                              CP->getOffset(), OpFlag);
4823   DebugLoc DL = CP->getDebugLoc();
4824   Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
4825   // With PIC, the address is actually $g + Offset.
4826   if (OpFlag) {
4827     Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
4828                          DAG.getNode(X86ISD::GlobalBaseReg,
4829                                      DebugLoc::getUnknownLoc(), getPointerTy()),
4830                          Result);
4831   }
4832
4833   return Result;
4834 }
4835
4836 SDValue X86TargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) {
4837   JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
4838
4839   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
4840   // global base reg.
4841   unsigned char OpFlag = 0;
4842   unsigned WrapperKind = X86ISD::Wrapper;
4843   CodeModel::Model M = getTargetMachine().getCodeModel();
4844
4845   if (Subtarget->isPICStyleRIPRel() &&
4846       (M == CodeModel::Small || M == CodeModel::Kernel))
4847     WrapperKind = X86ISD::WrapperRIP;
4848   else if (Subtarget->isPICStyleGOT())
4849     OpFlag = X86II::MO_GOTOFF;
4850   else if (Subtarget->isPICStyleStubPIC())
4851     OpFlag = X86II::MO_PIC_BASE_OFFSET;
4852
4853   SDValue Result = DAG.getTargetJumpTable(JT->getIndex(), getPointerTy(),
4854                                           OpFlag);
4855   DebugLoc DL = JT->getDebugLoc();
4856   Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
4857
4858   // With PIC, the address is actually $g + Offset.
4859   if (OpFlag) {
4860     Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
4861                          DAG.getNode(X86ISD::GlobalBaseReg,
4862                                      DebugLoc::getUnknownLoc(), getPointerTy()),
4863                          Result);
4864   }
4865
4866   return Result;
4867 }
4868
4869 SDValue
4870 X86TargetLowering::LowerExternalSymbol(SDValue Op, SelectionDAG &DAG) {
4871   const char *Sym = cast<ExternalSymbolSDNode>(Op)->getSymbol();
4872
4873   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
4874   // global base reg.
4875   unsigned char OpFlag = 0;
4876   unsigned WrapperKind = X86ISD::Wrapper;
4877   CodeModel::Model M = getTargetMachine().getCodeModel();
4878
4879   if (Subtarget->isPICStyleRIPRel() &&
4880       (M == CodeModel::Small || M == CodeModel::Kernel))
4881     WrapperKind = X86ISD::WrapperRIP;
4882   else if (Subtarget->isPICStyleGOT())
4883     OpFlag = X86II::MO_GOTOFF;
4884   else if (Subtarget->isPICStyleStubPIC())
4885     OpFlag = X86II::MO_PIC_BASE_OFFSET;
4886
4887   SDValue Result = DAG.getTargetExternalSymbol(Sym, getPointerTy(), OpFlag);
4888
4889   DebugLoc DL = Op.getDebugLoc();
4890   Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
4891
4892
4893   // With PIC, the address is actually $g + Offset.
4894   if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
4895       !Subtarget->is64Bit()) {
4896     Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
4897                          DAG.getNode(X86ISD::GlobalBaseReg,
4898                                      DebugLoc::getUnknownLoc(),
4899                                      getPointerTy()),
4900                          Result);
4901   }
4902
4903   return Result;
4904 }
4905
4906 SDValue
4907 X86TargetLowering::LowerBlockAddress(SDValue Op, SelectionDAG &DAG) {
4908   // Create the TargetBlockAddressAddress node.
4909   unsigned char OpFlags =
4910     Subtarget->ClassifyBlockAddressReference();
4911   CodeModel::Model M = getTargetMachine().getCodeModel();
4912   BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
4913   DebugLoc dl = Op.getDebugLoc();
4914   SDValue Result = DAG.getBlockAddress(BA, getPointerTy(),
4915                                        /*isTarget=*/true, OpFlags);
4916
4917   if (Subtarget->isPICStyleRIPRel() &&
4918       (M == CodeModel::Small || M == CodeModel::Kernel))
4919     Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
4920   else
4921     Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
4922
4923   // With PIC, the address is actually $g + Offset.
4924   if (isGlobalRelativeToPICBase(OpFlags)) {
4925     Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
4926                          DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
4927                          Result);
4928   }
4929
4930   return Result;
4931 }
4932
4933 SDValue
4934 X86TargetLowering::LowerGlobalAddress(const GlobalValue *GV, DebugLoc dl,
4935                                       int64_t Offset,
4936                                       SelectionDAG &DAG) const {
4937   // Create the TargetGlobalAddress node, folding in the constant
4938   // offset if it is legal.
4939   unsigned char OpFlags =
4940     Subtarget->ClassifyGlobalReference(GV, getTargetMachine());
4941   CodeModel::Model M = getTargetMachine().getCodeModel();
4942   SDValue Result;
4943   if (OpFlags == X86II::MO_NO_FLAG &&
4944       X86::isOffsetSuitableForCodeModel(Offset, M)) {
4945     // A direct static reference to a global.
4946     Result = DAG.getTargetGlobalAddress(GV, getPointerTy(), Offset);
4947     Offset = 0;
4948   } else {
4949     Result = DAG.getTargetGlobalAddress(GV, getPointerTy(), 0, OpFlags);
4950   }
4951
4952   if (Subtarget->isPICStyleRIPRel() &&
4953       (M == CodeModel::Small || M == CodeModel::Kernel))
4954     Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
4955   else
4956     Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
4957
4958   // With PIC, the address is actually $g + Offset.
4959   if (isGlobalRelativeToPICBase(OpFlags)) {
4960     Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
4961                          DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
4962                          Result);
4963   }
4964
4965   // For globals that require a load from a stub to get the address, emit the
4966   // load.
4967   if (isGlobalStubReference(OpFlags))
4968     Result = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Result,
4969                          PseudoSourceValue::getGOT(), 0);
4970
4971   // If there was a non-zero offset that we didn't fold, create an explicit
4972   // addition for it.
4973   if (Offset != 0)
4974     Result = DAG.getNode(ISD::ADD, dl, getPointerTy(), Result,
4975                          DAG.getConstant(Offset, getPointerTy()));
4976
4977   return Result;
4978 }
4979
4980 SDValue
4981 X86TargetLowering::LowerGlobalAddress(SDValue Op, SelectionDAG &DAG) {
4982   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
4983   int64_t Offset = cast<GlobalAddressSDNode>(Op)->getOffset();
4984   return LowerGlobalAddress(GV, Op.getDebugLoc(), Offset, DAG);
4985 }
4986
4987 static SDValue
4988 GetTLSADDR(SelectionDAG &DAG, SDValue Chain, GlobalAddressSDNode *GA,
4989            SDValue *InFlag, const EVT PtrVT, unsigned ReturnReg,
4990            unsigned char OperandFlags) {
4991   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
4992   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Flag);
4993   DebugLoc dl = GA->getDebugLoc();
4994   SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(),
4995                                            GA->getValueType(0),
4996                                            GA->getOffset(),
4997                                            OperandFlags);
4998   if (InFlag) {
4999     SDValue Ops[] = { Chain,  TGA, *InFlag };
5000     Chain = DAG.getNode(X86ISD::TLSADDR, dl, NodeTys, Ops, 3);
5001   } else {
5002     SDValue Ops[]  = { Chain, TGA };
5003     Chain = DAG.getNode(X86ISD::TLSADDR, dl, NodeTys, Ops, 2);
5004   }
5005
5006   // TLSADDR will be codegen'ed as call. Inform MFI that function has calls.
5007   MFI->setHasCalls(true);
5008
5009   SDValue Flag = Chain.getValue(1);
5010   return DAG.getCopyFromReg(Chain, dl, ReturnReg, PtrVT, Flag);
5011 }
5012
5013 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 32 bit
5014 static SDValue
5015 LowerToTLSGeneralDynamicModel32(GlobalAddressSDNode *GA, SelectionDAG &DAG,
5016                                 const EVT PtrVT) {
5017   SDValue InFlag;
5018   DebugLoc dl = GA->getDebugLoc();  // ? function entry point might be better
5019   SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
5020                                      DAG.getNode(X86ISD::GlobalBaseReg,
5021                                                  DebugLoc::getUnknownLoc(),
5022                                                  PtrVT), InFlag);
5023   InFlag = Chain.getValue(1);
5024
5025   return GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX, X86II::MO_TLSGD);
5026 }
5027
5028 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 64 bit
5029 static SDValue
5030 LowerToTLSGeneralDynamicModel64(GlobalAddressSDNode *GA, SelectionDAG &DAG,
5031                                 const EVT PtrVT) {
5032   return GetTLSADDR(DAG, DAG.getEntryNode(), GA, NULL, PtrVT,
5033                     X86::RAX, X86II::MO_TLSGD);
5034 }
5035
5036 // Lower ISD::GlobalTLSAddress using the "initial exec" (for no-pic) or
5037 // "local exec" model.
5038 static SDValue LowerToTLSExecModel(GlobalAddressSDNode *GA, SelectionDAG &DAG,
5039                                    const EVT PtrVT, TLSModel::Model model,
5040                                    bool is64Bit) {
5041   DebugLoc dl = GA->getDebugLoc();
5042   // Get the Thread Pointer
5043   SDValue Base = DAG.getNode(X86ISD::SegmentBaseAddress,
5044                              DebugLoc::getUnknownLoc(), PtrVT,
5045                              DAG.getRegister(is64Bit? X86::FS : X86::GS,
5046                                              MVT::i32));
5047
5048   SDValue ThreadPointer = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Base,
5049                                       NULL, 0);
5050
5051   unsigned char OperandFlags = 0;
5052   // Most TLS accesses are not RIP relative, even on x86-64.  One exception is
5053   // initialexec.
5054   unsigned WrapperKind = X86ISD::Wrapper;
5055   if (model == TLSModel::LocalExec) {
5056     OperandFlags = is64Bit ? X86II::MO_TPOFF : X86II::MO_NTPOFF;
5057   } else if (is64Bit) {
5058     assert(model == TLSModel::InitialExec);
5059     OperandFlags = X86II::MO_GOTTPOFF;
5060     WrapperKind = X86ISD::WrapperRIP;
5061   } else {
5062     assert(model == TLSModel::InitialExec);
5063     OperandFlags = X86II::MO_INDNTPOFF;
5064   }
5065
5066   // emit "addl x@ntpoff,%eax" (local exec) or "addl x@indntpoff,%eax" (initial
5067   // exec)
5068   SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), GA->getValueType(0),
5069                                            GA->getOffset(), OperandFlags);
5070   SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
5071
5072   if (model == TLSModel::InitialExec)
5073     Offset = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Offset,
5074                          PseudoSourceValue::getGOT(), 0);
5075
5076   // The address of the thread local variable is the add of the thread
5077   // pointer with the offset of the variable.
5078   return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
5079 }
5080
5081 SDValue
5082 X86TargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) {
5083   // TODO: implement the "local dynamic" model
5084   // TODO: implement the "initial exec"model for pic executables
5085   assert(Subtarget->isTargetELF() &&
5086          "TLS not implemented for non-ELF targets");
5087   GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
5088   const GlobalValue *GV = GA->getGlobal();
5089
5090   // If GV is an alias then use the aliasee for determining
5091   // thread-localness.
5092   if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(GV))
5093     GV = GA->resolveAliasedGlobal(false);
5094
5095   TLSModel::Model model = getTLSModel(GV,
5096                                       getTargetMachine().getRelocationModel());
5097
5098   switch (model) {
5099   case TLSModel::GeneralDynamic:
5100   case TLSModel::LocalDynamic: // not implemented
5101     if (Subtarget->is64Bit())
5102       return LowerToTLSGeneralDynamicModel64(GA, DAG, getPointerTy());
5103     return LowerToTLSGeneralDynamicModel32(GA, DAG, getPointerTy());
5104
5105   case TLSModel::InitialExec:
5106   case TLSModel::LocalExec:
5107     return LowerToTLSExecModel(GA, DAG, getPointerTy(), model,
5108                                Subtarget->is64Bit());
5109   }
5110
5111   llvm_unreachable("Unreachable");
5112   return SDValue();
5113 }
5114
5115
5116 /// LowerShift - Lower SRA_PARTS and friends, which return two i32 values and
5117 /// take a 2 x i32 value to shift plus a shift amount.
5118 SDValue X86TargetLowering::LowerShift(SDValue Op, SelectionDAG &DAG) {
5119   assert(Op.getNumOperands() == 3 && "Not a double-shift!");
5120   EVT VT = Op.getValueType();
5121   unsigned VTBits = VT.getSizeInBits();
5122   DebugLoc dl = Op.getDebugLoc();
5123   bool isSRA = Op.getOpcode() == ISD::SRA_PARTS;
5124   SDValue ShOpLo = Op.getOperand(0);
5125   SDValue ShOpHi = Op.getOperand(1);
5126   SDValue ShAmt  = Op.getOperand(2);
5127   SDValue Tmp1 = isSRA ? DAG.getNode(ISD::SRA, dl, VT, ShOpHi,
5128                                      DAG.getConstant(VTBits - 1, MVT::i8))
5129                        : DAG.getConstant(0, VT);
5130
5131   SDValue Tmp2, Tmp3;
5132   if (Op.getOpcode() == ISD::SHL_PARTS) {
5133     Tmp2 = DAG.getNode(X86ISD::SHLD, dl, VT, ShOpHi, ShOpLo, ShAmt);
5134     Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ShAmt);
5135   } else {
5136     Tmp2 = DAG.getNode(X86ISD::SHRD, dl, VT, ShOpLo, ShOpHi, ShAmt);
5137     Tmp3 = DAG.getNode(isSRA ? ISD::SRA : ISD::SRL, dl, VT, ShOpHi, ShAmt);
5138   }
5139
5140   SDValue AndNode = DAG.getNode(ISD::AND, dl, MVT::i8, ShAmt,
5141                                 DAG.getConstant(VTBits, MVT::i8));
5142   SDValue Cond = DAG.getNode(X86ISD::CMP, dl, VT,
5143                              AndNode, DAG.getConstant(0, MVT::i8));
5144
5145   SDValue Hi, Lo;
5146   SDValue CC = DAG.getConstant(X86::COND_NE, MVT::i8);
5147   SDValue Ops0[4] = { Tmp2, Tmp3, CC, Cond };
5148   SDValue Ops1[4] = { Tmp3, Tmp1, CC, Cond };
5149
5150   if (Op.getOpcode() == ISD::SHL_PARTS) {
5151     Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0, 4);
5152     Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1, 4);
5153   } else {
5154     Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0, 4);
5155     Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1, 4);
5156   }
5157
5158   SDValue Ops[2] = { Lo, Hi };
5159   return DAG.getMergeValues(Ops, 2, dl);
5160 }
5161
5162 SDValue X86TargetLowering::LowerSINT_TO_FP(SDValue Op, SelectionDAG &DAG) {
5163   EVT SrcVT = Op.getOperand(0).getValueType();
5164
5165   if (SrcVT.isVector()) {
5166     if (SrcVT == MVT::v2i32 && Op.getValueType() == MVT::v2f64) {
5167       return Op;
5168     }
5169     return SDValue();
5170   }
5171
5172   assert(SrcVT.getSimpleVT() <= MVT::i64 && SrcVT.getSimpleVT() >= MVT::i16 &&
5173          "Unknown SINT_TO_FP to lower!");
5174
5175   // These are really Legal; return the operand so the caller accepts it as
5176   // Legal.
5177   if (SrcVT == MVT::i32 && isScalarFPTypeInSSEReg(Op.getValueType()))
5178     return Op;
5179   if (SrcVT == MVT::i64 && isScalarFPTypeInSSEReg(Op.getValueType()) &&
5180       Subtarget->is64Bit()) {
5181     return Op;
5182   }
5183
5184   DebugLoc dl = Op.getDebugLoc();
5185   unsigned Size = SrcVT.getSizeInBits()/8;
5186   MachineFunction &MF = DAG.getMachineFunction();
5187   int SSFI = MF.getFrameInfo()->CreateStackObject(Size, Size, false);
5188   SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
5189   SDValue Chain = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
5190                                StackSlot,
5191                                PseudoSourceValue::getFixedStack(SSFI), 0);
5192   return BuildFILD(Op, SrcVT, Chain, StackSlot, DAG);
5193 }
5194
5195 SDValue X86TargetLowering::BuildFILD(SDValue Op, EVT SrcVT, SDValue Chain,
5196                                      SDValue StackSlot,
5197                                      SelectionDAG &DAG) {
5198   // Build the FILD
5199   DebugLoc dl = Op.getDebugLoc();
5200   SDVTList Tys;
5201   bool useSSE = isScalarFPTypeInSSEReg(Op.getValueType());
5202   if (useSSE)
5203     Tys = DAG.getVTList(MVT::f64, MVT::Other, MVT::Flag);
5204   else
5205     Tys = DAG.getVTList(Op.getValueType(), MVT::Other);
5206   SDValue Ops[] = { Chain, StackSlot, DAG.getValueType(SrcVT) };
5207   SDValue Result = DAG.getNode(useSSE ? X86ISD::FILD_FLAG : X86ISD::FILD, dl,
5208                                Tys, Ops, array_lengthof(Ops));
5209
5210   if (useSSE) {
5211     Chain = Result.getValue(1);
5212     SDValue InFlag = Result.getValue(2);
5213
5214     // FIXME: Currently the FST is flagged to the FILD_FLAG. This
5215     // shouldn't be necessary except that RFP cannot be live across
5216     // multiple blocks. When stackifier is fixed, they can be uncoupled.
5217     MachineFunction &MF = DAG.getMachineFunction();
5218     int SSFI = MF.getFrameInfo()->CreateStackObject(8, 8, false);
5219     SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
5220     Tys = DAG.getVTList(MVT::Other);
5221     SDValue Ops[] = {
5222       Chain, Result, StackSlot, DAG.getValueType(Op.getValueType()), InFlag
5223     };
5224     Chain = DAG.getNode(X86ISD::FST, dl, Tys, Ops, array_lengthof(Ops));
5225     Result = DAG.getLoad(Op.getValueType(), dl, Chain, StackSlot,
5226                          PseudoSourceValue::getFixedStack(SSFI), 0);
5227   }
5228
5229   return Result;
5230 }
5231
5232 // LowerUINT_TO_FP_i64 - 64-bit unsigned integer to double expansion.
5233 SDValue X86TargetLowering::LowerUINT_TO_FP_i64(SDValue Op, SelectionDAG &DAG) {
5234   // This algorithm is not obvious. Here it is in C code, more or less:
5235   /*
5236     double uint64_to_double( uint32_t hi, uint32_t lo ) {
5237       static const __m128i exp = { 0x4330000045300000ULL, 0 };
5238       static const __m128d bias = { 0x1.0p84, 0x1.0p52 };
5239
5240       // Copy ints to xmm registers.
5241       __m128i xh = _mm_cvtsi32_si128( hi );
5242       __m128i xl = _mm_cvtsi32_si128( lo );
5243
5244       // Combine into low half of a single xmm register.
5245       __m128i x = _mm_unpacklo_epi32( xh, xl );
5246       __m128d d;
5247       double sd;
5248
5249       // Merge in appropriate exponents to give the integer bits the right
5250       // magnitude.
5251       x = _mm_unpacklo_epi32( x, exp );
5252
5253       // Subtract away the biases to deal with the IEEE-754 double precision
5254       // implicit 1.
5255       d = _mm_sub_pd( (__m128d) x, bias );
5256
5257       // All conversions up to here are exact. The correctly rounded result is
5258       // calculated using the current rounding mode using the following
5259       // horizontal add.
5260       d = _mm_add_sd( d, _mm_unpackhi_pd( d, d ) );
5261       _mm_store_sd( &sd, d );   // Because we are returning doubles in XMM, this
5262                                 // store doesn't really need to be here (except
5263                                 // maybe to zero the other double)
5264       return sd;
5265     }
5266   */
5267
5268   DebugLoc dl = Op.getDebugLoc();
5269   LLVMContext *Context = DAG.getContext();
5270
5271   // Build some magic constants.
5272   std::vector<Constant*> CV0;
5273   CV0.push_back(ConstantInt::get(*Context, APInt(32, 0x45300000)));
5274   CV0.push_back(ConstantInt::get(*Context, APInt(32, 0x43300000)));
5275   CV0.push_back(ConstantInt::get(*Context, APInt(32, 0)));
5276   CV0.push_back(ConstantInt::get(*Context, APInt(32, 0)));
5277   Constant *C0 = ConstantVector::get(CV0);
5278   SDValue CPIdx0 = DAG.getConstantPool(C0, getPointerTy(), 16);
5279
5280   std::vector<Constant*> CV1;
5281   CV1.push_back(
5282     ConstantFP::get(*Context, APFloat(APInt(64, 0x4530000000000000ULL))));
5283   CV1.push_back(
5284     ConstantFP::get(*Context, APFloat(APInt(64, 0x4330000000000000ULL))));
5285   Constant *C1 = ConstantVector::get(CV1);
5286   SDValue CPIdx1 = DAG.getConstantPool(C1, getPointerTy(), 16);
5287
5288   SDValue XR1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
5289                             DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
5290                                         Op.getOperand(0),
5291                                         DAG.getIntPtrConstant(1)));
5292   SDValue XR2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
5293                             DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
5294                                         Op.getOperand(0),
5295                                         DAG.getIntPtrConstant(0)));
5296   SDValue Unpck1 = getUnpackl(DAG, dl, MVT::v4i32, XR1, XR2);
5297   SDValue CLod0 = DAG.getLoad(MVT::v4i32, dl, DAG.getEntryNode(), CPIdx0,
5298                               PseudoSourceValue::getConstantPool(), 0,
5299                               false, 16);
5300   SDValue Unpck2 = getUnpackl(DAG, dl, MVT::v4i32, Unpck1, CLod0);
5301   SDValue XR2F = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v2f64, Unpck2);
5302   SDValue CLod1 = DAG.getLoad(MVT::v2f64, dl, CLod0.getValue(1), CPIdx1,
5303                               PseudoSourceValue::getConstantPool(), 0,
5304                               false, 16);
5305   SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, XR2F, CLod1);
5306
5307   // Add the halves; easiest way is to swap them into another reg first.
5308   int ShufMask[2] = { 1, -1 };
5309   SDValue Shuf = DAG.getVectorShuffle(MVT::v2f64, dl, Sub,
5310                                       DAG.getUNDEF(MVT::v2f64), ShufMask);
5311   SDValue Add = DAG.getNode(ISD::FADD, dl, MVT::v2f64, Shuf, Sub);
5312   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Add,
5313                      DAG.getIntPtrConstant(0));
5314 }
5315
5316 // LowerUINT_TO_FP_i32 - 32-bit unsigned integer to float expansion.
5317 SDValue X86TargetLowering::LowerUINT_TO_FP_i32(SDValue Op, SelectionDAG &DAG) {
5318   DebugLoc dl = Op.getDebugLoc();
5319   // FP constant to bias correct the final result.
5320   SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL),
5321                                    MVT::f64);
5322
5323   // Load the 32-bit value into an XMM register.
5324   SDValue Load = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
5325                              DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
5326                                          Op.getOperand(0),
5327                                          DAG.getIntPtrConstant(0)));
5328
5329   Load = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
5330                      DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v2f64, Load),
5331                      DAG.getIntPtrConstant(0));
5332
5333   // Or the load with the bias.
5334   SDValue Or = DAG.getNode(ISD::OR, dl, MVT::v2i64,
5335                            DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v2i64,
5336                                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
5337                                                    MVT::v2f64, Load)),
5338                            DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v2i64,
5339                                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
5340                                                    MVT::v2f64, Bias)));
5341   Or = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
5342                    DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v2f64, Or),
5343                    DAG.getIntPtrConstant(0));
5344
5345   // Subtract the bias.
5346   SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::f64, Or, Bias);
5347
5348   // Handle final rounding.
5349   EVT DestVT = Op.getValueType();
5350
5351   if (DestVT.bitsLT(MVT::f64)) {
5352     return DAG.getNode(ISD::FP_ROUND, dl, DestVT, Sub,
5353                        DAG.getIntPtrConstant(0));
5354   } else if (DestVT.bitsGT(MVT::f64)) {
5355     return DAG.getNode(ISD::FP_EXTEND, dl, DestVT, Sub);
5356   }
5357
5358   // Handle final rounding.
5359   return Sub;
5360 }
5361
5362 SDValue X86TargetLowering::LowerUINT_TO_FP(SDValue Op, SelectionDAG &DAG) {
5363   SDValue N0 = Op.getOperand(0);
5364   DebugLoc dl = Op.getDebugLoc();
5365
5366   // Now not UINT_TO_FP is legal (it's marked custom), dag combiner won't
5367   // optimize it to a SINT_TO_FP when the sign bit is known zero. Perform
5368   // the optimization here.
5369   if (DAG.SignBitIsZero(N0))
5370     return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(), N0);
5371
5372   EVT SrcVT = N0.getValueType();
5373   if (SrcVT == MVT::i64) {
5374     // We only handle SSE2 f64 target here; caller can expand the rest.
5375     if (Op.getValueType() != MVT::f64 || !X86ScalarSSEf64)
5376       return SDValue();
5377
5378     return LowerUINT_TO_FP_i64(Op, DAG);
5379   } else if (SrcVT == MVT::i32 && X86ScalarSSEf64) {
5380     return LowerUINT_TO_FP_i32(Op, DAG);
5381   }
5382
5383   assert(SrcVT == MVT::i32 && "Unknown UINT_TO_FP to lower!");
5384
5385   // Make a 64-bit buffer, and use it to build an FILD.
5386   SDValue StackSlot = DAG.CreateStackTemporary(MVT::i64);
5387   SDValue WordOff = DAG.getConstant(4, getPointerTy());
5388   SDValue OffsetSlot = DAG.getNode(ISD::ADD, dl,
5389                                    getPointerTy(), StackSlot, WordOff);
5390   SDValue Store1 = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
5391                                 StackSlot, NULL, 0);
5392   SDValue Store2 = DAG.getStore(Store1, dl, DAG.getConstant(0, MVT::i32),
5393                                 OffsetSlot, NULL, 0);
5394   return BuildFILD(Op, MVT::i64, Store2, StackSlot, DAG);
5395 }
5396
5397 std::pair<SDValue,SDValue> X86TargetLowering::
5398 FP_TO_INTHelper(SDValue Op, SelectionDAG &DAG, bool IsSigned) {
5399   DebugLoc dl = Op.getDebugLoc();
5400
5401   EVT DstTy = Op.getValueType();
5402
5403   if (!IsSigned) {
5404     assert(DstTy == MVT::i32 && "Unexpected FP_TO_UINT");
5405     DstTy = MVT::i64;
5406   }
5407
5408   assert(DstTy.getSimpleVT() <= MVT::i64 &&
5409          DstTy.getSimpleVT() >= MVT::i16 &&
5410          "Unknown FP_TO_SINT to lower!");
5411
5412   // These are really Legal.
5413   if (DstTy == MVT::i32 &&
5414       isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
5415     return std::make_pair(SDValue(), SDValue());
5416   if (Subtarget->is64Bit() &&
5417       DstTy == MVT::i64 &&
5418       isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
5419     return std::make_pair(SDValue(), SDValue());
5420
5421   // We lower FP->sint64 into FISTP64, followed by a load, all to a temporary
5422   // stack slot.
5423   MachineFunction &MF = DAG.getMachineFunction();
5424   unsigned MemSize = DstTy.getSizeInBits()/8;
5425   int SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
5426   SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
5427
5428   unsigned Opc;
5429   switch (DstTy.getSimpleVT().SimpleTy) {
5430   default: llvm_unreachable("Invalid FP_TO_SINT to lower!");
5431   case MVT::i16: Opc = X86ISD::FP_TO_INT16_IN_MEM; break;
5432   case MVT::i32: Opc = X86ISD::FP_TO_INT32_IN_MEM; break;
5433   case MVT::i64: Opc = X86ISD::FP_TO_INT64_IN_MEM; break;
5434   }
5435
5436   SDValue Chain = DAG.getEntryNode();
5437   SDValue Value = Op.getOperand(0);
5438   if (isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType())) {
5439     assert(DstTy == MVT::i64 && "Invalid FP_TO_SINT to lower!");
5440     Chain = DAG.getStore(Chain, dl, Value, StackSlot,
5441                          PseudoSourceValue::getFixedStack(SSFI), 0);
5442     SDVTList Tys = DAG.getVTList(Op.getOperand(0).getValueType(), MVT::Other);
5443     SDValue Ops[] = {
5444       Chain, StackSlot, DAG.getValueType(Op.getOperand(0).getValueType())
5445     };
5446     Value = DAG.getNode(X86ISD::FLD, dl, Tys, Ops, 3);
5447     Chain = Value.getValue(1);
5448     SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
5449     StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
5450   }
5451
5452   // Build the FP_TO_INT*_IN_MEM
5453   SDValue Ops[] = { Chain, Value, StackSlot };
5454   SDValue FIST = DAG.getNode(Opc, dl, MVT::Other, Ops, 3);
5455
5456   return std::make_pair(FIST, StackSlot);
5457 }
5458
5459 SDValue X86TargetLowering::LowerFP_TO_SINT(SDValue Op, SelectionDAG &DAG) {
5460   if (Op.getValueType().isVector()) {
5461     if (Op.getValueType() == MVT::v2i32 &&
5462         Op.getOperand(0).getValueType() == MVT::v2f64) {
5463       return Op;
5464     }
5465     return SDValue();
5466   }
5467
5468   std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG, true);
5469   SDValue FIST = Vals.first, StackSlot = Vals.second;
5470   // If FP_TO_INTHelper failed, the node is actually supposed to be Legal.
5471   if (FIST.getNode() == 0) return Op;
5472
5473   // Load the result.
5474   return DAG.getLoad(Op.getValueType(), Op.getDebugLoc(),
5475                      FIST, StackSlot, NULL, 0);
5476 }
5477
5478 SDValue X86TargetLowering::LowerFP_TO_UINT(SDValue Op, SelectionDAG &DAG) {
5479   std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG, false);
5480   SDValue FIST = Vals.first, StackSlot = Vals.second;
5481   assert(FIST.getNode() && "Unexpected failure");
5482
5483   // Load the result.
5484   return DAG.getLoad(Op.getValueType(), Op.getDebugLoc(),
5485                      FIST, StackSlot, NULL, 0);
5486 }
5487
5488 SDValue X86TargetLowering::LowerFABS(SDValue Op, SelectionDAG &DAG) {
5489   LLVMContext *Context = DAG.getContext();
5490   DebugLoc dl = Op.getDebugLoc();
5491   EVT VT = Op.getValueType();
5492   EVT EltVT = VT;
5493   if (VT.isVector())
5494     EltVT = VT.getVectorElementType();
5495   std::vector<Constant*> CV;
5496   if (EltVT == MVT::f64) {
5497     Constant *C = ConstantFP::get(*Context, APFloat(APInt(64, ~(1ULL << 63))));
5498     CV.push_back(C);
5499     CV.push_back(C);
5500   } else {
5501     Constant *C = ConstantFP::get(*Context, APFloat(APInt(32, ~(1U << 31))));
5502     CV.push_back(C);
5503     CV.push_back(C);
5504     CV.push_back(C);
5505     CV.push_back(C);
5506   }
5507   Constant *C = ConstantVector::get(CV);
5508   SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
5509   SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
5510                                PseudoSourceValue::getConstantPool(), 0,
5511                                false, 16);
5512   return DAG.getNode(X86ISD::FAND, dl, VT, Op.getOperand(0), Mask);
5513 }
5514
5515 SDValue X86TargetLowering::LowerFNEG(SDValue Op, SelectionDAG &DAG) {
5516   LLVMContext *Context = DAG.getContext();
5517   DebugLoc dl = Op.getDebugLoc();
5518   EVT VT = Op.getValueType();
5519   EVT EltVT = VT;
5520   if (VT.isVector())
5521     EltVT = VT.getVectorElementType();
5522   std::vector<Constant*> CV;
5523   if (EltVT == MVT::f64) {
5524     Constant *C = ConstantFP::get(*Context, APFloat(APInt(64, 1ULL << 63)));
5525     CV.push_back(C);
5526     CV.push_back(C);
5527   } else {
5528     Constant *C = ConstantFP::get(*Context, APFloat(APInt(32, 1U << 31)));
5529     CV.push_back(C);
5530     CV.push_back(C);
5531     CV.push_back(C);
5532     CV.push_back(C);
5533   }
5534   Constant *C = ConstantVector::get(CV);
5535   SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
5536   SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
5537                                PseudoSourceValue::getConstantPool(), 0,
5538                                false, 16);
5539   if (VT.isVector()) {
5540     return DAG.getNode(ISD::BIT_CONVERT, dl, VT,
5541                        DAG.getNode(ISD::XOR, dl, MVT::v2i64,
5542                     DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v2i64,
5543                                 Op.getOperand(0)),
5544                     DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v2i64, Mask)));
5545   } else {
5546     return DAG.getNode(X86ISD::FXOR, dl, VT, Op.getOperand(0), Mask);
5547   }
5548 }
5549
5550 SDValue X86TargetLowering::LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) {
5551   LLVMContext *Context = DAG.getContext();
5552   SDValue Op0 = Op.getOperand(0);
5553   SDValue Op1 = Op.getOperand(1);
5554   DebugLoc dl = Op.getDebugLoc();
5555   EVT VT = Op.getValueType();
5556   EVT SrcVT = Op1.getValueType();
5557
5558   // If second operand is smaller, extend it first.
5559   if (SrcVT.bitsLT(VT)) {
5560     Op1 = DAG.getNode(ISD::FP_EXTEND, dl, VT, Op1);
5561     SrcVT = VT;
5562   }
5563   // And if it is bigger, shrink it first.
5564   if (SrcVT.bitsGT(VT)) {
5565     Op1 = DAG.getNode(ISD::FP_ROUND, dl, VT, Op1, DAG.getIntPtrConstant(1));
5566     SrcVT = VT;
5567   }
5568
5569   // At this point the operands and the result should have the same
5570   // type, and that won't be f80 since that is not custom lowered.
5571
5572   // First get the sign bit of second operand.
5573   std::vector<Constant*> CV;
5574   if (SrcVT == MVT::f64) {
5575     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, 1ULL << 63))));
5576     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, 0))));
5577   } else {
5578     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 1U << 31))));
5579     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
5580     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
5581     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
5582   }
5583   Constant *C = ConstantVector::get(CV);
5584   SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
5585   SDValue Mask1 = DAG.getLoad(SrcVT, dl, DAG.getEntryNode(), CPIdx,
5586                                 PseudoSourceValue::getConstantPool(), 0,
5587                                 false, 16);
5588   SDValue SignBit = DAG.getNode(X86ISD::FAND, dl, SrcVT, Op1, Mask1);
5589
5590   // Shift sign bit right or left if the two operands have different types.
5591   if (SrcVT.bitsGT(VT)) {
5592     // Op0 is MVT::f32, Op1 is MVT::f64.
5593     SignBit = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f64, SignBit);
5594     SignBit = DAG.getNode(X86ISD::FSRL, dl, MVT::v2f64, SignBit,
5595                           DAG.getConstant(32, MVT::i32));
5596     SignBit = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v4f32, SignBit);
5597     SignBit = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f32, SignBit,
5598                           DAG.getIntPtrConstant(0));
5599   }
5600
5601   // Clear first operand sign bit.
5602   CV.clear();
5603   if (VT == MVT::f64) {
5604     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, ~(1ULL << 63)))));
5605     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, 0))));
5606   } else {
5607     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, ~(1U << 31)))));
5608     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
5609     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
5610     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
5611   }
5612   C = ConstantVector::get(CV);
5613   CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
5614   SDValue Mask2 = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
5615                                 PseudoSourceValue::getConstantPool(), 0,
5616                                 false, 16);
5617   SDValue Val = DAG.getNode(X86ISD::FAND, dl, VT, Op0, Mask2);
5618
5619   // Or the value with the sign bit.
5620   return DAG.getNode(X86ISD::FOR, dl, VT, Val, SignBit);
5621 }
5622
5623 /// Emit nodes that will be selected as "test Op0,Op0", or something
5624 /// equivalent.
5625 SDValue X86TargetLowering::EmitTest(SDValue Op, unsigned X86CC,
5626                                     SelectionDAG &DAG) {
5627   DebugLoc dl = Op.getDebugLoc();
5628
5629   // CF and OF aren't always set the way we want. Determine which
5630   // of these we need.
5631   bool NeedCF = false;
5632   bool NeedOF = false;
5633   switch (X86CC) {
5634   case X86::COND_A: case X86::COND_AE:
5635   case X86::COND_B: case X86::COND_BE:
5636     NeedCF = true;
5637     break;
5638   case X86::COND_G: case X86::COND_GE:
5639   case X86::COND_L: case X86::COND_LE:
5640   case X86::COND_O: case X86::COND_NO:
5641     NeedOF = true;
5642     break;
5643   default: break;
5644   }
5645
5646   // See if we can use the EFLAGS value from the operand instead of
5647   // doing a separate TEST. TEST always sets OF and CF to 0, so unless
5648   // we prove that the arithmetic won't overflow, we can't use OF or CF.
5649   if (Op.getResNo() == 0 && !NeedOF && !NeedCF) {
5650     unsigned Opcode = 0;
5651     unsigned NumOperands = 0;
5652     switch (Op.getNode()->getOpcode()) {
5653     case ISD::ADD:
5654       // Due to an isel shortcoming, be conservative if this add is likely to
5655       // be selected as part of a load-modify-store instruction. When the root
5656       // node in a match is a store, isel doesn't know how to remap non-chain
5657       // non-flag uses of other nodes in the match, such as the ADD in this
5658       // case. This leads to the ADD being left around and reselected, with
5659       // the result being two adds in the output.
5660       for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
5661            UE = Op.getNode()->use_end(); UI != UE; ++UI)
5662         if (UI->getOpcode() == ISD::STORE)
5663           goto default_case;
5664       if (ConstantSDNode *C =
5665             dyn_cast<ConstantSDNode>(Op.getNode()->getOperand(1))) {
5666         // An add of one will be selected as an INC.
5667         if (C->getAPIntValue() == 1) {
5668           Opcode = X86ISD::INC;
5669           NumOperands = 1;
5670           break;
5671         }
5672         // An add of negative one (subtract of one) will be selected as a DEC.
5673         if (C->getAPIntValue().isAllOnesValue()) {
5674           Opcode = X86ISD::DEC;
5675           NumOperands = 1;
5676           break;
5677         }
5678       }
5679       // Otherwise use a regular EFLAGS-setting add.
5680       Opcode = X86ISD::ADD;
5681       NumOperands = 2;
5682       break;
5683     case ISD::AND: {
5684       // If the primary and result isn't used, don't bother using X86ISD::AND,
5685       // because a TEST instruction will be better.
5686       bool NonFlagUse = false;
5687       for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
5688              UE = Op.getNode()->use_end(); UI != UE; ++UI) {
5689         SDNode *User = *UI;
5690         unsigned UOpNo = UI.getOperandNo();
5691         if (User->getOpcode() == ISD::TRUNCATE && User->hasOneUse()) {
5692           // Look pass truncate.
5693           UOpNo = User->use_begin().getOperandNo();
5694           User = *User->use_begin();
5695         }
5696         if (User->getOpcode() != ISD::BRCOND &&
5697             User->getOpcode() != ISD::SETCC &&
5698             (User->getOpcode() != ISD::SELECT || UOpNo != 0)) {
5699           NonFlagUse = true;
5700           break;
5701         }
5702       }
5703       if (!NonFlagUse)
5704         break;
5705     }
5706     // FALL THROUGH
5707     case ISD::SUB:
5708     case ISD::OR:
5709     case ISD::XOR:
5710       // Due to the ISEL shortcoming noted above, be conservative if this op is
5711       // likely to be selected as part of a load-modify-store instruction.
5712       for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
5713            UE = Op.getNode()->use_end(); UI != UE; ++UI)
5714         if (UI->getOpcode() == ISD::STORE)
5715           goto default_case;
5716       // Otherwise use a regular EFLAGS-setting instruction.
5717       switch (Op.getNode()->getOpcode()) {
5718       case ISD::SUB: Opcode = X86ISD::SUB; break;
5719       case ISD::OR:  Opcode = X86ISD::OR;  break;
5720       case ISD::XOR: Opcode = X86ISD::XOR; break;
5721       case ISD::AND: Opcode = X86ISD::AND; break;
5722       default: llvm_unreachable("unexpected operator!");
5723       }
5724       NumOperands = 2;
5725       break;
5726     case X86ISD::ADD:
5727     case X86ISD::SUB:
5728     case X86ISD::INC:
5729     case X86ISD::DEC:
5730     case X86ISD::OR:
5731     case X86ISD::XOR:
5732     case X86ISD::AND:
5733       return SDValue(Op.getNode(), 1);
5734     default:
5735     default_case:
5736       break;
5737     }
5738     if (Opcode != 0) {
5739       SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
5740       SmallVector<SDValue, 4> Ops;
5741       for (unsigned i = 0; i != NumOperands; ++i)
5742         Ops.push_back(Op.getOperand(i));
5743       SDValue New = DAG.getNode(Opcode, dl, VTs, &Ops[0], NumOperands);
5744       DAG.ReplaceAllUsesWith(Op, New);
5745       return SDValue(New.getNode(), 1);
5746     }
5747   }
5748
5749   // Otherwise just emit a CMP with 0, which is the TEST pattern.
5750   return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
5751                      DAG.getConstant(0, Op.getValueType()));
5752 }
5753
5754 /// Emit nodes that will be selected as "cmp Op0,Op1", or something
5755 /// equivalent.
5756 SDValue X86TargetLowering::EmitCmp(SDValue Op0, SDValue Op1, unsigned X86CC,
5757                                    SelectionDAG &DAG) {
5758   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op1))
5759     if (C->getAPIntValue() == 0)
5760       return EmitTest(Op0, X86CC, DAG);
5761
5762   DebugLoc dl = Op0.getDebugLoc();
5763   return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op0, Op1);
5764 }
5765
5766 /// LowerToBT - Result of 'and' is compared against zero. Turn it into a BT node
5767 /// if it's possible.
5768 static SDValue LowerToBT(SDValue Op0, ISD::CondCode CC,
5769                          DebugLoc dl, SelectionDAG &DAG) {
5770   SDValue LHS, RHS;
5771   if (Op0.getOperand(1).getOpcode() == ISD::SHL) {
5772     if (ConstantSDNode *Op010C =
5773         dyn_cast<ConstantSDNode>(Op0.getOperand(1).getOperand(0)))
5774       if (Op010C->getZExtValue() == 1) {
5775         LHS = Op0.getOperand(0);
5776         RHS = Op0.getOperand(1).getOperand(1);
5777       }
5778   } else if (Op0.getOperand(0).getOpcode() == ISD::SHL) {
5779     if (ConstantSDNode *Op000C =
5780         dyn_cast<ConstantSDNode>(Op0.getOperand(0).getOperand(0)))
5781       if (Op000C->getZExtValue() == 1) {
5782         LHS = Op0.getOperand(1);
5783         RHS = Op0.getOperand(0).getOperand(1);
5784       }
5785   } else if (Op0.getOperand(1).getOpcode() == ISD::Constant) {
5786     ConstantSDNode *AndRHS = cast<ConstantSDNode>(Op0.getOperand(1));
5787     SDValue AndLHS = Op0.getOperand(0);
5788     if (AndRHS->getZExtValue() == 1 && AndLHS.getOpcode() == ISD::SRL) {
5789       LHS = AndLHS.getOperand(0);
5790       RHS = AndLHS.getOperand(1);
5791     }
5792   }
5793
5794   if (LHS.getNode()) {
5795     // If LHS is i8, promote it to i16 with any_extend.  There is no i8 BT
5796     // instruction.  Since the shift amount is in-range-or-undefined, we know
5797     // that doing a bittest on the i16 value is ok.  We extend to i32 because
5798     // the encoding for the i16 version is larger than the i32 version.
5799     if (LHS.getValueType() == MVT::i8)
5800       LHS = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, LHS);
5801
5802     // If the operand types disagree, extend the shift amount to match.  Since
5803     // BT ignores high bits (like shifts) we can use anyextend.
5804     if (LHS.getValueType() != RHS.getValueType())
5805       RHS = DAG.getNode(ISD::ANY_EXTEND, dl, LHS.getValueType(), RHS);
5806
5807     SDValue BT = DAG.getNode(X86ISD::BT, dl, MVT::i32, LHS, RHS);
5808     unsigned Cond = CC == ISD::SETEQ ? X86::COND_AE : X86::COND_B;
5809     return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
5810                        DAG.getConstant(Cond, MVT::i8), BT);
5811   }
5812
5813   return SDValue();
5814 }
5815
5816 SDValue X86TargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) {
5817   assert(Op.getValueType() == MVT::i8 && "SetCC type must be 8-bit integer");
5818   SDValue Op0 = Op.getOperand(0);
5819   SDValue Op1 = Op.getOperand(1);
5820   DebugLoc dl = Op.getDebugLoc();
5821   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
5822
5823   // Optimize to BT if possible.
5824   // Lower (X & (1 << N)) == 0 to BT(X, N).
5825   // Lower ((X >>u N) & 1) != 0 to BT(X, N).
5826   // Lower ((X >>s N) & 1) != 0 to BT(X, N).
5827   if (Op0.getOpcode() == ISD::AND &&
5828       Op0.hasOneUse() &&
5829       Op1.getOpcode() == ISD::Constant &&
5830       cast<ConstantSDNode>(Op1)->getZExtValue() == 0 &&
5831       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
5832     SDValue NewSetCC = LowerToBT(Op0, CC, dl, DAG);
5833     if (NewSetCC.getNode())
5834       return NewSetCC;
5835   }
5836
5837   bool isFP = Op.getOperand(1).getValueType().isFloatingPoint();
5838   unsigned X86CC = TranslateX86CC(CC, isFP, Op0, Op1, DAG);
5839   if (X86CC == X86::COND_INVALID)
5840     return SDValue();
5841
5842   SDValue Cond = EmitCmp(Op0, Op1, X86CC, DAG);
5843
5844   // Use sbb x, x to materialize carry bit into a GPR.
5845   if (X86CC == X86::COND_B)
5846     return DAG.getNode(ISD::AND, dl, MVT::i8,
5847                        DAG.getNode(X86ISD::SETCC_CARRY, dl, MVT::i8,
5848                                    DAG.getConstant(X86CC, MVT::i8), Cond),
5849                        DAG.getConstant(1, MVT::i8));
5850
5851   return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
5852                      DAG.getConstant(X86CC, MVT::i8), Cond);
5853 }
5854
5855 SDValue X86TargetLowering::LowerVSETCC(SDValue Op, SelectionDAG &DAG) {
5856   SDValue Cond;
5857   SDValue Op0 = Op.getOperand(0);
5858   SDValue Op1 = Op.getOperand(1);
5859   SDValue CC = Op.getOperand(2);
5860   EVT VT = Op.getValueType();
5861   ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
5862   bool isFP = Op.getOperand(1).getValueType().isFloatingPoint();
5863   DebugLoc dl = Op.getDebugLoc();
5864
5865   if (isFP) {
5866     unsigned SSECC = 8;
5867     EVT VT0 = Op0.getValueType();
5868     assert(VT0 == MVT::v4f32 || VT0 == MVT::v2f64);
5869     unsigned Opc = VT0 == MVT::v4f32 ? X86ISD::CMPPS : X86ISD::CMPPD;
5870     bool Swap = false;
5871
5872     switch (SetCCOpcode) {
5873     default: break;
5874     case ISD::SETOEQ:
5875     case ISD::SETEQ:  SSECC = 0; break;
5876     case ISD::SETOGT:
5877     case ISD::SETGT: Swap = true; // Fallthrough
5878     case ISD::SETLT:
5879     case ISD::SETOLT: SSECC = 1; break;
5880     case ISD::SETOGE:
5881     case ISD::SETGE: Swap = true; // Fallthrough
5882     case ISD::SETLE:
5883     case ISD::SETOLE: SSECC = 2; break;
5884     case ISD::SETUO:  SSECC = 3; break;
5885     case ISD::SETUNE:
5886     case ISD::SETNE:  SSECC = 4; break;
5887     case ISD::SETULE: Swap = true;
5888     case ISD::SETUGE: SSECC = 5; break;
5889     case ISD::SETULT: Swap = true;
5890     case ISD::SETUGT: SSECC = 6; break;
5891     case ISD::SETO:   SSECC = 7; break;
5892     }
5893     if (Swap)
5894       std::swap(Op0, Op1);
5895
5896     // In the two special cases we can't handle, emit two comparisons.
5897     if (SSECC == 8) {
5898       if (SetCCOpcode == ISD::SETUEQ) {
5899         SDValue UNORD, EQ;
5900         UNORD = DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(3, MVT::i8));
5901         EQ = DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(0, MVT::i8));
5902         return DAG.getNode(ISD::OR, dl, VT, UNORD, EQ);
5903       }
5904       else if (SetCCOpcode == ISD::SETONE) {
5905         SDValue ORD, NEQ;
5906         ORD = DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(7, MVT::i8));
5907         NEQ = DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(4, MVT::i8));
5908         return DAG.getNode(ISD::AND, dl, VT, ORD, NEQ);
5909       }
5910       llvm_unreachable("Illegal FP comparison");
5911     }
5912     // Handle all other FP comparisons here.
5913     return DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(SSECC, MVT::i8));
5914   }
5915
5916   // We are handling one of the integer comparisons here.  Since SSE only has
5917   // GT and EQ comparisons for integer, swapping operands and multiple
5918   // operations may be required for some comparisons.
5919   unsigned Opc = 0, EQOpc = 0, GTOpc = 0;
5920   bool Swap = false, Invert = false, FlipSigns = false;
5921
5922   switch (VT.getSimpleVT().SimpleTy) {
5923   default: break;
5924   case MVT::v8i8:
5925   case MVT::v16i8: EQOpc = X86ISD::PCMPEQB; GTOpc = X86ISD::PCMPGTB; break;
5926   case MVT::v4i16:
5927   case MVT::v8i16: EQOpc = X86ISD::PCMPEQW; GTOpc = X86ISD::PCMPGTW; break;
5928   case MVT::v2i32:
5929   case MVT::v4i32: EQOpc = X86ISD::PCMPEQD; GTOpc = X86ISD::PCMPGTD; break;
5930   case MVT::v2i64: EQOpc = X86ISD::PCMPEQQ; GTOpc = X86ISD::PCMPGTQ; break;
5931   }
5932
5933   switch (SetCCOpcode) {
5934   default: break;
5935   case ISD::SETNE:  Invert = true;
5936   case ISD::SETEQ:  Opc = EQOpc; break;
5937   case ISD::SETLT:  Swap = true;
5938   case ISD::SETGT:  Opc = GTOpc; break;
5939   case ISD::SETGE:  Swap = true;
5940   case ISD::SETLE:  Opc = GTOpc; Invert = true; break;
5941   case ISD::SETULT: Swap = true;
5942   case ISD::SETUGT: Opc = GTOpc; FlipSigns = true; break;
5943   case ISD::SETUGE: Swap = true;
5944   case ISD::SETULE: Opc = GTOpc; FlipSigns = true; Invert = true; break;
5945   }
5946   if (Swap)
5947     std::swap(Op0, Op1);
5948
5949   // Since SSE has no unsigned integer comparisons, we need to flip  the sign
5950   // bits of the inputs before performing those operations.
5951   if (FlipSigns) {
5952     EVT EltVT = VT.getVectorElementType();
5953     SDValue SignBit = DAG.getConstant(APInt::getSignBit(EltVT.getSizeInBits()),
5954                                       EltVT);
5955     std::vector<SDValue> SignBits(VT.getVectorNumElements(), SignBit);
5956     SDValue SignVec = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &SignBits[0],
5957                                     SignBits.size());
5958     Op0 = DAG.getNode(ISD::XOR, dl, VT, Op0, SignVec);
5959     Op1 = DAG.getNode(ISD::XOR, dl, VT, Op1, SignVec);
5960   }
5961
5962   SDValue Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
5963
5964   // If the logical-not of the result is required, perform that now.
5965   if (Invert)
5966     Result = DAG.getNOT(dl, Result, VT);
5967
5968   return Result;
5969 }
5970
5971 // isX86LogicalCmp - Return true if opcode is a X86 logical comparison.
5972 static bool isX86LogicalCmp(SDValue Op) {
5973   unsigned Opc = Op.getNode()->getOpcode();
5974   if (Opc == X86ISD::CMP || Opc == X86ISD::COMI || Opc == X86ISD::UCOMI)
5975     return true;
5976   if (Op.getResNo() == 1 &&
5977       (Opc == X86ISD::ADD ||
5978        Opc == X86ISD::SUB ||
5979        Opc == X86ISD::SMUL ||
5980        Opc == X86ISD::UMUL ||
5981        Opc == X86ISD::INC ||
5982        Opc == X86ISD::DEC ||
5983        Opc == X86ISD::OR ||
5984        Opc == X86ISD::XOR ||
5985        Opc == X86ISD::AND))
5986     return true;
5987
5988   return false;
5989 }
5990
5991 SDValue X86TargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) {
5992   bool addTest = true;
5993   SDValue Cond  = Op.getOperand(0);
5994   DebugLoc dl = Op.getDebugLoc();
5995   SDValue CC;
5996
5997   if (Cond.getOpcode() == ISD::SETCC) {
5998     SDValue NewCond = LowerSETCC(Cond, DAG);
5999     if (NewCond.getNode())
6000       Cond = NewCond;
6001   }
6002
6003   // (select (x == 0), -1, 0) -> (sign_bit (x - 1))
6004   SDValue Op1 = Op.getOperand(1);
6005   SDValue Op2 = Op.getOperand(2);
6006   if (Cond.getOpcode() == X86ISD::SETCC &&
6007       cast<ConstantSDNode>(Cond.getOperand(0))->getZExtValue() == X86::COND_E) {
6008     SDValue Cmp = Cond.getOperand(1);
6009     if (Cmp.getOpcode() == X86ISD::CMP) {
6010       ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(Op1);
6011       ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(Op2);
6012       ConstantSDNode *RHSC =
6013         dyn_cast<ConstantSDNode>(Cmp.getOperand(1).getNode());
6014       if (N1C && N1C->isAllOnesValue() &&
6015           N2C && N2C->isNullValue() &&
6016           RHSC && RHSC->isNullValue()) {
6017         SDValue CmpOp0 = Cmp.getOperand(0);
6018         Cmp = DAG.getNode(X86ISD::CMP, dl, Op.getValueType(),
6019                           CmpOp0, DAG.getConstant(1, CmpOp0.getValueType()));
6020         return DAG.getNode(X86ISD::SETCC_CARRY, dl, Op.getValueType(),
6021                            DAG.getConstant(X86::COND_B, MVT::i8), Cmp);
6022       }
6023     }
6024   }
6025
6026   // Look pass (and (setcc_carry (cmp ...)), 1).
6027   if (Cond.getOpcode() == ISD::AND &&
6028       Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
6029     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
6030     if (C && C->getAPIntValue() == 1) 
6031       Cond = Cond.getOperand(0);
6032   }
6033
6034   // If condition flag is set by a X86ISD::CMP, then use it as the condition
6035   // setting operand in place of the X86ISD::SETCC.
6036   if (Cond.getOpcode() == X86ISD::SETCC ||
6037       Cond.getOpcode() == X86ISD::SETCC_CARRY) {
6038     CC = Cond.getOperand(0);
6039
6040     SDValue Cmp = Cond.getOperand(1);
6041     unsigned Opc = Cmp.getOpcode();
6042     EVT VT = Op.getValueType();
6043
6044     bool IllegalFPCMov = false;
6045     if (VT.isFloatingPoint() && !VT.isVector() &&
6046         !isScalarFPTypeInSSEReg(VT))  // FPStack?
6047       IllegalFPCMov = !hasFPCMov(cast<ConstantSDNode>(CC)->getSExtValue());
6048
6049     if ((isX86LogicalCmp(Cmp) && !IllegalFPCMov) ||
6050         Opc == X86ISD::BT) { // FIXME
6051       Cond = Cmp;
6052       addTest = false;
6053     }
6054   }
6055
6056   if (addTest) {
6057     // Look pass the truncate.
6058     if (Cond.getOpcode() == ISD::TRUNCATE)
6059       Cond = Cond.getOperand(0);
6060
6061     // We know the result of AND is compared against zero. Try to match
6062     // it to BT.
6063     if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) { 
6064       SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, dl, DAG);
6065       if (NewSetCC.getNode()) {
6066         CC = NewSetCC.getOperand(0);
6067         Cond = NewSetCC.getOperand(1);
6068         addTest = false;
6069       }
6070     }
6071   }
6072
6073   if (addTest) {
6074     CC = DAG.getConstant(X86::COND_NE, MVT::i8);
6075     Cond = EmitTest(Cond, X86::COND_NE, DAG);
6076   }
6077
6078   // X86ISD::CMOV means set the result (which is operand 1) to the RHS if
6079   // condition is true.
6080   SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::Flag);
6081   SDValue Ops[] = { Op2, Op1, CC, Cond };
6082   return DAG.getNode(X86ISD::CMOV, dl, VTs, Ops, array_lengthof(Ops));
6083 }
6084
6085 // isAndOrOfSingleUseSetCCs - Return true if node is an ISD::AND or
6086 // ISD::OR of two X86ISD::SETCC nodes each of which has no other use apart
6087 // from the AND / OR.
6088 static bool isAndOrOfSetCCs(SDValue Op, unsigned &Opc) {
6089   Opc = Op.getOpcode();
6090   if (Opc != ISD::OR && Opc != ISD::AND)
6091     return false;
6092   return (Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
6093           Op.getOperand(0).hasOneUse() &&
6094           Op.getOperand(1).getOpcode() == X86ISD::SETCC &&
6095           Op.getOperand(1).hasOneUse());
6096 }
6097
6098 // isXor1OfSetCC - Return true if node is an ISD::XOR of a X86ISD::SETCC and
6099 // 1 and that the SETCC node has a single use.
6100 static bool isXor1OfSetCC(SDValue Op) {
6101   if (Op.getOpcode() != ISD::XOR)
6102     return false;
6103   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
6104   if (N1C && N1C->getAPIntValue() == 1) {
6105     return Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
6106       Op.getOperand(0).hasOneUse();
6107   }
6108   return false;
6109 }
6110
6111 SDValue X86TargetLowering::LowerBRCOND(SDValue Op, SelectionDAG &DAG) {
6112   bool addTest = true;
6113   SDValue Chain = Op.getOperand(0);
6114   SDValue Cond  = Op.getOperand(1);
6115   SDValue Dest  = Op.getOperand(2);
6116   DebugLoc dl = Op.getDebugLoc();
6117   SDValue CC;
6118
6119   if (Cond.getOpcode() == ISD::SETCC) {
6120     SDValue NewCond = LowerSETCC(Cond, DAG);
6121     if (NewCond.getNode())
6122       Cond = NewCond;
6123   }
6124 #if 0
6125   // FIXME: LowerXALUO doesn't handle these!!
6126   else if (Cond.getOpcode() == X86ISD::ADD  ||
6127            Cond.getOpcode() == X86ISD::SUB  ||
6128            Cond.getOpcode() == X86ISD::SMUL ||
6129            Cond.getOpcode() == X86ISD::UMUL)
6130     Cond = LowerXALUO(Cond, DAG);
6131 #endif
6132
6133   // Look pass (and (setcc_carry (cmp ...)), 1).
6134   if (Cond.getOpcode() == ISD::AND &&
6135       Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
6136     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
6137     if (C && C->getAPIntValue() == 1) 
6138       Cond = Cond.getOperand(0);
6139   }
6140
6141   // If condition flag is set by a X86ISD::CMP, then use it as the condition
6142   // setting operand in place of the X86ISD::SETCC.
6143   if (Cond.getOpcode() == X86ISD::SETCC ||
6144       Cond.getOpcode() == X86ISD::SETCC_CARRY) {
6145     CC = Cond.getOperand(0);
6146
6147     SDValue Cmp = Cond.getOperand(1);
6148     unsigned Opc = Cmp.getOpcode();
6149     // FIXME: WHY THE SPECIAL CASING OF LogicalCmp??
6150     if (isX86LogicalCmp(Cmp) || Opc == X86ISD::BT) {
6151       Cond = Cmp;
6152       addTest = false;
6153     } else {
6154       switch (cast<ConstantSDNode>(CC)->getZExtValue()) {
6155       default: break;
6156       case X86::COND_O:
6157       case X86::COND_B:
6158         // These can only come from an arithmetic instruction with overflow,
6159         // e.g. SADDO, UADDO.
6160         Cond = Cond.getNode()->getOperand(1);
6161         addTest = false;
6162         break;
6163       }
6164     }
6165   } else {
6166     unsigned CondOpc;
6167     if (Cond.hasOneUse() && isAndOrOfSetCCs(Cond, CondOpc)) {
6168       SDValue Cmp = Cond.getOperand(0).getOperand(1);
6169       if (CondOpc == ISD::OR) {
6170         // Also, recognize the pattern generated by an FCMP_UNE. We can emit
6171         // two branches instead of an explicit OR instruction with a
6172         // separate test.
6173         if (Cmp == Cond.getOperand(1).getOperand(1) &&
6174             isX86LogicalCmp(Cmp)) {
6175           CC = Cond.getOperand(0).getOperand(0);
6176           Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
6177                               Chain, Dest, CC, Cmp);
6178           CC = Cond.getOperand(1).getOperand(0);
6179           Cond = Cmp;
6180           addTest = false;
6181         }
6182       } else { // ISD::AND
6183         // Also, recognize the pattern generated by an FCMP_OEQ. We can emit
6184         // two branches instead of an explicit AND instruction with a
6185         // separate test. However, we only do this if this block doesn't
6186         // have a fall-through edge, because this requires an explicit
6187         // jmp when the condition is false.
6188         if (Cmp == Cond.getOperand(1).getOperand(1) &&
6189             isX86LogicalCmp(Cmp) &&
6190             Op.getNode()->hasOneUse()) {
6191           X86::CondCode CCode =
6192             (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
6193           CCode = X86::GetOppositeBranchCondition(CCode);
6194           CC = DAG.getConstant(CCode, MVT::i8);
6195           SDValue User = SDValue(*Op.getNode()->use_begin(), 0);
6196           // Look for an unconditional branch following this conditional branch.
6197           // We need this because we need to reverse the successors in order
6198           // to implement FCMP_OEQ.
6199           if (User.getOpcode() == ISD::BR) {
6200             SDValue FalseBB = User.getOperand(1);
6201             SDValue NewBR =
6202               DAG.UpdateNodeOperands(User, User.getOperand(0), Dest);
6203             assert(NewBR == User);
6204             Dest = FalseBB;
6205
6206             Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
6207                                 Chain, Dest, CC, Cmp);
6208             X86::CondCode CCode =
6209               (X86::CondCode)Cond.getOperand(1).getConstantOperandVal(0);
6210             CCode = X86::GetOppositeBranchCondition(CCode);
6211             CC = DAG.getConstant(CCode, MVT::i8);
6212             Cond = Cmp;
6213             addTest = false;
6214           }
6215         }
6216       }
6217     } else if (Cond.hasOneUse() && isXor1OfSetCC(Cond)) {
6218       // Recognize for xorb (setcc), 1 patterns. The xor inverts the condition.
6219       // It should be transformed during dag combiner except when the condition
6220       // is set by a arithmetics with overflow node.
6221       X86::CondCode CCode =
6222         (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
6223       CCode = X86::GetOppositeBranchCondition(CCode);
6224       CC = DAG.getConstant(CCode, MVT::i8);
6225       Cond = Cond.getOperand(0).getOperand(1);
6226       addTest = false;
6227     }
6228   }
6229
6230   if (addTest) {
6231     // Look pass the truncate.
6232     if (Cond.getOpcode() == ISD::TRUNCATE)
6233       Cond = Cond.getOperand(0);
6234
6235     // We know the result of AND is compared against zero. Try to match
6236     // it to BT.
6237     if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) { 
6238       SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, dl, DAG);
6239       if (NewSetCC.getNode()) {
6240         CC = NewSetCC.getOperand(0);
6241         Cond = NewSetCC.getOperand(1);
6242         addTest = false;
6243       }
6244     }
6245   }
6246
6247   if (addTest) {
6248     CC = DAG.getConstant(X86::COND_NE, MVT::i8);
6249     Cond = EmitTest(Cond, X86::COND_NE, DAG);
6250   }
6251   return DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
6252                      Chain, Dest, CC, Cond);
6253 }
6254
6255
6256 // Lower dynamic stack allocation to _alloca call for Cygwin/Mingw targets.
6257 // Calls to _alloca is needed to probe the stack when allocating more than 4k
6258 // bytes in one go. Touching the stack at 4K increments is necessary to ensure
6259 // that the guard pages used by the OS virtual memory manager are allocated in
6260 // correct sequence.
6261 SDValue
6262 X86TargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
6263                                            SelectionDAG &DAG) {
6264   assert(Subtarget->isTargetCygMing() &&
6265          "This should be used only on Cygwin/Mingw targets");
6266   DebugLoc dl = Op.getDebugLoc();
6267
6268   // Get the inputs.
6269   SDValue Chain = Op.getOperand(0);
6270   SDValue Size  = Op.getOperand(1);
6271   // FIXME: Ensure alignment here
6272
6273   SDValue Flag;
6274
6275   EVT IntPtr = getPointerTy();
6276   EVT SPTy = Subtarget->is64Bit() ? MVT::i64 : MVT::i32;
6277
6278   Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(0, true));
6279
6280   Chain = DAG.getCopyToReg(Chain, dl, X86::EAX, Size, Flag);
6281   Flag = Chain.getValue(1);
6282
6283   SDVTList  NodeTys = DAG.getVTList(MVT::Other, MVT::Flag);
6284   SDValue Ops[] = { Chain,
6285                       DAG.getTargetExternalSymbol("_alloca", IntPtr),
6286                       DAG.getRegister(X86::EAX, IntPtr),
6287                       DAG.getRegister(X86StackPtr, SPTy),
6288                       Flag };
6289   Chain = DAG.getNode(X86ISD::CALL, dl, NodeTys, Ops, 5);
6290   Flag = Chain.getValue(1);
6291
6292   Chain = DAG.getCALLSEQ_END(Chain,
6293                              DAG.getIntPtrConstant(0, true),
6294                              DAG.getIntPtrConstant(0, true),
6295                              Flag);
6296
6297   Chain = DAG.getCopyFromReg(Chain, dl, X86StackPtr, SPTy).getValue(1);
6298
6299   SDValue Ops1[2] = { Chain.getValue(0), Chain };
6300   return DAG.getMergeValues(Ops1, 2, dl);
6301 }
6302
6303 SDValue
6304 X86TargetLowering::EmitTargetCodeForMemset(SelectionDAG &DAG, DebugLoc dl,
6305                                            SDValue Chain,
6306                                            SDValue Dst, SDValue Src,
6307                                            SDValue Size, unsigned Align,
6308                                            const Value *DstSV,
6309                                            uint64_t DstSVOff) {
6310   ConstantSDNode *ConstantSize = dyn_cast<ConstantSDNode>(Size);
6311
6312   // If not DWORD aligned or size is more than the threshold, call the library.
6313   // The libc version is likely to be faster for these cases. It can use the
6314   // address value and run time information about the CPU.
6315   if ((Align & 3) != 0 ||
6316       !ConstantSize ||
6317       ConstantSize->getZExtValue() >
6318         getSubtarget()->getMaxInlineSizeThreshold()) {
6319     SDValue InFlag(0, 0);
6320
6321     // Check to see if there is a specialized entry-point for memory zeroing.
6322     ConstantSDNode *V = dyn_cast<ConstantSDNode>(Src);
6323
6324     if (const char *bzeroEntry =  V &&
6325         V->isNullValue() ? Subtarget->getBZeroEntry() : 0) {
6326       EVT IntPtr = getPointerTy();
6327       const Type *IntPtrTy = TD->getIntPtrType(*DAG.getContext());
6328       TargetLowering::ArgListTy Args;
6329       TargetLowering::ArgListEntry Entry;
6330       Entry.Node = Dst;
6331       Entry.Ty = IntPtrTy;
6332       Args.push_back(Entry);
6333       Entry.Node = Size;
6334       Args.push_back(Entry);
6335       std::pair<SDValue,SDValue> CallResult =
6336         LowerCallTo(Chain, Type::getVoidTy(*DAG.getContext()),
6337                     false, false, false, false,
6338                     0, CallingConv::C, false, /*isReturnValueUsed=*/false,
6339                     DAG.getExternalSymbol(bzeroEntry, IntPtr), Args, DAG, dl,
6340                     DAG.GetOrdering(Chain.getNode()));
6341       return CallResult.second;
6342     }
6343
6344     // Otherwise have the target-independent code call memset.
6345     return SDValue();
6346   }
6347
6348   uint64_t SizeVal = ConstantSize->getZExtValue();
6349   SDValue InFlag(0, 0);
6350   EVT AVT;
6351   SDValue Count;
6352   ConstantSDNode *ValC = dyn_cast<ConstantSDNode>(Src);
6353   unsigned BytesLeft = 0;
6354   bool TwoRepStos = false;
6355   if (ValC) {
6356     unsigned ValReg;
6357     uint64_t Val = ValC->getZExtValue() & 255;
6358
6359     // If the value is a constant, then we can potentially use larger sets.
6360     switch (Align & 3) {
6361     case 2:   // WORD aligned
6362       AVT = MVT::i16;
6363       ValReg = X86::AX;
6364       Val = (Val << 8) | Val;
6365       break;
6366     case 0:  // DWORD aligned
6367       AVT = MVT::i32;
6368       ValReg = X86::EAX;
6369       Val = (Val << 8)  | Val;
6370       Val = (Val << 16) | Val;
6371       if (Subtarget->is64Bit() && ((Align & 0x7) == 0)) {  // QWORD aligned
6372         AVT = MVT::i64;
6373         ValReg = X86::RAX;
6374         Val = (Val << 32) | Val;
6375       }
6376       break;
6377     default:  // Byte aligned
6378       AVT = MVT::i8;
6379       ValReg = X86::AL;
6380       Count = DAG.getIntPtrConstant(SizeVal);
6381       break;
6382     }
6383
6384     if (AVT.bitsGT(MVT::i8)) {
6385       unsigned UBytes = AVT.getSizeInBits() / 8;
6386       Count = DAG.getIntPtrConstant(SizeVal / UBytes);
6387       BytesLeft = SizeVal % UBytes;
6388     }
6389
6390     Chain  = DAG.getCopyToReg(Chain, dl, ValReg, DAG.getConstant(Val, AVT),
6391                               InFlag);
6392     InFlag = Chain.getValue(1);
6393   } else {
6394     AVT = MVT::i8;
6395     Count  = DAG.getIntPtrConstant(SizeVal);
6396     Chain  = DAG.getCopyToReg(Chain, dl, X86::AL, Src, InFlag);
6397     InFlag = Chain.getValue(1);
6398   }
6399
6400   Chain  = DAG.getCopyToReg(Chain, dl, Subtarget->is64Bit() ? X86::RCX :
6401                                                               X86::ECX,
6402                             Count, InFlag);
6403   InFlag = Chain.getValue(1);
6404   Chain  = DAG.getCopyToReg(Chain, dl, Subtarget->is64Bit() ? X86::RDI :
6405                                                               X86::EDI,
6406                             Dst, InFlag);
6407   InFlag = Chain.getValue(1);
6408
6409   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Flag);
6410   SDValue Ops[] = { Chain, DAG.getValueType(AVT), InFlag };
6411   Chain = DAG.getNode(X86ISD::REP_STOS, dl, Tys, Ops, array_lengthof(Ops));
6412
6413   if (TwoRepStos) {
6414     InFlag = Chain.getValue(1);
6415     Count  = Size;
6416     EVT CVT = Count.getValueType();
6417     SDValue Left = DAG.getNode(ISD::AND, dl, CVT, Count,
6418                                DAG.getConstant((AVT == MVT::i64) ? 7 : 3, CVT));
6419     Chain  = DAG.getCopyToReg(Chain, dl, (CVT == MVT::i64) ? X86::RCX :
6420                                                              X86::ECX,
6421                               Left, InFlag);
6422     InFlag = Chain.getValue(1);
6423     Tys = DAG.getVTList(MVT::Other, MVT::Flag);
6424     SDValue Ops[] = { Chain, DAG.getValueType(MVT::i8), InFlag };
6425     Chain = DAG.getNode(X86ISD::REP_STOS, dl, Tys, Ops, array_lengthof(Ops));
6426   } else if (BytesLeft) {
6427     // Handle the last 1 - 7 bytes.
6428     unsigned Offset = SizeVal - BytesLeft;
6429     EVT AddrVT = Dst.getValueType();
6430     EVT SizeVT = Size.getValueType();
6431
6432     Chain = DAG.getMemset(Chain, dl,
6433                           DAG.getNode(ISD::ADD, dl, AddrVT, Dst,
6434                                       DAG.getConstant(Offset, AddrVT)),
6435                           Src,
6436                           DAG.getConstant(BytesLeft, SizeVT),
6437                           Align, DstSV, DstSVOff + Offset);
6438   }
6439
6440   // TODO: Use a Tokenfactor, as in memcpy, instead of a single chain.
6441   return Chain;
6442 }
6443
6444 SDValue
6445 X86TargetLowering::EmitTargetCodeForMemcpy(SelectionDAG &DAG, DebugLoc dl,
6446                                       SDValue Chain, SDValue Dst, SDValue Src,
6447                                       SDValue Size, unsigned Align,
6448                                       bool AlwaysInline,
6449                                       const Value *DstSV, uint64_t DstSVOff,
6450                                       const Value *SrcSV, uint64_t SrcSVOff) {
6451   // This requires the copy size to be a constant, preferrably
6452   // within a subtarget-specific limit.
6453   ConstantSDNode *ConstantSize = dyn_cast<ConstantSDNode>(Size);
6454   if (!ConstantSize)
6455     return SDValue();
6456   uint64_t SizeVal = ConstantSize->getZExtValue();
6457   if (!AlwaysInline && SizeVal > getSubtarget()->getMaxInlineSizeThreshold())
6458     return SDValue();
6459
6460   /// If not DWORD aligned, call the library.
6461   if ((Align & 3) != 0)
6462     return SDValue();
6463
6464   // DWORD aligned
6465   EVT AVT = MVT::i32;
6466   if (Subtarget->is64Bit() && ((Align & 0x7) == 0))  // QWORD aligned
6467     AVT = MVT::i64;
6468
6469   unsigned UBytes = AVT.getSizeInBits() / 8;
6470   unsigned CountVal = SizeVal / UBytes;
6471   SDValue Count = DAG.getIntPtrConstant(CountVal);
6472   unsigned BytesLeft = SizeVal % UBytes;
6473
6474   SDValue InFlag(0, 0);
6475   Chain  = DAG.getCopyToReg(Chain, dl, Subtarget->is64Bit() ? X86::RCX :
6476                                                               X86::ECX,
6477                             Count, InFlag);
6478   InFlag = Chain.getValue(1);
6479   Chain  = DAG.getCopyToReg(Chain, dl, Subtarget->is64Bit() ? X86::RDI :
6480                                                              X86::EDI,
6481                             Dst, InFlag);
6482   InFlag = Chain.getValue(1);
6483   Chain  = DAG.getCopyToReg(Chain, dl, Subtarget->is64Bit() ? X86::RSI :
6484                                                               X86::ESI,
6485                             Src, InFlag);
6486   InFlag = Chain.getValue(1);
6487
6488   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Flag);
6489   SDValue Ops[] = { Chain, DAG.getValueType(AVT), InFlag };
6490   SDValue RepMovs = DAG.getNode(X86ISD::REP_MOVS, dl, Tys, Ops,
6491                                 array_lengthof(Ops));
6492
6493   SmallVector<SDValue, 4> Results;
6494   Results.push_back(RepMovs);
6495   if (BytesLeft) {
6496     // Handle the last 1 - 7 bytes.
6497     unsigned Offset = SizeVal - BytesLeft;
6498     EVT DstVT = Dst.getValueType();
6499     EVT SrcVT = Src.getValueType();
6500     EVT SizeVT = Size.getValueType();
6501     Results.push_back(DAG.getMemcpy(Chain, dl,
6502                                     DAG.getNode(ISD::ADD, dl, DstVT, Dst,
6503                                                 DAG.getConstant(Offset, DstVT)),
6504                                     DAG.getNode(ISD::ADD, dl, SrcVT, Src,
6505                                                 DAG.getConstant(Offset, SrcVT)),
6506                                     DAG.getConstant(BytesLeft, SizeVT),
6507                                     Align, AlwaysInline,
6508                                     DstSV, DstSVOff + Offset,
6509                                     SrcSV, SrcSVOff + Offset));
6510   }
6511
6512   return DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
6513                      &Results[0], Results.size());
6514 }
6515
6516 SDValue X86TargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) {
6517   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
6518   DebugLoc dl = Op.getDebugLoc();
6519
6520   if (!Subtarget->is64Bit()) {
6521     // vastart just stores the address of the VarArgsFrameIndex slot into the
6522     // memory location argument.
6523     SDValue FR = DAG.getFrameIndex(VarArgsFrameIndex, getPointerTy());
6524     return DAG.getStore(Op.getOperand(0), dl, FR, Op.getOperand(1), SV, 0);
6525   }
6526
6527   // __va_list_tag:
6528   //   gp_offset         (0 - 6 * 8)
6529   //   fp_offset         (48 - 48 + 8 * 16)
6530   //   overflow_arg_area (point to parameters coming in memory).
6531   //   reg_save_area
6532   SmallVector<SDValue, 8> MemOps;
6533   SDValue FIN = Op.getOperand(1);
6534   // Store gp_offset
6535   SDValue Store = DAG.getStore(Op.getOperand(0), dl,
6536                                  DAG.getConstant(VarArgsGPOffset, MVT::i32),
6537                                  FIN, SV, 0);
6538   MemOps.push_back(Store);
6539
6540   // Store fp_offset
6541   FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(),
6542                     FIN, DAG.getIntPtrConstant(4));
6543   Store = DAG.getStore(Op.getOperand(0), dl,
6544                        DAG.getConstant(VarArgsFPOffset, MVT::i32),
6545                        FIN, SV, 0);
6546   MemOps.push_back(Store);
6547
6548   // Store ptr to overflow_arg_area
6549   FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(),
6550                     FIN, DAG.getIntPtrConstant(4));
6551   SDValue OVFIN = DAG.getFrameIndex(VarArgsFrameIndex, getPointerTy());
6552   Store = DAG.getStore(Op.getOperand(0), dl, OVFIN, FIN, SV, 0);
6553   MemOps.push_back(Store);
6554
6555   // Store ptr to reg_save_area.
6556   FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(),
6557                     FIN, DAG.getIntPtrConstant(8));
6558   SDValue RSFIN = DAG.getFrameIndex(RegSaveFrameIndex, getPointerTy());
6559   Store = DAG.getStore(Op.getOperand(0), dl, RSFIN, FIN, SV, 0);
6560   MemOps.push_back(Store);
6561   return DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
6562                      &MemOps[0], MemOps.size());
6563 }
6564
6565 SDValue X86TargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) {
6566   // X86-64 va_list is a struct { i32, i32, i8*, i8* }.
6567   assert(Subtarget->is64Bit() && "This code only handles 64-bit va_arg!");
6568   SDValue Chain = Op.getOperand(0);
6569   SDValue SrcPtr = Op.getOperand(1);
6570   SDValue SrcSV = Op.getOperand(2);
6571
6572   llvm_report_error("VAArgInst is not yet implemented for x86-64!");
6573   return SDValue();
6574 }
6575
6576 SDValue X86TargetLowering::LowerVACOPY(SDValue Op, SelectionDAG &DAG) {
6577   // X86-64 va_list is a struct { i32, i32, i8*, i8* }.
6578   assert(Subtarget->is64Bit() && "This code only handles 64-bit va_copy!");
6579   SDValue Chain = Op.getOperand(0);
6580   SDValue DstPtr = Op.getOperand(1);
6581   SDValue SrcPtr = Op.getOperand(2);
6582   const Value *DstSV = cast<SrcValueSDNode>(Op.getOperand(3))->getValue();
6583   const Value *SrcSV = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
6584   DebugLoc dl = Op.getDebugLoc();
6585
6586   return DAG.getMemcpy(Chain, dl, DstPtr, SrcPtr,
6587                        DAG.getIntPtrConstant(24), 8, false,
6588                        DstSV, 0, SrcSV, 0);
6589 }
6590
6591 SDValue
6592 X86TargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op, SelectionDAG &DAG) {
6593   DebugLoc dl = Op.getDebugLoc();
6594   unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
6595   switch (IntNo) {
6596   default: return SDValue();    // Don't custom lower most intrinsics.
6597   // Comparison intrinsics.
6598   case Intrinsic::x86_sse_comieq_ss:
6599   case Intrinsic::x86_sse_comilt_ss:
6600   case Intrinsic::x86_sse_comile_ss:
6601   case Intrinsic::x86_sse_comigt_ss:
6602   case Intrinsic::x86_sse_comige_ss:
6603   case Intrinsic::x86_sse_comineq_ss:
6604   case Intrinsic::x86_sse_ucomieq_ss:
6605   case Intrinsic::x86_sse_ucomilt_ss:
6606   case Intrinsic::x86_sse_ucomile_ss:
6607   case Intrinsic::x86_sse_ucomigt_ss:
6608   case Intrinsic::x86_sse_ucomige_ss:
6609   case Intrinsic::x86_sse_ucomineq_ss:
6610   case Intrinsic::x86_sse2_comieq_sd:
6611   case Intrinsic::x86_sse2_comilt_sd:
6612   case Intrinsic::x86_sse2_comile_sd:
6613   case Intrinsic::x86_sse2_comigt_sd:
6614   case Intrinsic::x86_sse2_comige_sd:
6615   case Intrinsic::x86_sse2_comineq_sd:
6616   case Intrinsic::x86_sse2_ucomieq_sd:
6617   case Intrinsic::x86_sse2_ucomilt_sd:
6618   case Intrinsic::x86_sse2_ucomile_sd:
6619   case Intrinsic::x86_sse2_ucomigt_sd:
6620   case Intrinsic::x86_sse2_ucomige_sd:
6621   case Intrinsic::x86_sse2_ucomineq_sd: {
6622     unsigned Opc = 0;
6623     ISD::CondCode CC = ISD::SETCC_INVALID;
6624     switch (IntNo) {
6625     default: break;
6626     case Intrinsic::x86_sse_comieq_ss:
6627     case Intrinsic::x86_sse2_comieq_sd:
6628       Opc = X86ISD::COMI;
6629       CC = ISD::SETEQ;
6630       break;
6631     case Intrinsic::x86_sse_comilt_ss:
6632     case Intrinsic::x86_sse2_comilt_sd:
6633       Opc = X86ISD::COMI;
6634       CC = ISD::SETLT;
6635       break;
6636     case Intrinsic::x86_sse_comile_ss:
6637     case Intrinsic::x86_sse2_comile_sd:
6638       Opc = X86ISD::COMI;
6639       CC = ISD::SETLE;
6640       break;
6641     case Intrinsic::x86_sse_comigt_ss:
6642     case Intrinsic::x86_sse2_comigt_sd:
6643       Opc = X86ISD::COMI;
6644       CC = ISD::SETGT;
6645       break;
6646     case Intrinsic::x86_sse_comige_ss:
6647     case Intrinsic::x86_sse2_comige_sd:
6648       Opc = X86ISD::COMI;
6649       CC = ISD::SETGE;
6650       break;
6651     case Intrinsic::x86_sse_comineq_ss:
6652     case Intrinsic::x86_sse2_comineq_sd:
6653       Opc = X86ISD::COMI;
6654       CC = ISD::SETNE;
6655       break;
6656     case Intrinsic::x86_sse_ucomieq_ss:
6657     case Intrinsic::x86_sse2_ucomieq_sd:
6658       Opc = X86ISD::UCOMI;
6659       CC = ISD::SETEQ;
6660       break;
6661     case Intrinsic::x86_sse_ucomilt_ss:
6662     case Intrinsic::x86_sse2_ucomilt_sd:
6663       Opc = X86ISD::UCOMI;
6664       CC = ISD::SETLT;
6665       break;
6666     case Intrinsic::x86_sse_ucomile_ss:
6667     case Intrinsic::x86_sse2_ucomile_sd:
6668       Opc = X86ISD::UCOMI;
6669       CC = ISD::SETLE;
6670       break;
6671     case Intrinsic::x86_sse_ucomigt_ss:
6672     case Intrinsic::x86_sse2_ucomigt_sd:
6673       Opc = X86ISD::UCOMI;
6674       CC = ISD::SETGT;
6675       break;
6676     case Intrinsic::x86_sse_ucomige_ss:
6677     case Intrinsic::x86_sse2_ucomige_sd:
6678       Opc = X86ISD::UCOMI;
6679       CC = ISD::SETGE;
6680       break;
6681     case Intrinsic::x86_sse_ucomineq_ss:
6682     case Intrinsic::x86_sse2_ucomineq_sd:
6683       Opc = X86ISD::UCOMI;
6684       CC = ISD::SETNE;
6685       break;
6686     }
6687
6688     SDValue LHS = Op.getOperand(1);
6689     SDValue RHS = Op.getOperand(2);
6690     unsigned X86CC = TranslateX86CC(CC, true, LHS, RHS, DAG);
6691     assert(X86CC != X86::COND_INVALID && "Unexpected illegal condition!");
6692     SDValue Cond = DAG.getNode(Opc, dl, MVT::i32, LHS, RHS);
6693     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
6694                                 DAG.getConstant(X86CC, MVT::i8), Cond);
6695     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
6696   }
6697   // ptest intrinsics. The intrinsic these come from are designed to return
6698   // an integer value, not just an instruction so lower it to the ptest
6699   // pattern and a setcc for the result.
6700   case Intrinsic::x86_sse41_ptestz:
6701   case Intrinsic::x86_sse41_ptestc:
6702   case Intrinsic::x86_sse41_ptestnzc:{
6703     unsigned X86CC = 0;
6704     switch (IntNo) {
6705     default: llvm_unreachable("Bad fallthrough in Intrinsic lowering.");
6706     case Intrinsic::x86_sse41_ptestz:
6707       // ZF = 1
6708       X86CC = X86::COND_E;
6709       break;
6710     case Intrinsic::x86_sse41_ptestc:
6711       // CF = 1
6712       X86CC = X86::COND_B;
6713       break;
6714     case Intrinsic::x86_sse41_ptestnzc:
6715       // ZF and CF = 0
6716       X86CC = X86::COND_A;
6717       break;
6718     }
6719
6720     SDValue LHS = Op.getOperand(1);
6721     SDValue RHS = Op.getOperand(2);
6722     SDValue Test = DAG.getNode(X86ISD::PTEST, dl, MVT::i32, LHS, RHS);
6723     SDValue CC = DAG.getConstant(X86CC, MVT::i8);
6724     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8, CC, Test);
6725     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
6726   }
6727
6728   // Fix vector shift instructions where the last operand is a non-immediate
6729   // i32 value.
6730   case Intrinsic::x86_sse2_pslli_w:
6731   case Intrinsic::x86_sse2_pslli_d:
6732   case Intrinsic::x86_sse2_pslli_q:
6733   case Intrinsic::x86_sse2_psrli_w:
6734   case Intrinsic::x86_sse2_psrli_d:
6735   case Intrinsic::x86_sse2_psrli_q:
6736   case Intrinsic::x86_sse2_psrai_w:
6737   case Intrinsic::x86_sse2_psrai_d:
6738   case Intrinsic::x86_mmx_pslli_w:
6739   case Intrinsic::x86_mmx_pslli_d:
6740   case Intrinsic::x86_mmx_pslli_q:
6741   case Intrinsic::x86_mmx_psrli_w:
6742   case Intrinsic::x86_mmx_psrli_d:
6743   case Intrinsic::x86_mmx_psrli_q:
6744   case Intrinsic::x86_mmx_psrai_w:
6745   case Intrinsic::x86_mmx_psrai_d: {
6746     SDValue ShAmt = Op.getOperand(2);
6747     if (isa<ConstantSDNode>(ShAmt))
6748       return SDValue();
6749
6750     unsigned NewIntNo = 0;
6751     EVT ShAmtVT = MVT::v4i32;
6752     switch (IntNo) {
6753     case Intrinsic::x86_sse2_pslli_w:
6754       NewIntNo = Intrinsic::x86_sse2_psll_w;
6755       break;
6756     case Intrinsic::x86_sse2_pslli_d:
6757       NewIntNo = Intrinsic::x86_sse2_psll_d;
6758       break;
6759     case Intrinsic::x86_sse2_pslli_q:
6760       NewIntNo = Intrinsic::x86_sse2_psll_q;
6761       break;
6762     case Intrinsic::x86_sse2_psrli_w:
6763       NewIntNo = Intrinsic::x86_sse2_psrl_w;
6764       break;
6765     case Intrinsic::x86_sse2_psrli_d:
6766       NewIntNo = Intrinsic::x86_sse2_psrl_d;
6767       break;
6768     case Intrinsic::x86_sse2_psrli_q:
6769       NewIntNo = Intrinsic::x86_sse2_psrl_q;
6770       break;
6771     case Intrinsic::x86_sse2_psrai_w:
6772       NewIntNo = Intrinsic::x86_sse2_psra_w;
6773       break;
6774     case Intrinsic::x86_sse2_psrai_d:
6775       NewIntNo = Intrinsic::x86_sse2_psra_d;
6776       break;
6777     default: {
6778       ShAmtVT = MVT::v2i32;
6779       switch (IntNo) {
6780       case Intrinsic::x86_mmx_pslli_w:
6781         NewIntNo = Intrinsic::x86_mmx_psll_w;
6782         break;
6783       case Intrinsic::x86_mmx_pslli_d:
6784         NewIntNo = Intrinsic::x86_mmx_psll_d;
6785         break;
6786       case Intrinsic::x86_mmx_pslli_q:
6787         NewIntNo = Intrinsic::x86_mmx_psll_q;
6788         break;
6789       case Intrinsic::x86_mmx_psrli_w:
6790         NewIntNo = Intrinsic::x86_mmx_psrl_w;
6791         break;
6792       case Intrinsic::x86_mmx_psrli_d:
6793         NewIntNo = Intrinsic::x86_mmx_psrl_d;
6794         break;
6795       case Intrinsic::x86_mmx_psrli_q:
6796         NewIntNo = Intrinsic::x86_mmx_psrl_q;
6797         break;
6798       case Intrinsic::x86_mmx_psrai_w:
6799         NewIntNo = Intrinsic::x86_mmx_psra_w;
6800         break;
6801       case Intrinsic::x86_mmx_psrai_d:
6802         NewIntNo = Intrinsic::x86_mmx_psra_d;
6803         break;
6804       default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
6805       }
6806       break;
6807     }
6808     }
6809
6810     // The vector shift intrinsics with scalars uses 32b shift amounts but
6811     // the sse2/mmx shift instructions reads 64 bits. Set the upper 32 bits
6812     // to be zero.
6813     SDValue ShOps[4];
6814     ShOps[0] = ShAmt;
6815     ShOps[1] = DAG.getConstant(0, MVT::i32);
6816     if (ShAmtVT == MVT::v4i32) {
6817       ShOps[2] = DAG.getUNDEF(MVT::i32);
6818       ShOps[3] = DAG.getUNDEF(MVT::i32);
6819       ShAmt =  DAG.getNode(ISD::BUILD_VECTOR, dl, ShAmtVT, &ShOps[0], 4);
6820     } else {
6821       ShAmt =  DAG.getNode(ISD::BUILD_VECTOR, dl, ShAmtVT, &ShOps[0], 2);
6822     }
6823
6824     EVT VT = Op.getValueType();
6825     ShAmt = DAG.getNode(ISD::BIT_CONVERT, dl, VT, ShAmt);
6826     return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
6827                        DAG.getConstant(NewIntNo, MVT::i32),
6828                        Op.getOperand(1), ShAmt);
6829   }
6830   }
6831 }
6832
6833 SDValue X86TargetLowering::LowerRETURNADDR(SDValue Op, SelectionDAG &DAG) {
6834   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
6835   DebugLoc dl = Op.getDebugLoc();
6836
6837   if (Depth > 0) {
6838     SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
6839     SDValue Offset =
6840       DAG.getConstant(TD->getPointerSize(),
6841                       Subtarget->is64Bit() ? MVT::i64 : MVT::i32);
6842     return DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(),
6843                        DAG.getNode(ISD::ADD, dl, getPointerTy(),
6844                                    FrameAddr, Offset),
6845                        NULL, 0);
6846   }
6847
6848   // Just load the return address.
6849   SDValue RetAddrFI = getReturnAddressFrameIndex(DAG);
6850   return DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(),
6851                      RetAddrFI, NULL, 0);
6852 }
6853
6854 SDValue X86TargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) {
6855   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
6856   MFI->setFrameAddressIsTaken(true);
6857   EVT VT = Op.getValueType();
6858   DebugLoc dl = Op.getDebugLoc();  // FIXME probably not meaningful
6859   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
6860   unsigned FrameReg = Subtarget->is64Bit() ? X86::RBP : X86::EBP;
6861   SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
6862   while (Depth--)
6863     FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr, NULL, 0);
6864   return FrameAddr;
6865 }
6866
6867 SDValue X86TargetLowering::LowerFRAME_TO_ARGS_OFFSET(SDValue Op,
6868                                                      SelectionDAG &DAG) {
6869   return DAG.getIntPtrConstant(2*TD->getPointerSize());
6870 }
6871
6872 SDValue X86TargetLowering::LowerEH_RETURN(SDValue Op, SelectionDAG &DAG)
6873 {
6874   MachineFunction &MF = DAG.getMachineFunction();
6875   SDValue Chain     = Op.getOperand(0);
6876   SDValue Offset    = Op.getOperand(1);
6877   SDValue Handler   = Op.getOperand(2);
6878   DebugLoc dl       = Op.getDebugLoc();
6879
6880   SDValue Frame = DAG.getRegister(Subtarget->is64Bit() ? X86::RBP : X86::EBP,
6881                                   getPointerTy());
6882   unsigned StoreAddrReg = (Subtarget->is64Bit() ? X86::RCX : X86::ECX);
6883
6884   SDValue StoreAddr = DAG.getNode(ISD::SUB, dl, getPointerTy(), Frame,
6885                                   DAG.getIntPtrConstant(-TD->getPointerSize()));
6886   StoreAddr = DAG.getNode(ISD::ADD, dl, getPointerTy(), StoreAddr, Offset);
6887   Chain = DAG.getStore(Chain, dl, Handler, StoreAddr, NULL, 0);
6888   Chain = DAG.getCopyToReg(Chain, dl, StoreAddrReg, StoreAddr);
6889   MF.getRegInfo().addLiveOut(StoreAddrReg);
6890
6891   return DAG.getNode(X86ISD::EH_RETURN, dl,
6892                      MVT::Other,
6893                      Chain, DAG.getRegister(StoreAddrReg, getPointerTy()));
6894 }
6895
6896 SDValue X86TargetLowering::LowerTRAMPOLINE(SDValue Op,
6897                                              SelectionDAG &DAG) {
6898   SDValue Root = Op.getOperand(0);
6899   SDValue Trmp = Op.getOperand(1); // trampoline
6900   SDValue FPtr = Op.getOperand(2); // nested function
6901   SDValue Nest = Op.getOperand(3); // 'nest' parameter value
6902   DebugLoc dl  = Op.getDebugLoc();
6903
6904   const Value *TrmpAddr = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
6905
6906   const X86InstrInfo *TII =
6907     ((X86TargetMachine&)getTargetMachine()).getInstrInfo();
6908
6909   if (Subtarget->is64Bit()) {
6910     SDValue OutChains[6];
6911
6912     // Large code-model.
6913
6914     const unsigned char JMP64r  = TII->getBaseOpcodeFor(X86::JMP64r);
6915     const unsigned char MOV64ri = TII->getBaseOpcodeFor(X86::MOV64ri);
6916
6917     const unsigned char N86R10 = RegInfo->getX86RegNum(X86::R10);
6918     const unsigned char N86R11 = RegInfo->getX86RegNum(X86::R11);
6919
6920     const unsigned char REX_WB = 0x40 | 0x08 | 0x01; // REX prefix
6921
6922     // Load the pointer to the nested function into R11.
6923     unsigned OpCode = ((MOV64ri | N86R11) << 8) | REX_WB; // movabsq r11
6924     SDValue Addr = Trmp;
6925     OutChains[0] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
6926                                 Addr, TrmpAddr, 0);
6927
6928     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
6929                        DAG.getConstant(2, MVT::i64));
6930     OutChains[1] = DAG.getStore(Root, dl, FPtr, Addr, TrmpAddr, 2, false, 2);
6931
6932     // Load the 'nest' parameter value into R10.
6933     // R10 is specified in X86CallingConv.td
6934     OpCode = ((MOV64ri | N86R10) << 8) | REX_WB; // movabsq r10
6935     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
6936                        DAG.getConstant(10, MVT::i64));
6937     OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
6938                                 Addr, TrmpAddr, 10);
6939
6940     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
6941                        DAG.getConstant(12, MVT::i64));
6942     OutChains[3] = DAG.getStore(Root, dl, Nest, Addr, TrmpAddr, 12, false, 2);
6943
6944     // Jump to the nested function.
6945     OpCode = (JMP64r << 8) | REX_WB; // jmpq *...
6946     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
6947                        DAG.getConstant(20, MVT::i64));
6948     OutChains[4] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
6949                                 Addr, TrmpAddr, 20);
6950
6951     unsigned char ModRM = N86R11 | (4 << 3) | (3 << 6); // ...r11
6952     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
6953                        DAG.getConstant(22, MVT::i64));
6954     OutChains[5] = DAG.getStore(Root, dl, DAG.getConstant(ModRM, MVT::i8), Addr,
6955                                 TrmpAddr, 22);
6956
6957     SDValue Ops[] =
6958       { Trmp, DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains, 6) };
6959     return DAG.getMergeValues(Ops, 2, dl);
6960   } else {
6961     const Function *Func =
6962       cast<Function>(cast<SrcValueSDNode>(Op.getOperand(5))->getValue());
6963     CallingConv::ID CC = Func->getCallingConv();
6964     unsigned NestReg;
6965
6966     switch (CC) {
6967     default:
6968       llvm_unreachable("Unsupported calling convention");
6969     case CallingConv::C:
6970     case CallingConv::X86_StdCall: {
6971       // Pass 'nest' parameter in ECX.
6972       // Must be kept in sync with X86CallingConv.td
6973       NestReg = X86::ECX;
6974
6975       // Check that ECX wasn't needed by an 'inreg' parameter.
6976       const FunctionType *FTy = Func->getFunctionType();
6977       const AttrListPtr &Attrs = Func->getAttributes();
6978
6979       if (!Attrs.isEmpty() && !Func->isVarArg()) {
6980         unsigned InRegCount = 0;
6981         unsigned Idx = 1;
6982
6983         for (FunctionType::param_iterator I = FTy->param_begin(),
6984              E = FTy->param_end(); I != E; ++I, ++Idx)
6985           if (Attrs.paramHasAttr(Idx, Attribute::InReg))
6986             // FIXME: should only count parameters that are lowered to integers.
6987             InRegCount += (TD->getTypeSizeInBits(*I) + 31) / 32;
6988
6989         if (InRegCount > 2) {
6990           llvm_report_error("Nest register in use - reduce number of inreg parameters!");
6991         }
6992       }
6993       break;
6994     }
6995     case CallingConv::X86_FastCall:
6996     case CallingConv::Fast:
6997       // Pass 'nest' parameter in EAX.
6998       // Must be kept in sync with X86CallingConv.td
6999       NestReg = X86::EAX;
7000       break;
7001     }
7002
7003     SDValue OutChains[4];
7004     SDValue Addr, Disp;
7005
7006     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
7007                        DAG.getConstant(10, MVT::i32));
7008     Disp = DAG.getNode(ISD::SUB, dl, MVT::i32, FPtr, Addr);
7009
7010     const unsigned char MOV32ri = TII->getBaseOpcodeFor(X86::MOV32ri);
7011     const unsigned char N86Reg = RegInfo->getX86RegNum(NestReg);
7012     OutChains[0] = DAG.getStore(Root, dl,
7013                                 DAG.getConstant(MOV32ri|N86Reg, MVT::i8),
7014                                 Trmp, TrmpAddr, 0);
7015
7016     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
7017                        DAG.getConstant(1, MVT::i32));
7018     OutChains[1] = DAG.getStore(Root, dl, Nest, Addr, TrmpAddr, 1, false, 1);
7019
7020     const unsigned char JMP = TII->getBaseOpcodeFor(X86::JMP);
7021     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
7022                        DAG.getConstant(5, MVT::i32));
7023     OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(JMP, MVT::i8), Addr,
7024                                 TrmpAddr, 5, false, 1);
7025
7026     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
7027                        DAG.getConstant(6, MVT::i32));
7028     OutChains[3] = DAG.getStore(Root, dl, Disp, Addr, TrmpAddr, 6, false, 1);
7029
7030     SDValue Ops[] =
7031       { Trmp, DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains, 4) };
7032     return DAG.getMergeValues(Ops, 2, dl);
7033   }
7034 }
7035
7036 SDValue X86TargetLowering::LowerFLT_ROUNDS_(SDValue Op, SelectionDAG &DAG) {
7037   /*
7038    The rounding mode is in bits 11:10 of FPSR, and has the following
7039    settings:
7040      00 Round to nearest
7041      01 Round to -inf
7042      10 Round to +inf
7043      11 Round to 0
7044
7045   FLT_ROUNDS, on the other hand, expects the following:
7046     -1 Undefined
7047      0 Round to 0
7048      1 Round to nearest
7049      2 Round to +inf
7050      3 Round to -inf
7051
7052   To perform the conversion, we do:
7053     (((((FPSR & 0x800) >> 11) | ((FPSR & 0x400) >> 9)) + 1) & 3)
7054   */
7055
7056   MachineFunction &MF = DAG.getMachineFunction();
7057   const TargetMachine &TM = MF.getTarget();
7058   const TargetFrameInfo &TFI = *TM.getFrameInfo();
7059   unsigned StackAlignment = TFI.getStackAlignment();
7060   EVT VT = Op.getValueType();
7061   DebugLoc dl = Op.getDebugLoc();
7062
7063   // Save FP Control Word to stack slot
7064   int SSFI = MF.getFrameInfo()->CreateStackObject(2, StackAlignment, false);
7065   SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
7066
7067   SDValue Chain = DAG.getNode(X86ISD::FNSTCW16m, dl, MVT::Other,
7068                               DAG.getEntryNode(), StackSlot);
7069
7070   // Load FP Control Word from stack slot
7071   SDValue CWD = DAG.getLoad(MVT::i16, dl, Chain, StackSlot, NULL, 0);
7072
7073   // Transform as necessary
7074   SDValue CWD1 =
7075     DAG.getNode(ISD::SRL, dl, MVT::i16,
7076                 DAG.getNode(ISD::AND, dl, MVT::i16,
7077                             CWD, DAG.getConstant(0x800, MVT::i16)),
7078                 DAG.getConstant(11, MVT::i8));
7079   SDValue CWD2 =
7080     DAG.getNode(ISD::SRL, dl, MVT::i16,
7081                 DAG.getNode(ISD::AND, dl, MVT::i16,
7082                             CWD, DAG.getConstant(0x400, MVT::i16)),
7083                 DAG.getConstant(9, MVT::i8));
7084
7085   SDValue RetVal =
7086     DAG.getNode(ISD::AND, dl, MVT::i16,
7087                 DAG.getNode(ISD::ADD, dl, MVT::i16,
7088                             DAG.getNode(ISD::OR, dl, MVT::i16, CWD1, CWD2),
7089                             DAG.getConstant(1, MVT::i16)),
7090                 DAG.getConstant(3, MVT::i16));
7091
7092
7093   return DAG.getNode((VT.getSizeInBits() < 16 ?
7094                       ISD::TRUNCATE : ISD::ZERO_EXTEND), dl, VT, RetVal);
7095 }
7096
7097 SDValue X86TargetLowering::LowerCTLZ(SDValue Op, SelectionDAG &DAG) {
7098   EVT VT = Op.getValueType();
7099   EVT OpVT = VT;
7100   unsigned NumBits = VT.getSizeInBits();
7101   DebugLoc dl = Op.getDebugLoc();
7102
7103   Op = Op.getOperand(0);
7104   if (VT == MVT::i8) {
7105     // Zero extend to i32 since there is not an i8 bsr.
7106     OpVT = MVT::i32;
7107     Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
7108   }
7109
7110   // Issue a bsr (scan bits in reverse) which also sets EFLAGS.
7111   SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
7112   Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
7113
7114   // If src is zero (i.e. bsr sets ZF), returns NumBits.
7115   SDValue Ops[] = {
7116     Op,
7117     DAG.getConstant(NumBits+NumBits-1, OpVT),
7118     DAG.getConstant(X86::COND_E, MVT::i8),
7119     Op.getValue(1)
7120   };
7121   Op = DAG.getNode(X86ISD::CMOV, dl, OpVT, Ops, array_lengthof(Ops));
7122
7123   // Finally xor with NumBits-1.
7124   Op = DAG.getNode(ISD::XOR, dl, OpVT, Op, DAG.getConstant(NumBits-1, OpVT));
7125
7126   if (VT == MVT::i8)
7127     Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
7128   return Op;
7129 }
7130
7131 SDValue X86TargetLowering::LowerCTTZ(SDValue Op, SelectionDAG &DAG) {
7132   EVT VT = Op.getValueType();
7133   EVT OpVT = VT;
7134   unsigned NumBits = VT.getSizeInBits();
7135   DebugLoc dl = Op.getDebugLoc();
7136
7137   Op = Op.getOperand(0);
7138   if (VT == MVT::i8) {
7139     OpVT = MVT::i32;
7140     Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
7141   }
7142
7143   // Issue a bsf (scan bits forward) which also sets EFLAGS.
7144   SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
7145   Op = DAG.getNode(X86ISD::BSF, dl, VTs, Op);
7146
7147   // If src is zero (i.e. bsf sets ZF), returns NumBits.
7148   SDValue Ops[] = {
7149     Op,
7150     DAG.getConstant(NumBits, OpVT),
7151     DAG.getConstant(X86::COND_E, MVT::i8),
7152     Op.getValue(1)
7153   };
7154   Op = DAG.getNode(X86ISD::CMOV, dl, OpVT, Ops, array_lengthof(Ops));
7155
7156   if (VT == MVT::i8)
7157     Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
7158   return Op;
7159 }
7160
7161 SDValue X86TargetLowering::LowerMUL_V2I64(SDValue Op, SelectionDAG &DAG) {
7162   EVT VT = Op.getValueType();
7163   assert(VT == MVT::v2i64 && "Only know how to lower V2I64 multiply");
7164   DebugLoc dl = Op.getDebugLoc();
7165
7166   //  ulong2 Ahi = __builtin_ia32_psrlqi128( a, 32);
7167   //  ulong2 Bhi = __builtin_ia32_psrlqi128( b, 32);
7168   //  ulong2 AloBlo = __builtin_ia32_pmuludq128( a, b );
7169   //  ulong2 AloBhi = __builtin_ia32_pmuludq128( a, Bhi );
7170   //  ulong2 AhiBlo = __builtin_ia32_pmuludq128( Ahi, b );
7171   //
7172   //  AloBhi = __builtin_ia32_psllqi128( AloBhi, 32 );
7173   //  AhiBlo = __builtin_ia32_psllqi128( AhiBlo, 32 );
7174   //  return AloBlo + AloBhi + AhiBlo;
7175
7176   SDValue A = Op.getOperand(0);
7177   SDValue B = Op.getOperand(1);
7178
7179   SDValue Ahi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
7180                        DAG.getConstant(Intrinsic::x86_sse2_psrli_q, MVT::i32),
7181                        A, DAG.getConstant(32, MVT::i32));
7182   SDValue Bhi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
7183                        DAG.getConstant(Intrinsic::x86_sse2_psrli_q, MVT::i32),
7184                        B, DAG.getConstant(32, MVT::i32));
7185   SDValue AloBlo = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
7186                        DAG.getConstant(Intrinsic::x86_sse2_pmulu_dq, MVT::i32),
7187                        A, B);
7188   SDValue AloBhi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
7189                        DAG.getConstant(Intrinsic::x86_sse2_pmulu_dq, MVT::i32),
7190                        A, Bhi);
7191   SDValue AhiBlo = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
7192                        DAG.getConstant(Intrinsic::x86_sse2_pmulu_dq, MVT::i32),
7193                        Ahi, B);
7194   AloBhi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
7195                        DAG.getConstant(Intrinsic::x86_sse2_pslli_q, MVT::i32),
7196                        AloBhi, DAG.getConstant(32, MVT::i32));
7197   AhiBlo = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
7198                        DAG.getConstant(Intrinsic::x86_sse2_pslli_q, MVT::i32),
7199                        AhiBlo, DAG.getConstant(32, MVT::i32));
7200   SDValue Res = DAG.getNode(ISD::ADD, dl, VT, AloBlo, AloBhi);
7201   Res = DAG.getNode(ISD::ADD, dl, VT, Res, AhiBlo);
7202   return Res;
7203 }
7204
7205
7206 SDValue X86TargetLowering::LowerXALUO(SDValue Op, SelectionDAG &DAG) {
7207   // Lower the "add/sub/mul with overflow" instruction into a regular ins plus
7208   // a "setcc" instruction that checks the overflow flag. The "brcond" lowering
7209   // looks for this combo and may remove the "setcc" instruction if the "setcc"
7210   // has only one use.
7211   SDNode *N = Op.getNode();
7212   SDValue LHS = N->getOperand(0);
7213   SDValue RHS = N->getOperand(1);
7214   unsigned BaseOp = 0;
7215   unsigned Cond = 0;
7216   DebugLoc dl = Op.getDebugLoc();
7217
7218   switch (Op.getOpcode()) {
7219   default: llvm_unreachable("Unknown ovf instruction!");
7220   case ISD::SADDO:
7221     // A subtract of one will be selected as a INC. Note that INC doesn't
7222     // set CF, so we can't do this for UADDO.
7223     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op))
7224       if (C->getAPIntValue() == 1) {
7225         BaseOp = X86ISD::INC;
7226         Cond = X86::COND_O;
7227         break;
7228       }
7229     BaseOp = X86ISD::ADD;
7230     Cond = X86::COND_O;
7231     break;
7232   case ISD::UADDO:
7233     BaseOp = X86ISD::ADD;
7234     Cond = X86::COND_B;
7235     break;
7236   case ISD::SSUBO:
7237     // A subtract of one will be selected as a DEC. Note that DEC doesn't
7238     // set CF, so we can't do this for USUBO.
7239     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op))
7240       if (C->getAPIntValue() == 1) {
7241         BaseOp = X86ISD::DEC;
7242         Cond = X86::COND_O;
7243         break;
7244       }
7245     BaseOp = X86ISD::SUB;
7246     Cond = X86::COND_O;
7247     break;
7248   case ISD::USUBO:
7249     BaseOp = X86ISD::SUB;
7250     Cond = X86::COND_B;
7251     break;
7252   case ISD::SMULO:
7253     BaseOp = X86ISD::SMUL;
7254     Cond = X86::COND_O;
7255     break;
7256   case ISD::UMULO:
7257     BaseOp = X86ISD::UMUL;
7258     Cond = X86::COND_B;
7259     break;
7260   }
7261
7262   // Also sets EFLAGS.
7263   SDVTList VTs = DAG.getVTList(N->getValueType(0), MVT::i32);
7264   SDValue Sum = DAG.getNode(BaseOp, dl, VTs, LHS, RHS);
7265
7266   SDValue SetCC =
7267     DAG.getNode(X86ISD::SETCC, dl, N->getValueType(1),
7268                 DAG.getConstant(Cond, MVT::i32), SDValue(Sum.getNode(), 1));
7269
7270   DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), SetCC);
7271   return Sum;
7272 }
7273
7274 SDValue X86TargetLowering::LowerCMP_SWAP(SDValue Op, SelectionDAG &DAG) {
7275   EVT T = Op.getValueType();
7276   DebugLoc dl = Op.getDebugLoc();
7277   unsigned Reg = 0;
7278   unsigned size = 0;
7279   switch(T.getSimpleVT().SimpleTy) {
7280   default:
7281     assert(false && "Invalid value type!");
7282   case MVT::i8:  Reg = X86::AL;  size = 1; break;
7283   case MVT::i16: Reg = X86::AX;  size = 2; break;
7284   case MVT::i32: Reg = X86::EAX; size = 4; break;
7285   case MVT::i64:
7286     assert(Subtarget->is64Bit() && "Node not type legal!");
7287     Reg = X86::RAX; size = 8;
7288     break;
7289   }
7290   SDValue cpIn = DAG.getCopyToReg(Op.getOperand(0), dl, Reg,
7291                                     Op.getOperand(2), SDValue());
7292   SDValue Ops[] = { cpIn.getValue(0),
7293                     Op.getOperand(1),
7294                     Op.getOperand(3),
7295                     DAG.getTargetConstant(size, MVT::i8),
7296                     cpIn.getValue(1) };
7297   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Flag);
7298   SDValue Result = DAG.getNode(X86ISD::LCMPXCHG_DAG, dl, Tys, Ops, 5);
7299   SDValue cpOut =
7300     DAG.getCopyFromReg(Result.getValue(0), dl, Reg, T, Result.getValue(1));
7301   return cpOut;
7302 }
7303
7304 SDValue X86TargetLowering::LowerREADCYCLECOUNTER(SDValue Op,
7305                                                  SelectionDAG &DAG) {
7306   assert(Subtarget->is64Bit() && "Result not type legalized?");
7307   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Flag);
7308   SDValue TheChain = Op.getOperand(0);
7309   DebugLoc dl = Op.getDebugLoc();
7310   SDValue rd = DAG.getNode(X86ISD::RDTSC_DAG, dl, Tys, &TheChain, 1);
7311   SDValue rax = DAG.getCopyFromReg(rd, dl, X86::RAX, MVT::i64, rd.getValue(1));
7312   SDValue rdx = DAG.getCopyFromReg(rax.getValue(1), dl, X86::RDX, MVT::i64,
7313                                    rax.getValue(2));
7314   SDValue Tmp = DAG.getNode(ISD::SHL, dl, MVT::i64, rdx,
7315                             DAG.getConstant(32, MVT::i8));
7316   SDValue Ops[] = {
7317     DAG.getNode(ISD::OR, dl, MVT::i64, rax, Tmp),
7318     rdx.getValue(1)
7319   };
7320   return DAG.getMergeValues(Ops, 2, dl);
7321 }
7322
7323 SDValue X86TargetLowering::LowerLOAD_SUB(SDValue Op, SelectionDAG &DAG) {
7324   SDNode *Node = Op.getNode();
7325   DebugLoc dl = Node->getDebugLoc();
7326   EVT T = Node->getValueType(0);
7327   SDValue negOp = DAG.getNode(ISD::SUB, dl, T,
7328                               DAG.getConstant(0, T), Node->getOperand(2));
7329   return DAG.getAtomic(ISD::ATOMIC_LOAD_ADD, dl,
7330                        cast<AtomicSDNode>(Node)->getMemoryVT(),
7331                        Node->getOperand(0),
7332                        Node->getOperand(1), negOp,
7333                        cast<AtomicSDNode>(Node)->getSrcValue(),
7334                        cast<AtomicSDNode>(Node)->getAlignment());
7335 }
7336
7337 /// LowerOperation - Provide custom lowering hooks for some operations.
7338 ///
7339 SDValue X86TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) {
7340   switch (Op.getOpcode()) {
7341   default: llvm_unreachable("Should not custom lower this!");
7342   case ISD::ATOMIC_CMP_SWAP:    return LowerCMP_SWAP(Op,DAG);
7343   case ISD::ATOMIC_LOAD_SUB:    return LowerLOAD_SUB(Op,DAG);
7344   case ISD::BUILD_VECTOR:       return LowerBUILD_VECTOR(Op, DAG);
7345   case ISD::CONCAT_VECTORS:     return LowerCONCAT_VECTORS(Op, DAG);
7346   case ISD::VECTOR_SHUFFLE:     return LowerVECTOR_SHUFFLE(Op, DAG);
7347   case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
7348   case ISD::INSERT_VECTOR_ELT:  return LowerINSERT_VECTOR_ELT(Op, DAG);
7349   case ISD::SCALAR_TO_VECTOR:   return LowerSCALAR_TO_VECTOR(Op, DAG);
7350   case ISD::ConstantPool:       return LowerConstantPool(Op, DAG);
7351   case ISD::GlobalAddress:      return LowerGlobalAddress(Op, DAG);
7352   case ISD::GlobalTLSAddress:   return LowerGlobalTLSAddress(Op, DAG);
7353   case ISD::ExternalSymbol:     return LowerExternalSymbol(Op, DAG);
7354   case ISD::BlockAddress:       return LowerBlockAddress(Op, DAG);
7355   case ISD::SHL_PARTS:
7356   case ISD::SRA_PARTS:
7357   case ISD::SRL_PARTS:          return LowerShift(Op, DAG);
7358   case ISD::SINT_TO_FP:         return LowerSINT_TO_FP(Op, DAG);
7359   case ISD::UINT_TO_FP:         return LowerUINT_TO_FP(Op, DAG);
7360   case ISD::FP_TO_SINT:         return LowerFP_TO_SINT(Op, DAG);
7361   case ISD::FP_TO_UINT:         return LowerFP_TO_UINT(Op, DAG);
7362   case ISD::FABS:               return LowerFABS(Op, DAG);
7363   case ISD::FNEG:               return LowerFNEG(Op, DAG);
7364   case ISD::FCOPYSIGN:          return LowerFCOPYSIGN(Op, DAG);
7365   case ISD::SETCC:              return LowerSETCC(Op, DAG);
7366   case ISD::VSETCC:             return LowerVSETCC(Op, DAG);
7367   case ISD::SELECT:             return LowerSELECT(Op, DAG);
7368   case ISD::BRCOND:             return LowerBRCOND(Op, DAG);
7369   case ISD::JumpTable:          return LowerJumpTable(Op, DAG);
7370   case ISD::VASTART:            return LowerVASTART(Op, DAG);
7371   case ISD::VAARG:              return LowerVAARG(Op, DAG);
7372   case ISD::VACOPY:             return LowerVACOPY(Op, DAG);
7373   case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
7374   case ISD::RETURNADDR:         return LowerRETURNADDR(Op, DAG);
7375   case ISD::FRAMEADDR:          return LowerFRAMEADDR(Op, DAG);
7376   case ISD::FRAME_TO_ARGS_OFFSET:
7377                                 return LowerFRAME_TO_ARGS_OFFSET(Op, DAG);
7378   case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG);
7379   case ISD::EH_RETURN:          return LowerEH_RETURN(Op, DAG);
7380   case ISD::TRAMPOLINE:         return LowerTRAMPOLINE(Op, DAG);
7381   case ISD::FLT_ROUNDS_:        return LowerFLT_ROUNDS_(Op, DAG);
7382   case ISD::CTLZ:               return LowerCTLZ(Op, DAG);
7383   case ISD::CTTZ:               return LowerCTTZ(Op, DAG);
7384   case ISD::MUL:                return LowerMUL_V2I64(Op, DAG);
7385   case ISD::SADDO:
7386   case ISD::UADDO:
7387   case ISD::SSUBO:
7388   case ISD::USUBO:
7389   case ISD::SMULO:
7390   case ISD::UMULO:              return LowerXALUO(Op, DAG);
7391   case ISD::READCYCLECOUNTER:   return LowerREADCYCLECOUNTER(Op, DAG);
7392   }
7393 }
7394
7395 void X86TargetLowering::
7396 ReplaceATOMIC_BINARY_64(SDNode *Node, SmallVectorImpl<SDValue>&Results,
7397                         SelectionDAG &DAG, unsigned NewOp) {
7398   EVT T = Node->getValueType(0);
7399   DebugLoc dl = Node->getDebugLoc();
7400   assert (T == MVT::i64 && "Only know how to expand i64 atomics");
7401
7402   SDValue Chain = Node->getOperand(0);
7403   SDValue In1 = Node->getOperand(1);
7404   SDValue In2L = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
7405                              Node->getOperand(2), DAG.getIntPtrConstant(0));
7406   SDValue In2H = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
7407                              Node->getOperand(2), DAG.getIntPtrConstant(1));
7408   SDValue Ops[] = { Chain, In1, In2L, In2H };
7409   SDVTList Tys = DAG.getVTList(MVT::i32, MVT::i32, MVT::Other);
7410   SDValue Result =
7411     DAG.getMemIntrinsicNode(NewOp, dl, Tys, Ops, 4, MVT::i64,
7412                             cast<MemSDNode>(Node)->getMemOperand());
7413   SDValue OpsF[] = { Result.getValue(0), Result.getValue(1)};
7414   Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, OpsF, 2));
7415   Results.push_back(Result.getValue(2));
7416 }
7417
7418 /// ReplaceNodeResults - Replace a node with an illegal result type
7419 /// with a new node built out of custom code.
7420 void X86TargetLowering::ReplaceNodeResults(SDNode *N,
7421                                            SmallVectorImpl<SDValue>&Results,
7422                                            SelectionDAG &DAG) {
7423   DebugLoc dl = N->getDebugLoc();
7424   switch (N->getOpcode()) {
7425   default:
7426     assert(false && "Do not know how to custom type legalize this operation!");
7427     return;
7428   case ISD::FP_TO_SINT: {
7429     std::pair<SDValue,SDValue> Vals =
7430         FP_TO_INTHelper(SDValue(N, 0), DAG, true);
7431     SDValue FIST = Vals.first, StackSlot = Vals.second;
7432     if (FIST.getNode() != 0) {
7433       EVT VT = N->getValueType(0);
7434       // Return a load from the stack slot.
7435       Results.push_back(DAG.getLoad(VT, dl, FIST, StackSlot, NULL, 0));
7436     }
7437     return;
7438   }
7439   case ISD::READCYCLECOUNTER: {
7440     SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Flag);
7441     SDValue TheChain = N->getOperand(0);
7442     SDValue rd = DAG.getNode(X86ISD::RDTSC_DAG, dl, Tys, &TheChain, 1);
7443     SDValue eax = DAG.getCopyFromReg(rd, dl, X86::EAX, MVT::i32,
7444                                      rd.getValue(1));
7445     SDValue edx = DAG.getCopyFromReg(eax.getValue(1), dl, X86::EDX, MVT::i32,
7446                                      eax.getValue(2));
7447     // Use a buildpair to merge the two 32-bit values into a 64-bit one.
7448     SDValue Ops[] = { eax, edx };
7449     Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Ops, 2));
7450     Results.push_back(edx.getValue(1));
7451     return;
7452   }
7453   case ISD::SDIV:
7454   case ISD::UDIV:
7455   case ISD::SREM:
7456   case ISD::UREM: {
7457     EVT WidenVT = getTypeToTransformTo(*DAG.getContext(), N->getValueType(0));
7458     Results.push_back(DAG.UnrollVectorOp(N, WidenVT.getVectorNumElements()));
7459     return;
7460   }
7461   case ISD::ATOMIC_CMP_SWAP: {
7462     EVT T = N->getValueType(0);
7463     assert (T == MVT::i64 && "Only know how to expand i64 Cmp and Swap");
7464     SDValue cpInL, cpInH;
7465     cpInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(2),
7466                         DAG.getConstant(0, MVT::i32));
7467     cpInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(2),
7468                         DAG.getConstant(1, MVT::i32));
7469     cpInL = DAG.getCopyToReg(N->getOperand(0), dl, X86::EAX, cpInL, SDValue());
7470     cpInH = DAG.getCopyToReg(cpInL.getValue(0), dl, X86::EDX, cpInH,
7471                              cpInL.getValue(1));
7472     SDValue swapInL, swapInH;
7473     swapInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(3),
7474                           DAG.getConstant(0, MVT::i32));
7475     swapInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(3),
7476                           DAG.getConstant(1, MVT::i32));
7477     swapInL = DAG.getCopyToReg(cpInH.getValue(0), dl, X86::EBX, swapInL,
7478                                cpInH.getValue(1));
7479     swapInH = DAG.getCopyToReg(swapInL.getValue(0), dl, X86::ECX, swapInH,
7480                                swapInL.getValue(1));
7481     SDValue Ops[] = { swapInH.getValue(0),
7482                       N->getOperand(1),
7483                       swapInH.getValue(1) };
7484     SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Flag);
7485     SDValue Result = DAG.getNode(X86ISD::LCMPXCHG8_DAG, dl, Tys, Ops, 3);
7486     SDValue cpOutL = DAG.getCopyFromReg(Result.getValue(0), dl, X86::EAX,
7487                                         MVT::i32, Result.getValue(1));
7488     SDValue cpOutH = DAG.getCopyFromReg(cpOutL.getValue(1), dl, X86::EDX,
7489                                         MVT::i32, cpOutL.getValue(2));
7490     SDValue OpsF[] = { cpOutL.getValue(0), cpOutH.getValue(0)};
7491     Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, OpsF, 2));
7492     Results.push_back(cpOutH.getValue(1));
7493     return;
7494   }
7495   case ISD::ATOMIC_LOAD_ADD:
7496     ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMADD64_DAG);
7497     return;
7498   case ISD::ATOMIC_LOAD_AND:
7499     ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMAND64_DAG);
7500     return;
7501   case ISD::ATOMIC_LOAD_NAND:
7502     ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMNAND64_DAG);
7503     return;
7504   case ISD::ATOMIC_LOAD_OR:
7505     ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMOR64_DAG);
7506     return;
7507   case ISD::ATOMIC_LOAD_SUB:
7508     ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMSUB64_DAG);
7509     return;
7510   case ISD::ATOMIC_LOAD_XOR:
7511     ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMXOR64_DAG);
7512     return;
7513   case ISD::ATOMIC_SWAP:
7514     ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMSWAP64_DAG);
7515     return;
7516   }
7517 }
7518
7519 const char *X86TargetLowering::getTargetNodeName(unsigned Opcode) const {
7520   switch (Opcode) {
7521   default: return NULL;
7522   case X86ISD::BSF:                return "X86ISD::BSF";
7523   case X86ISD::BSR:                return "X86ISD::BSR";
7524   case X86ISD::SHLD:               return "X86ISD::SHLD";
7525   case X86ISD::SHRD:               return "X86ISD::SHRD";
7526   case X86ISD::FAND:               return "X86ISD::FAND";
7527   case X86ISD::FOR:                return "X86ISD::FOR";
7528   case X86ISD::FXOR:               return "X86ISD::FXOR";
7529   case X86ISD::FSRL:               return "X86ISD::FSRL";
7530   case X86ISD::FILD:               return "X86ISD::FILD";
7531   case X86ISD::FILD_FLAG:          return "X86ISD::FILD_FLAG";
7532   case X86ISD::FP_TO_INT16_IN_MEM: return "X86ISD::FP_TO_INT16_IN_MEM";
7533   case X86ISD::FP_TO_INT32_IN_MEM: return "X86ISD::FP_TO_INT32_IN_MEM";
7534   case X86ISD::FP_TO_INT64_IN_MEM: return "X86ISD::FP_TO_INT64_IN_MEM";
7535   case X86ISD::FLD:                return "X86ISD::FLD";
7536   case X86ISD::FST:                return "X86ISD::FST";
7537   case X86ISD::CALL:               return "X86ISD::CALL";
7538   case X86ISD::RDTSC_DAG:          return "X86ISD::RDTSC_DAG";
7539   case X86ISD::BT:                 return "X86ISD::BT";
7540   case X86ISD::CMP:                return "X86ISD::CMP";
7541   case X86ISD::COMI:               return "X86ISD::COMI";
7542   case X86ISD::UCOMI:              return "X86ISD::UCOMI";
7543   case X86ISD::SETCC:              return "X86ISD::SETCC";
7544   case X86ISD::SETCC_CARRY:        return "X86ISD::SETCC_CARRY";
7545   case X86ISD::CMOV:               return "X86ISD::CMOV";
7546   case X86ISD::BRCOND:             return "X86ISD::BRCOND";
7547   case X86ISD::RET_FLAG:           return "X86ISD::RET_FLAG";
7548   case X86ISD::REP_STOS:           return "X86ISD::REP_STOS";
7549   case X86ISD::REP_MOVS:           return "X86ISD::REP_MOVS";
7550   case X86ISD::GlobalBaseReg:      return "X86ISD::GlobalBaseReg";
7551   case X86ISD::Wrapper:            return "X86ISD::Wrapper";
7552   case X86ISD::WrapperRIP:         return "X86ISD::WrapperRIP";
7553   case X86ISD::PEXTRB:             return "X86ISD::PEXTRB";
7554   case X86ISD::PEXTRW:             return "X86ISD::PEXTRW";
7555   case X86ISD::INSERTPS:           return "X86ISD::INSERTPS";
7556   case X86ISD::PINSRB:             return "X86ISD::PINSRB";
7557   case X86ISD::PINSRW:             return "X86ISD::PINSRW";
7558   case X86ISD::PSHUFB:             return "X86ISD::PSHUFB";
7559   case X86ISD::FMAX:               return "X86ISD::FMAX";
7560   case X86ISD::FMIN:               return "X86ISD::FMIN";
7561   case X86ISD::FRSQRT:             return "X86ISD::FRSQRT";
7562   case X86ISD::FRCP:               return "X86ISD::FRCP";
7563   case X86ISD::TLSADDR:            return "X86ISD::TLSADDR";
7564   case X86ISD::SegmentBaseAddress: return "X86ISD::SegmentBaseAddress";
7565   case X86ISD::EH_RETURN:          return "X86ISD::EH_RETURN";
7566   case X86ISD::TC_RETURN:          return "X86ISD::TC_RETURN";
7567   case X86ISD::FNSTCW16m:          return "X86ISD::FNSTCW16m";
7568   case X86ISD::LCMPXCHG_DAG:       return "X86ISD::LCMPXCHG_DAG";
7569   case X86ISD::LCMPXCHG8_DAG:      return "X86ISD::LCMPXCHG8_DAG";
7570   case X86ISD::ATOMADD64_DAG:      return "X86ISD::ATOMADD64_DAG";
7571   case X86ISD::ATOMSUB64_DAG:      return "X86ISD::ATOMSUB64_DAG";
7572   case X86ISD::ATOMOR64_DAG:       return "X86ISD::ATOMOR64_DAG";
7573   case X86ISD::ATOMXOR64_DAG:      return "X86ISD::ATOMXOR64_DAG";
7574   case X86ISD::ATOMAND64_DAG:      return "X86ISD::ATOMAND64_DAG";
7575   case X86ISD::ATOMNAND64_DAG:     return "X86ISD::ATOMNAND64_DAG";
7576   case X86ISD::VZEXT_MOVL:         return "X86ISD::VZEXT_MOVL";
7577   case X86ISD::VZEXT_LOAD:         return "X86ISD::VZEXT_LOAD";
7578   case X86ISD::VSHL:               return "X86ISD::VSHL";
7579   case X86ISD::VSRL:               return "X86ISD::VSRL";
7580   case X86ISD::CMPPD:              return "X86ISD::CMPPD";
7581   case X86ISD::CMPPS:              return "X86ISD::CMPPS";
7582   case X86ISD::PCMPEQB:            return "X86ISD::PCMPEQB";
7583   case X86ISD::PCMPEQW:            return "X86ISD::PCMPEQW";
7584   case X86ISD::PCMPEQD:            return "X86ISD::PCMPEQD";
7585   case X86ISD::PCMPEQQ:            return "X86ISD::PCMPEQQ";
7586   case X86ISD::PCMPGTB:            return "X86ISD::PCMPGTB";
7587   case X86ISD::PCMPGTW:            return "X86ISD::PCMPGTW";
7588   case X86ISD::PCMPGTD:            return "X86ISD::PCMPGTD";
7589   case X86ISD::PCMPGTQ:            return "X86ISD::PCMPGTQ";
7590   case X86ISD::ADD:                return "X86ISD::ADD";
7591   case X86ISD::SUB:                return "X86ISD::SUB";
7592   case X86ISD::SMUL:               return "X86ISD::SMUL";
7593   case X86ISD::UMUL:               return "X86ISD::UMUL";
7594   case X86ISD::INC:                return "X86ISD::INC";
7595   case X86ISD::DEC:                return "X86ISD::DEC";
7596   case X86ISD::OR:                 return "X86ISD::OR";
7597   case X86ISD::XOR:                return "X86ISD::XOR";
7598   case X86ISD::AND:                return "X86ISD::AND";
7599   case X86ISD::MUL_IMM:            return "X86ISD::MUL_IMM";
7600   case X86ISD::PTEST:              return "X86ISD::PTEST";
7601   case X86ISD::VASTART_SAVE_XMM_REGS: return "X86ISD::VASTART_SAVE_XMM_REGS";
7602   }
7603 }
7604
7605 // isLegalAddressingMode - Return true if the addressing mode represented
7606 // by AM is legal for this target, for a load/store of the specified type.
7607 bool X86TargetLowering::isLegalAddressingMode(const AddrMode &AM,
7608                                               const Type *Ty) const {
7609   // X86 supports extremely general addressing modes.
7610   CodeModel::Model M = getTargetMachine().getCodeModel();
7611
7612   // X86 allows a sign-extended 32-bit immediate field as a displacement.
7613   if (!X86::isOffsetSuitableForCodeModel(AM.BaseOffs, M, AM.BaseGV != NULL))
7614     return false;
7615
7616   if (AM.BaseGV) {
7617     unsigned GVFlags =
7618       Subtarget->ClassifyGlobalReference(AM.BaseGV, getTargetMachine());
7619
7620     // If a reference to this global requires an extra load, we can't fold it.
7621     if (isGlobalStubReference(GVFlags))
7622       return false;
7623
7624     // If BaseGV requires a register for the PIC base, we cannot also have a
7625     // BaseReg specified.
7626     if (AM.HasBaseReg && isGlobalRelativeToPICBase(GVFlags))
7627       return false;
7628
7629     // If lower 4G is not available, then we must use rip-relative addressing.
7630     if (Subtarget->is64Bit() && (AM.BaseOffs || AM.Scale > 1))
7631       return false;
7632   }
7633
7634   switch (AM.Scale) {
7635   case 0:
7636   case 1:
7637   case 2:
7638   case 4:
7639   case 8:
7640     // These scales always work.
7641     break;
7642   case 3:
7643   case 5:
7644   case 9:
7645     // These scales are formed with basereg+scalereg.  Only accept if there is
7646     // no basereg yet.
7647     if (AM.HasBaseReg)
7648       return false;
7649     break;
7650   default:  // Other stuff never works.
7651     return false;
7652   }
7653
7654   return true;
7655 }
7656
7657
7658 bool X86TargetLowering::isTruncateFree(const Type *Ty1, const Type *Ty2) const {
7659   if (!Ty1->isInteger() || !Ty2->isInteger())
7660     return false;
7661   unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
7662   unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
7663   if (NumBits1 <= NumBits2)
7664     return false;
7665   return Subtarget->is64Bit() || NumBits1 < 64;
7666 }
7667
7668 bool X86TargetLowering::isTruncateFree(EVT VT1, EVT VT2) const {
7669   if (!VT1.isInteger() || !VT2.isInteger())
7670     return false;
7671   unsigned NumBits1 = VT1.getSizeInBits();
7672   unsigned NumBits2 = VT2.getSizeInBits();
7673   if (NumBits1 <= NumBits2)
7674     return false;
7675   return Subtarget->is64Bit() || NumBits1 < 64;
7676 }
7677
7678 bool X86TargetLowering::isZExtFree(const Type *Ty1, const Type *Ty2) const {
7679   // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
7680   return Ty1->isInteger(32) && Ty2->isInteger(64) && Subtarget->is64Bit();
7681 }
7682
7683 bool X86TargetLowering::isZExtFree(EVT VT1, EVT VT2) const {
7684   // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
7685   return VT1 == MVT::i32 && VT2 == MVT::i64 && Subtarget->is64Bit();
7686 }
7687
7688 bool X86TargetLowering::isNarrowingProfitable(EVT VT1, EVT VT2) const {
7689   // i16 instructions are longer (0x66 prefix) and potentially slower.
7690   return !(VT1 == MVT::i32 && VT2 == MVT::i16);
7691 }
7692
7693 /// isShuffleMaskLegal - Targets can use this to indicate that they only
7694 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
7695 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
7696 /// are assumed to be legal.
7697 bool
7698 X86TargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M,
7699                                       EVT VT) const {
7700   // Only do shuffles on 128-bit vector types for now.
7701   if (VT.getSizeInBits() == 64)
7702     return false;
7703
7704   // FIXME: pshufb, blends, shifts.
7705   return (VT.getVectorNumElements() == 2 ||
7706           ShuffleVectorSDNode::isSplatMask(&M[0], VT) ||
7707           isMOVLMask(M, VT) ||
7708           isSHUFPMask(M, VT) ||
7709           isPSHUFDMask(M, VT) ||
7710           isPSHUFHWMask(M, VT) ||
7711           isPSHUFLWMask(M, VT) ||
7712           isPALIGNRMask(M, VT, Subtarget->hasSSSE3()) ||
7713           isUNPCKLMask(M, VT) ||
7714           isUNPCKHMask(M, VT) ||
7715           isUNPCKL_v_undef_Mask(M, VT) ||
7716           isUNPCKH_v_undef_Mask(M, VT));
7717 }
7718
7719 bool
7720 X86TargetLowering::isVectorClearMaskLegal(const SmallVectorImpl<int> &Mask,
7721                                           EVT VT) const {
7722   unsigned NumElts = VT.getVectorNumElements();
7723   // FIXME: This collection of masks seems suspect.
7724   if (NumElts == 2)
7725     return true;
7726   if (NumElts == 4 && VT.getSizeInBits() == 128) {
7727     return (isMOVLMask(Mask, VT)  ||
7728             isCommutedMOVLMask(Mask, VT, true) ||
7729             isSHUFPMask(Mask, VT) ||
7730             isCommutedSHUFPMask(Mask, VT));
7731   }
7732   return false;
7733 }
7734
7735 //===----------------------------------------------------------------------===//
7736 //                           X86 Scheduler Hooks
7737 //===----------------------------------------------------------------------===//
7738
7739 // private utility function
7740 MachineBasicBlock *
7741 X86TargetLowering::EmitAtomicBitwiseWithCustomInserter(MachineInstr *bInstr,
7742                                                        MachineBasicBlock *MBB,
7743                                                        unsigned regOpc,
7744                                                        unsigned immOpc,
7745                                                        unsigned LoadOpc,
7746                                                        unsigned CXchgOpc,
7747                                                        unsigned copyOpc,
7748                                                        unsigned notOpc,
7749                                                        unsigned EAXreg,
7750                                                        TargetRegisterClass *RC,
7751                                                        bool invSrc) const {
7752   // For the atomic bitwise operator, we generate
7753   //   thisMBB:
7754   //   newMBB:
7755   //     ld  t1 = [bitinstr.addr]
7756   //     op  t2 = t1, [bitinstr.val]
7757   //     mov EAX = t1
7758   //     lcs dest = [bitinstr.addr], t2  [EAX is implicit]
7759   //     bz  newMBB
7760   //     fallthrough -->nextMBB
7761   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
7762   const BasicBlock *LLVM_BB = MBB->getBasicBlock();
7763   MachineFunction::iterator MBBIter = MBB;
7764   ++MBBIter;
7765
7766   /// First build the CFG
7767   MachineFunction *F = MBB->getParent();
7768   MachineBasicBlock *thisMBB = MBB;
7769   MachineBasicBlock *newMBB = F->CreateMachineBasicBlock(LLVM_BB);
7770   MachineBasicBlock *nextMBB = F->CreateMachineBasicBlock(LLVM_BB);
7771   F->insert(MBBIter, newMBB);
7772   F->insert(MBBIter, nextMBB);
7773
7774   // Move all successors to thisMBB to nextMBB
7775   nextMBB->transferSuccessors(thisMBB);
7776
7777   // Update thisMBB to fall through to newMBB
7778   thisMBB->addSuccessor(newMBB);
7779
7780   // newMBB jumps to itself and fall through to nextMBB
7781   newMBB->addSuccessor(nextMBB);
7782   newMBB->addSuccessor(newMBB);
7783
7784   // Insert instructions into newMBB based on incoming instruction
7785   assert(bInstr->getNumOperands() < X86AddrNumOperands + 4 &&
7786          "unexpected number of operands");
7787   DebugLoc dl = bInstr->getDebugLoc();
7788   MachineOperand& destOper = bInstr->getOperand(0);
7789   MachineOperand* argOpers[2 + X86AddrNumOperands];
7790   int numArgs = bInstr->getNumOperands() - 1;
7791   for (int i=0; i < numArgs; ++i)
7792     argOpers[i] = &bInstr->getOperand(i+1);
7793
7794   // x86 address has 4 operands: base, index, scale, and displacement
7795   int lastAddrIndx = X86AddrNumOperands - 1; // [0,3]
7796   int valArgIndx = lastAddrIndx + 1;
7797
7798   unsigned t1 = F->getRegInfo().createVirtualRegister(RC);
7799   MachineInstrBuilder MIB = BuildMI(newMBB, dl, TII->get(LoadOpc), t1);
7800   for (int i=0; i <= lastAddrIndx; ++i)
7801     (*MIB).addOperand(*argOpers[i]);
7802
7803   unsigned tt = F->getRegInfo().createVirtualRegister(RC);
7804   if (invSrc) {
7805     MIB = BuildMI(newMBB, dl, TII->get(notOpc), tt).addReg(t1);
7806   }
7807   else
7808     tt = t1;
7809
7810   unsigned t2 = F->getRegInfo().createVirtualRegister(RC);
7811   assert((argOpers[valArgIndx]->isReg() ||
7812           argOpers[valArgIndx]->isImm()) &&
7813          "invalid operand");
7814   if (argOpers[valArgIndx]->isReg())
7815     MIB = BuildMI(newMBB, dl, TII->get(regOpc), t2);
7816   else
7817     MIB = BuildMI(newMBB, dl, TII->get(immOpc), t2);
7818   MIB.addReg(tt);
7819   (*MIB).addOperand(*argOpers[valArgIndx]);
7820
7821   MIB = BuildMI(newMBB, dl, TII->get(copyOpc), EAXreg);
7822   MIB.addReg(t1);
7823
7824   MIB = BuildMI(newMBB, dl, TII->get(CXchgOpc));
7825   for (int i=0; i <= lastAddrIndx; ++i)
7826     (*MIB).addOperand(*argOpers[i]);
7827   MIB.addReg(t2);
7828   assert(bInstr->hasOneMemOperand() && "Unexpected number of memoperand");
7829   (*MIB).setMemRefs(bInstr->memoperands_begin(),
7830                     bInstr->memoperands_end());
7831
7832   MIB = BuildMI(newMBB, dl, TII->get(copyOpc), destOper.getReg());
7833   MIB.addReg(EAXreg);
7834
7835   // insert branch
7836   BuildMI(newMBB, dl, TII->get(X86::JNE)).addMBB(newMBB);
7837
7838   F->DeleteMachineInstr(bInstr);   // The pseudo instruction is gone now.
7839   return nextMBB;
7840 }
7841
7842 // private utility function:  64 bit atomics on 32 bit host.
7843 MachineBasicBlock *
7844 X86TargetLowering::EmitAtomicBit6432WithCustomInserter(MachineInstr *bInstr,
7845                                                        MachineBasicBlock *MBB,
7846                                                        unsigned regOpcL,
7847                                                        unsigned regOpcH,
7848                                                        unsigned immOpcL,
7849                                                        unsigned immOpcH,
7850                                                        bool invSrc) const {
7851   // For the atomic bitwise operator, we generate
7852   //   thisMBB (instructions are in pairs, except cmpxchg8b)
7853   //     ld t1,t2 = [bitinstr.addr]
7854   //   newMBB:
7855   //     out1, out2 = phi (thisMBB, t1/t2) (newMBB, t3/t4)
7856   //     op  t5, t6 <- out1, out2, [bitinstr.val]
7857   //      (for SWAP, substitute:  mov t5, t6 <- [bitinstr.val])
7858   //     mov ECX, EBX <- t5, t6
7859   //     mov EAX, EDX <- t1, t2
7860   //     cmpxchg8b [bitinstr.addr]  [EAX, EDX, EBX, ECX implicit]
7861   //     mov t3, t4 <- EAX, EDX
7862   //     bz  newMBB
7863   //     result in out1, out2
7864   //     fallthrough -->nextMBB
7865
7866   const TargetRegisterClass *RC = X86::GR32RegisterClass;
7867   const unsigned LoadOpc = X86::MOV32rm;
7868   const unsigned copyOpc = X86::MOV32rr;
7869   const unsigned NotOpc = X86::NOT32r;
7870   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
7871   const BasicBlock *LLVM_BB = MBB->getBasicBlock();
7872   MachineFunction::iterator MBBIter = MBB;
7873   ++MBBIter;
7874
7875   /// First build the CFG
7876   MachineFunction *F = MBB->getParent();
7877   MachineBasicBlock *thisMBB = MBB;
7878   MachineBasicBlock *newMBB = F->CreateMachineBasicBlock(LLVM_BB);
7879   MachineBasicBlock *nextMBB = F->CreateMachineBasicBlock(LLVM_BB);
7880   F->insert(MBBIter, newMBB);
7881   F->insert(MBBIter, nextMBB);
7882
7883   // Move all successors to thisMBB to nextMBB
7884   nextMBB->transferSuccessors(thisMBB);
7885
7886   // Update thisMBB to fall through to newMBB
7887   thisMBB->addSuccessor(newMBB);
7888
7889   // newMBB jumps to itself and fall through to nextMBB
7890   newMBB->addSuccessor(nextMBB);
7891   newMBB->addSuccessor(newMBB);
7892
7893   DebugLoc dl = bInstr->getDebugLoc();
7894   // Insert instructions into newMBB based on incoming instruction
7895   // There are 8 "real" operands plus 9 implicit def/uses, ignored here.
7896   assert(bInstr->getNumOperands() < X86AddrNumOperands + 14 &&
7897          "unexpected number of operands");
7898   MachineOperand& dest1Oper = bInstr->getOperand(0);
7899   MachineOperand& dest2Oper = bInstr->getOperand(1);
7900   MachineOperand* argOpers[2 + X86AddrNumOperands];
7901   for (int i=0; i < 2 + X86AddrNumOperands; ++i)
7902     argOpers[i] = &bInstr->getOperand(i+2);
7903
7904   // x86 address has 5 operands: base, index, scale, displacement, and segment.
7905   int lastAddrIndx = X86AddrNumOperands - 1; // [0,3]
7906
7907   unsigned t1 = F->getRegInfo().createVirtualRegister(RC);
7908   MachineInstrBuilder MIB = BuildMI(thisMBB, dl, TII->get(LoadOpc), t1);
7909   for (int i=0; i <= lastAddrIndx; ++i)
7910     (*MIB).addOperand(*argOpers[i]);
7911   unsigned t2 = F->getRegInfo().createVirtualRegister(RC);
7912   MIB = BuildMI(thisMBB, dl, TII->get(LoadOpc), t2);
7913   // add 4 to displacement.
7914   for (int i=0; i <= lastAddrIndx-2; ++i)
7915     (*MIB).addOperand(*argOpers[i]);
7916   MachineOperand newOp3 = *(argOpers[3]);
7917   if (newOp3.isImm())
7918     newOp3.setImm(newOp3.getImm()+4);
7919   else
7920     newOp3.setOffset(newOp3.getOffset()+4);
7921   (*MIB).addOperand(newOp3);
7922   (*MIB).addOperand(*argOpers[lastAddrIndx]);
7923
7924   // t3/4 are defined later, at the bottom of the loop
7925   unsigned t3 = F->getRegInfo().createVirtualRegister(RC);
7926   unsigned t4 = F->getRegInfo().createVirtualRegister(RC);
7927   BuildMI(newMBB, dl, TII->get(X86::PHI), dest1Oper.getReg())
7928     .addReg(t1).addMBB(thisMBB).addReg(t3).addMBB(newMBB);
7929   BuildMI(newMBB, dl, TII->get(X86::PHI), dest2Oper.getReg())
7930     .addReg(t2).addMBB(thisMBB).addReg(t4).addMBB(newMBB);
7931
7932   // The subsequent operations should be using the destination registers of
7933   //the PHI instructions.
7934   if (invSrc) {
7935     t1 = F->getRegInfo().createVirtualRegister(RC);
7936     t2 = F->getRegInfo().createVirtualRegister(RC);
7937     MIB = BuildMI(newMBB, dl, TII->get(NotOpc), t1).addReg(dest1Oper.getReg());
7938     MIB = BuildMI(newMBB, dl, TII->get(NotOpc), t2).addReg(dest2Oper.getReg());
7939   } else {
7940     t1 = dest1Oper.getReg();
7941     t2 = dest2Oper.getReg();
7942   }
7943
7944   int valArgIndx = lastAddrIndx + 1;
7945   assert((argOpers[valArgIndx]->isReg() ||
7946           argOpers[valArgIndx]->isImm()) &&
7947          "invalid operand");
7948   unsigned t5 = F->getRegInfo().createVirtualRegister(RC);
7949   unsigned t6 = F->getRegInfo().createVirtualRegister(RC);
7950   if (argOpers[valArgIndx]->isReg())
7951     MIB = BuildMI(newMBB, dl, TII->get(regOpcL), t5);
7952   else
7953     MIB = BuildMI(newMBB, dl, TII->get(immOpcL), t5);
7954   if (regOpcL != X86::MOV32rr)
7955     MIB.addReg(t1);
7956   (*MIB).addOperand(*argOpers[valArgIndx]);
7957   assert(argOpers[valArgIndx + 1]->isReg() ==
7958          argOpers[valArgIndx]->isReg());
7959   assert(argOpers[valArgIndx + 1]->isImm() ==
7960          argOpers[valArgIndx]->isImm());
7961   if (argOpers[valArgIndx + 1]->isReg())
7962     MIB = BuildMI(newMBB, dl, TII->get(regOpcH), t6);
7963   else
7964     MIB = BuildMI(newMBB, dl, TII->get(immOpcH), t6);
7965   if (regOpcH != X86::MOV32rr)
7966     MIB.addReg(t2);
7967   (*MIB).addOperand(*argOpers[valArgIndx + 1]);
7968
7969   MIB = BuildMI(newMBB, dl, TII->get(copyOpc), X86::EAX);
7970   MIB.addReg(t1);
7971   MIB = BuildMI(newMBB, dl, TII->get(copyOpc), X86::EDX);
7972   MIB.addReg(t2);
7973
7974   MIB = BuildMI(newMBB, dl, TII->get(copyOpc), X86::EBX);
7975   MIB.addReg(t5);
7976   MIB = BuildMI(newMBB, dl, TII->get(copyOpc), X86::ECX);
7977   MIB.addReg(t6);
7978
7979   MIB = BuildMI(newMBB, dl, TII->get(X86::LCMPXCHG8B));
7980   for (int i=0; i <= lastAddrIndx; ++i)
7981     (*MIB).addOperand(*argOpers[i]);
7982
7983   assert(bInstr->hasOneMemOperand() && "Unexpected number of memoperand");
7984   (*MIB).setMemRefs(bInstr->memoperands_begin(),
7985                     bInstr->memoperands_end());
7986
7987   MIB = BuildMI(newMBB, dl, TII->get(copyOpc), t3);
7988   MIB.addReg(X86::EAX);
7989   MIB = BuildMI(newMBB, dl, TII->get(copyOpc), t4);
7990   MIB.addReg(X86::EDX);
7991
7992   // insert branch
7993   BuildMI(newMBB, dl, TII->get(X86::JNE)).addMBB(newMBB);
7994
7995   F->DeleteMachineInstr(bInstr);   // The pseudo instruction is gone now.
7996   return nextMBB;
7997 }
7998
7999 // private utility function
8000 MachineBasicBlock *
8001 X86TargetLowering::EmitAtomicMinMaxWithCustomInserter(MachineInstr *mInstr,
8002                                                       MachineBasicBlock *MBB,
8003                                                       unsigned cmovOpc) const {
8004   // For the atomic min/max operator, we generate
8005   //   thisMBB:
8006   //   newMBB:
8007   //     ld t1 = [min/max.addr]
8008   //     mov t2 = [min/max.val]
8009   //     cmp  t1, t2
8010   //     cmov[cond] t2 = t1
8011   //     mov EAX = t1
8012   //     lcs dest = [bitinstr.addr], t2  [EAX is implicit]
8013   //     bz   newMBB
8014   //     fallthrough -->nextMBB
8015   //
8016   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
8017   const BasicBlock *LLVM_BB = MBB->getBasicBlock();
8018   MachineFunction::iterator MBBIter = MBB;
8019   ++MBBIter;
8020
8021   /// First build the CFG
8022   MachineFunction *F = MBB->getParent();
8023   MachineBasicBlock *thisMBB = MBB;
8024   MachineBasicBlock *newMBB = F->CreateMachineBasicBlock(LLVM_BB);
8025   MachineBasicBlock *nextMBB = F->CreateMachineBasicBlock(LLVM_BB);
8026   F->insert(MBBIter, newMBB);
8027   F->insert(MBBIter, nextMBB);
8028
8029   // Move all successors of thisMBB to nextMBB
8030   nextMBB->transferSuccessors(thisMBB);
8031
8032   // Update thisMBB to fall through to newMBB
8033   thisMBB->addSuccessor(newMBB);
8034
8035   // newMBB jumps to newMBB and fall through to nextMBB
8036   newMBB->addSuccessor(nextMBB);
8037   newMBB->addSuccessor(newMBB);
8038
8039   DebugLoc dl = mInstr->getDebugLoc();
8040   // Insert instructions into newMBB based on incoming instruction
8041   assert(mInstr->getNumOperands() < X86AddrNumOperands + 4 &&
8042          "unexpected number of operands");
8043   MachineOperand& destOper = mInstr->getOperand(0);
8044   MachineOperand* argOpers[2 + X86AddrNumOperands];
8045   int numArgs = mInstr->getNumOperands() - 1;
8046   for (int i=0; i < numArgs; ++i)
8047     argOpers[i] = &mInstr->getOperand(i+1);
8048
8049   // x86 address has 4 operands: base, index, scale, and displacement
8050   int lastAddrIndx = X86AddrNumOperands - 1; // [0,3]
8051   int valArgIndx = lastAddrIndx + 1;
8052
8053   unsigned t1 = F->getRegInfo().createVirtualRegister(X86::GR32RegisterClass);
8054   MachineInstrBuilder MIB = BuildMI(newMBB, dl, TII->get(X86::MOV32rm), t1);
8055   for (int i=0; i <= lastAddrIndx; ++i)
8056     (*MIB).addOperand(*argOpers[i]);
8057
8058   // We only support register and immediate values
8059   assert((argOpers[valArgIndx]->isReg() ||
8060           argOpers[valArgIndx]->isImm()) &&
8061          "invalid operand");
8062
8063   unsigned t2 = F->getRegInfo().createVirtualRegister(X86::GR32RegisterClass);
8064   if (argOpers[valArgIndx]->isReg())
8065     MIB = BuildMI(newMBB, dl, TII->get(X86::MOV32rr), t2);
8066   else
8067     MIB = BuildMI(newMBB, dl, TII->get(X86::MOV32rr), t2);
8068   (*MIB).addOperand(*argOpers[valArgIndx]);
8069
8070   MIB = BuildMI(newMBB, dl, TII->get(X86::MOV32rr), X86::EAX);
8071   MIB.addReg(t1);
8072
8073   MIB = BuildMI(newMBB, dl, TII->get(X86::CMP32rr));
8074   MIB.addReg(t1);
8075   MIB.addReg(t2);
8076
8077   // Generate movc
8078   unsigned t3 = F->getRegInfo().createVirtualRegister(X86::GR32RegisterClass);
8079   MIB = BuildMI(newMBB, dl, TII->get(cmovOpc),t3);
8080   MIB.addReg(t2);
8081   MIB.addReg(t1);
8082
8083   // Cmp and exchange if none has modified the memory location
8084   MIB = BuildMI(newMBB, dl, TII->get(X86::LCMPXCHG32));
8085   for (int i=0; i <= lastAddrIndx; ++i)
8086     (*MIB).addOperand(*argOpers[i]);
8087   MIB.addReg(t3);
8088   assert(mInstr->hasOneMemOperand() && "Unexpected number of memoperand");
8089   (*MIB).setMemRefs(mInstr->memoperands_begin(),
8090                     mInstr->memoperands_end());
8091
8092   MIB = BuildMI(newMBB, dl, TII->get(X86::MOV32rr), destOper.getReg());
8093   MIB.addReg(X86::EAX);
8094
8095   // insert branch
8096   BuildMI(newMBB, dl, TII->get(X86::JNE)).addMBB(newMBB);
8097
8098   F->DeleteMachineInstr(mInstr);   // The pseudo instruction is gone now.
8099   return nextMBB;
8100 }
8101
8102 // FIXME: When we get size specific XMM0 registers, i.e. XMM0_V16I8
8103 // all of this code can be replaced with that in the .td file.
8104 MachineBasicBlock *
8105 X86TargetLowering::EmitPCMP(MachineInstr *MI, MachineBasicBlock *BB,
8106                             unsigned numArgs, bool memArg) const {
8107
8108   MachineFunction *F = BB->getParent();
8109   DebugLoc dl = MI->getDebugLoc();
8110   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
8111
8112   unsigned Opc;
8113   if (memArg)
8114     Opc = numArgs == 3 ? X86::PCMPISTRM128rm : X86::PCMPESTRM128rm;
8115   else
8116     Opc = numArgs == 3 ? X86::PCMPISTRM128rr : X86::PCMPESTRM128rr;
8117
8118   MachineInstrBuilder MIB = BuildMI(BB, dl, TII->get(Opc));
8119
8120   for (unsigned i = 0; i < numArgs; ++i) {
8121     MachineOperand &Op = MI->getOperand(i+1);
8122
8123     if (!(Op.isReg() && Op.isImplicit()))
8124       MIB.addOperand(Op);
8125   }
8126
8127   BuildMI(BB, dl, TII->get(X86::MOVAPSrr), MI->getOperand(0).getReg())
8128     .addReg(X86::XMM0);
8129
8130   F->DeleteMachineInstr(MI);
8131
8132   return BB;
8133 }
8134
8135 MachineBasicBlock *
8136 X86TargetLowering::EmitVAStartSaveXMMRegsWithCustomInserter(
8137                                                  MachineInstr *MI,
8138                                                  MachineBasicBlock *MBB) const {
8139   // Emit code to save XMM registers to the stack. The ABI says that the
8140   // number of registers to save is given in %al, so it's theoretically
8141   // possible to do an indirect jump trick to avoid saving all of them,
8142   // however this code takes a simpler approach and just executes all
8143   // of the stores if %al is non-zero. It's less code, and it's probably
8144   // easier on the hardware branch predictor, and stores aren't all that
8145   // expensive anyway.
8146
8147   // Create the new basic blocks. One block contains all the XMM stores,
8148   // and one block is the final destination regardless of whether any
8149   // stores were performed.
8150   const BasicBlock *LLVM_BB = MBB->getBasicBlock();
8151   MachineFunction *F = MBB->getParent();
8152   MachineFunction::iterator MBBIter = MBB;
8153   ++MBBIter;
8154   MachineBasicBlock *XMMSaveMBB = F->CreateMachineBasicBlock(LLVM_BB);
8155   MachineBasicBlock *EndMBB = F->CreateMachineBasicBlock(LLVM_BB);
8156   F->insert(MBBIter, XMMSaveMBB);
8157   F->insert(MBBIter, EndMBB);
8158
8159   // Set up the CFG.
8160   // Move any original successors of MBB to the end block.
8161   EndMBB->transferSuccessors(MBB);
8162   // The original block will now fall through to the XMM save block.
8163   MBB->addSuccessor(XMMSaveMBB);
8164   // The XMMSaveMBB will fall through to the end block.
8165   XMMSaveMBB->addSuccessor(EndMBB);
8166
8167   // Now add the instructions.
8168   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
8169   DebugLoc DL = MI->getDebugLoc();
8170
8171   unsigned CountReg = MI->getOperand(0).getReg();
8172   int64_t RegSaveFrameIndex = MI->getOperand(1).getImm();
8173   int64_t VarArgsFPOffset = MI->getOperand(2).getImm();
8174
8175   if (!Subtarget->isTargetWin64()) {
8176     // If %al is 0, branch around the XMM save block.
8177     BuildMI(MBB, DL, TII->get(X86::TEST8rr)).addReg(CountReg).addReg(CountReg);
8178     BuildMI(MBB, DL, TII->get(X86::JE)).addMBB(EndMBB);
8179     MBB->addSuccessor(EndMBB);
8180   }
8181
8182   // In the XMM save block, save all the XMM argument registers.
8183   for (int i = 3, e = MI->getNumOperands(); i != e; ++i) {
8184     int64_t Offset = (i - 3) * 16 + VarArgsFPOffset;
8185     MachineMemOperand *MMO =
8186       F->getMachineMemOperand(
8187         PseudoSourceValue::getFixedStack(RegSaveFrameIndex),
8188         MachineMemOperand::MOStore, Offset,
8189         /*Size=*/16, /*Align=*/16);
8190     BuildMI(XMMSaveMBB, DL, TII->get(X86::MOVAPSmr))
8191       .addFrameIndex(RegSaveFrameIndex)
8192       .addImm(/*Scale=*/1)
8193       .addReg(/*IndexReg=*/0)
8194       .addImm(/*Disp=*/Offset)
8195       .addReg(/*Segment=*/0)
8196       .addReg(MI->getOperand(i).getReg())
8197       .addMemOperand(MMO);
8198   }
8199
8200   F->DeleteMachineInstr(MI);   // The pseudo instruction is gone now.
8201
8202   return EndMBB;
8203 }
8204
8205 MachineBasicBlock *
8206 X86TargetLowering::EmitLoweredSelect(MachineInstr *MI,
8207                                      MachineBasicBlock *BB,
8208                    DenseMap<MachineBasicBlock*, MachineBasicBlock*> *EM) const {
8209   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
8210   DebugLoc DL = MI->getDebugLoc();
8211
8212   // To "insert" a SELECT_CC instruction, we actually have to insert the
8213   // diamond control-flow pattern.  The incoming instruction knows the
8214   // destination vreg to set, the condition code register to branch on, the
8215   // true/false values to select between, and a branch opcode to use.
8216   const BasicBlock *LLVM_BB = BB->getBasicBlock();
8217   MachineFunction::iterator It = BB;
8218   ++It;
8219
8220   //  thisMBB:
8221   //  ...
8222   //   TrueVal = ...
8223   //   cmpTY ccX, r1, r2
8224   //   bCC copy1MBB
8225   //   fallthrough --> copy0MBB
8226   MachineBasicBlock *thisMBB = BB;
8227   MachineFunction *F = BB->getParent();
8228   MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
8229   MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
8230   unsigned Opc =
8231     X86::GetCondBranchFromCond((X86::CondCode)MI->getOperand(3).getImm());
8232   BuildMI(BB, DL, TII->get(Opc)).addMBB(sinkMBB);
8233   F->insert(It, copy0MBB);
8234   F->insert(It, sinkMBB);
8235   // Update machine-CFG edges by first adding all successors of the current
8236   // block to the new block which will contain the Phi node for the select.
8237   // Also inform sdisel of the edge changes.
8238   for (MachineBasicBlock::succ_iterator I = BB->succ_begin(),
8239          E = BB->succ_end(); I != E; ++I) {
8240     EM->insert(std::make_pair(*I, sinkMBB));
8241     sinkMBB->addSuccessor(*I);
8242   }
8243   // Next, remove all successors of the current block, and add the true
8244   // and fallthrough blocks as its successors.
8245   while (!BB->succ_empty())
8246     BB->removeSuccessor(BB->succ_begin());
8247   // Add the true and fallthrough blocks as its successors.
8248   BB->addSuccessor(copy0MBB);
8249   BB->addSuccessor(sinkMBB);
8250
8251   //  copy0MBB:
8252   //   %FalseValue = ...
8253   //   # fallthrough to sinkMBB
8254   BB = copy0MBB;
8255
8256   // Update machine-CFG edges
8257   BB->addSuccessor(sinkMBB);
8258
8259   //  sinkMBB:
8260   //   %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
8261   //  ...
8262   BB = sinkMBB;
8263   BuildMI(BB, DL, TII->get(X86::PHI), MI->getOperand(0).getReg())
8264     .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB)
8265     .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
8266
8267   F->DeleteMachineInstr(MI);   // The pseudo instruction is gone now.
8268   return BB;
8269 }
8270
8271
8272 MachineBasicBlock *
8273 X86TargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
8274                                                MachineBasicBlock *BB,
8275                    DenseMap<MachineBasicBlock*, MachineBasicBlock*> *EM) const {
8276   switch (MI->getOpcode()) {
8277   default: assert(false && "Unexpected instr type to insert");
8278   case X86::CMOV_GR8:
8279   case X86::CMOV_V1I64:
8280   case X86::CMOV_FR32:
8281   case X86::CMOV_FR64:
8282   case X86::CMOV_V4F32:
8283   case X86::CMOV_V2F64:
8284   case X86::CMOV_V2I64:
8285     return EmitLoweredSelect(MI, BB, EM);
8286
8287   case X86::FP32_TO_INT16_IN_MEM:
8288   case X86::FP32_TO_INT32_IN_MEM:
8289   case X86::FP32_TO_INT64_IN_MEM:
8290   case X86::FP64_TO_INT16_IN_MEM:
8291   case X86::FP64_TO_INT32_IN_MEM:
8292   case X86::FP64_TO_INT64_IN_MEM:
8293   case X86::FP80_TO_INT16_IN_MEM:
8294   case X86::FP80_TO_INT32_IN_MEM:
8295   case X86::FP80_TO_INT64_IN_MEM: {
8296     const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
8297     DebugLoc DL = MI->getDebugLoc();
8298
8299     // Change the floating point control register to use "round towards zero"
8300     // mode when truncating to an integer value.
8301     MachineFunction *F = BB->getParent();
8302     int CWFrameIdx = F->getFrameInfo()->CreateStackObject(2, 2, false);
8303     addFrameReference(BuildMI(BB, DL, TII->get(X86::FNSTCW16m)), CWFrameIdx);
8304
8305     // Load the old value of the high byte of the control word...
8306     unsigned OldCW =
8307       F->getRegInfo().createVirtualRegister(X86::GR16RegisterClass);
8308     addFrameReference(BuildMI(BB, DL, TII->get(X86::MOV16rm), OldCW),
8309                       CWFrameIdx);
8310
8311     // Set the high part to be round to zero...
8312     addFrameReference(BuildMI(BB, DL, TII->get(X86::MOV16mi)), CWFrameIdx)
8313       .addImm(0xC7F);
8314
8315     // Reload the modified control word now...
8316     addFrameReference(BuildMI(BB, DL, TII->get(X86::FLDCW16m)), CWFrameIdx);
8317
8318     // Restore the memory image of control word to original value
8319     addFrameReference(BuildMI(BB, DL, TII->get(X86::MOV16mr)), CWFrameIdx)
8320       .addReg(OldCW);
8321
8322     // Get the X86 opcode to use.
8323     unsigned Opc;
8324     switch (MI->getOpcode()) {
8325     default: llvm_unreachable("illegal opcode!");
8326     case X86::FP32_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m32; break;
8327     case X86::FP32_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m32; break;
8328     case X86::FP32_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m32; break;
8329     case X86::FP64_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m64; break;
8330     case X86::FP64_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m64; break;
8331     case X86::FP64_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m64; break;
8332     case X86::FP80_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m80; break;
8333     case X86::FP80_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m80; break;
8334     case X86::FP80_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m80; break;
8335     }
8336
8337     X86AddressMode AM;
8338     MachineOperand &Op = MI->getOperand(0);
8339     if (Op.isReg()) {
8340       AM.BaseType = X86AddressMode::RegBase;
8341       AM.Base.Reg = Op.getReg();
8342     } else {
8343       AM.BaseType = X86AddressMode::FrameIndexBase;
8344       AM.Base.FrameIndex = Op.getIndex();
8345     }
8346     Op = MI->getOperand(1);
8347     if (Op.isImm())
8348       AM.Scale = Op.getImm();
8349     Op = MI->getOperand(2);
8350     if (Op.isImm())
8351       AM.IndexReg = Op.getImm();
8352     Op = MI->getOperand(3);
8353     if (Op.isGlobal()) {
8354       AM.GV = Op.getGlobal();
8355     } else {
8356       AM.Disp = Op.getImm();
8357     }
8358     addFullAddress(BuildMI(BB, DL, TII->get(Opc)), AM)
8359                       .addReg(MI->getOperand(X86AddrNumOperands).getReg());
8360
8361     // Reload the original control word now.
8362     addFrameReference(BuildMI(BB, DL, TII->get(X86::FLDCW16m)), CWFrameIdx);
8363
8364     F->DeleteMachineInstr(MI);   // The pseudo instruction is gone now.
8365     return BB;
8366   }
8367     // String/text processing lowering.
8368   case X86::PCMPISTRM128REG:
8369     return EmitPCMP(MI, BB, 3, false /* in-mem */);
8370   case X86::PCMPISTRM128MEM:
8371     return EmitPCMP(MI, BB, 3, true /* in-mem */);
8372   case X86::PCMPESTRM128REG:
8373     return EmitPCMP(MI, BB, 5, false /* in mem */);
8374   case X86::PCMPESTRM128MEM:
8375     return EmitPCMP(MI, BB, 5, true /* in mem */);
8376
8377     // Atomic Lowering.
8378   case X86::ATOMAND32:
8379     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND32rr,
8380                                                X86::AND32ri, X86::MOV32rm,
8381                                                X86::LCMPXCHG32, X86::MOV32rr,
8382                                                X86::NOT32r, X86::EAX,
8383                                                X86::GR32RegisterClass);
8384   case X86::ATOMOR32:
8385     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR32rr,
8386                                                X86::OR32ri, X86::MOV32rm,
8387                                                X86::LCMPXCHG32, X86::MOV32rr,
8388                                                X86::NOT32r, X86::EAX,
8389                                                X86::GR32RegisterClass);
8390   case X86::ATOMXOR32:
8391     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR32rr,
8392                                                X86::XOR32ri, X86::MOV32rm,
8393                                                X86::LCMPXCHG32, X86::MOV32rr,
8394                                                X86::NOT32r, X86::EAX,
8395                                                X86::GR32RegisterClass);
8396   case X86::ATOMNAND32:
8397     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND32rr,
8398                                                X86::AND32ri, X86::MOV32rm,
8399                                                X86::LCMPXCHG32, X86::MOV32rr,
8400                                                X86::NOT32r, X86::EAX,
8401                                                X86::GR32RegisterClass, true);
8402   case X86::ATOMMIN32:
8403     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVL32rr);
8404   case X86::ATOMMAX32:
8405     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVG32rr);
8406   case X86::ATOMUMIN32:
8407     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVB32rr);
8408   case X86::ATOMUMAX32:
8409     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVA32rr);
8410
8411   case X86::ATOMAND16:
8412     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND16rr,
8413                                                X86::AND16ri, X86::MOV16rm,
8414                                                X86::LCMPXCHG16, X86::MOV16rr,
8415                                                X86::NOT16r, X86::AX,
8416                                                X86::GR16RegisterClass);
8417   case X86::ATOMOR16:
8418     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR16rr,
8419                                                X86::OR16ri, X86::MOV16rm,
8420                                                X86::LCMPXCHG16, X86::MOV16rr,
8421                                                X86::NOT16r, X86::AX,
8422                                                X86::GR16RegisterClass);
8423   case X86::ATOMXOR16:
8424     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR16rr,
8425                                                X86::XOR16ri, X86::MOV16rm,
8426                                                X86::LCMPXCHG16, X86::MOV16rr,
8427                                                X86::NOT16r, X86::AX,
8428                                                X86::GR16RegisterClass);
8429   case X86::ATOMNAND16:
8430     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND16rr,
8431                                                X86::AND16ri, X86::MOV16rm,
8432                                                X86::LCMPXCHG16, X86::MOV16rr,
8433                                                X86::NOT16r, X86::AX,
8434                                                X86::GR16RegisterClass, true);
8435   case X86::ATOMMIN16:
8436     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVL16rr);
8437   case X86::ATOMMAX16:
8438     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVG16rr);
8439   case X86::ATOMUMIN16:
8440     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVB16rr);
8441   case X86::ATOMUMAX16:
8442     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVA16rr);
8443
8444   case X86::ATOMAND8:
8445     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND8rr,
8446                                                X86::AND8ri, X86::MOV8rm,
8447                                                X86::LCMPXCHG8, X86::MOV8rr,
8448                                                X86::NOT8r, X86::AL,
8449                                                X86::GR8RegisterClass);
8450   case X86::ATOMOR8:
8451     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR8rr,
8452                                                X86::OR8ri, X86::MOV8rm,
8453                                                X86::LCMPXCHG8, X86::MOV8rr,
8454                                                X86::NOT8r, X86::AL,
8455                                                X86::GR8RegisterClass);
8456   case X86::ATOMXOR8:
8457     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR8rr,
8458                                                X86::XOR8ri, X86::MOV8rm,
8459                                                X86::LCMPXCHG8, X86::MOV8rr,
8460                                                X86::NOT8r, X86::AL,
8461                                                X86::GR8RegisterClass);
8462   case X86::ATOMNAND8:
8463     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND8rr,
8464                                                X86::AND8ri, X86::MOV8rm,
8465                                                X86::LCMPXCHG8, X86::MOV8rr,
8466                                                X86::NOT8r, X86::AL,
8467                                                X86::GR8RegisterClass, true);
8468   // FIXME: There are no CMOV8 instructions; MIN/MAX need some other way.
8469   // This group is for 64-bit host.
8470   case X86::ATOMAND64:
8471     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND64rr,
8472                                                X86::AND64ri32, X86::MOV64rm,
8473                                                X86::LCMPXCHG64, X86::MOV64rr,
8474                                                X86::NOT64r, X86::RAX,
8475                                                X86::GR64RegisterClass);
8476   case X86::ATOMOR64:
8477     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR64rr,
8478                                                X86::OR64ri32, X86::MOV64rm,
8479                                                X86::LCMPXCHG64, X86::MOV64rr,
8480                                                X86::NOT64r, X86::RAX,
8481                                                X86::GR64RegisterClass);
8482   case X86::ATOMXOR64:
8483     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR64rr,
8484                                                X86::XOR64ri32, X86::MOV64rm,
8485                                                X86::LCMPXCHG64, X86::MOV64rr,
8486                                                X86::NOT64r, X86::RAX,
8487                                                X86::GR64RegisterClass);
8488   case X86::ATOMNAND64:
8489     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND64rr,
8490                                                X86::AND64ri32, X86::MOV64rm,
8491                                                X86::LCMPXCHG64, X86::MOV64rr,
8492                                                X86::NOT64r, X86::RAX,
8493                                                X86::GR64RegisterClass, true);
8494   case X86::ATOMMIN64:
8495     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVL64rr);
8496   case X86::ATOMMAX64:
8497     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVG64rr);
8498   case X86::ATOMUMIN64:
8499     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVB64rr);
8500   case X86::ATOMUMAX64:
8501     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVA64rr);
8502
8503   // This group does 64-bit operations on a 32-bit host.
8504   case X86::ATOMAND6432:
8505     return EmitAtomicBit6432WithCustomInserter(MI, BB,
8506                                                X86::AND32rr, X86::AND32rr,
8507                                                X86::AND32ri, X86::AND32ri,
8508                                                false);
8509   case X86::ATOMOR6432:
8510     return EmitAtomicBit6432WithCustomInserter(MI, BB,
8511                                                X86::OR32rr, X86::OR32rr,
8512                                                X86::OR32ri, X86::OR32ri,
8513                                                false);
8514   case X86::ATOMXOR6432:
8515     return EmitAtomicBit6432WithCustomInserter(MI, BB,
8516                                                X86::XOR32rr, X86::XOR32rr,
8517                                                X86::XOR32ri, X86::XOR32ri,
8518                                                false);
8519   case X86::ATOMNAND6432:
8520     return EmitAtomicBit6432WithCustomInserter(MI, BB,
8521                                                X86::AND32rr, X86::AND32rr,
8522                                                X86::AND32ri, X86::AND32ri,
8523                                                true);
8524   case X86::ATOMADD6432:
8525     return EmitAtomicBit6432WithCustomInserter(MI, BB,
8526                                                X86::ADD32rr, X86::ADC32rr,
8527                                                X86::ADD32ri, X86::ADC32ri,
8528                                                false);
8529   case X86::ATOMSUB6432:
8530     return EmitAtomicBit6432WithCustomInserter(MI, BB,
8531                                                X86::SUB32rr, X86::SBB32rr,
8532                                                X86::SUB32ri, X86::SBB32ri,
8533                                                false);
8534   case X86::ATOMSWAP6432:
8535     return EmitAtomicBit6432WithCustomInserter(MI, BB,
8536                                                X86::MOV32rr, X86::MOV32rr,
8537                                                X86::MOV32ri, X86::MOV32ri,
8538                                                false);
8539   case X86::VASTART_SAVE_XMM_REGS:
8540     return EmitVAStartSaveXMMRegsWithCustomInserter(MI, BB);
8541   }
8542 }
8543
8544 //===----------------------------------------------------------------------===//
8545 //                           X86 Optimization Hooks
8546 //===----------------------------------------------------------------------===//
8547
8548 void X86TargetLowering::computeMaskedBitsForTargetNode(const SDValue Op,
8549                                                        const APInt &Mask,
8550                                                        APInt &KnownZero,
8551                                                        APInt &KnownOne,
8552                                                        const SelectionDAG &DAG,
8553                                                        unsigned Depth) const {
8554   unsigned Opc = Op.getOpcode();
8555   assert((Opc >= ISD::BUILTIN_OP_END ||
8556           Opc == ISD::INTRINSIC_WO_CHAIN ||
8557           Opc == ISD::INTRINSIC_W_CHAIN ||
8558           Opc == ISD::INTRINSIC_VOID) &&
8559          "Should use MaskedValueIsZero if you don't know whether Op"
8560          " is a target node!");
8561
8562   KnownZero = KnownOne = APInt(Mask.getBitWidth(), 0);   // Don't know anything.
8563   switch (Opc) {
8564   default: break;
8565   case X86ISD::ADD:
8566   case X86ISD::SUB:
8567   case X86ISD::SMUL:
8568   case X86ISD::UMUL:
8569   case X86ISD::INC:
8570   case X86ISD::DEC:
8571   case X86ISD::OR:
8572   case X86ISD::XOR:
8573   case X86ISD::AND:
8574     // These nodes' second result is a boolean.
8575     if (Op.getResNo() == 0)
8576       break;
8577     // Fallthrough
8578   case X86ISD::SETCC:
8579     KnownZero |= APInt::getHighBitsSet(Mask.getBitWidth(),
8580                                        Mask.getBitWidth() - 1);
8581     break;
8582   }
8583 }
8584
8585 /// isGAPlusOffset - Returns true (and the GlobalValue and the offset) if the
8586 /// node is a GlobalAddress + offset.
8587 bool X86TargetLowering::isGAPlusOffset(SDNode *N,
8588                                        GlobalValue* &GA, int64_t &Offset) const{
8589   if (N->getOpcode() == X86ISD::Wrapper) {
8590     if (isa<GlobalAddressSDNode>(N->getOperand(0))) {
8591       GA = cast<GlobalAddressSDNode>(N->getOperand(0))->getGlobal();
8592       Offset = cast<GlobalAddressSDNode>(N->getOperand(0))->getOffset();
8593       return true;
8594     }
8595   }
8596   return TargetLowering::isGAPlusOffset(N, GA, Offset);
8597 }
8598
8599 static bool EltsFromConsecutiveLoads(ShuffleVectorSDNode *N, unsigned NumElems,
8600                                      EVT EltVT, LoadSDNode *&LDBase,
8601                                      unsigned &LastLoadedElt,
8602                                      SelectionDAG &DAG, MachineFrameInfo *MFI,
8603                                      const TargetLowering &TLI) {
8604   LDBase = NULL;
8605   LastLoadedElt = -1U;
8606   for (unsigned i = 0; i < NumElems; ++i) {
8607     if (N->getMaskElt(i) < 0) {
8608       if (!LDBase)
8609         return false;
8610       continue;
8611     }
8612
8613     SDValue Elt = DAG.getShuffleScalarElt(N, i);
8614     if (!Elt.getNode() ||
8615         (Elt.getOpcode() != ISD::UNDEF && !ISD::isNON_EXTLoad(Elt.getNode())))
8616       return false;
8617     if (!LDBase) {
8618       if (Elt.getNode()->getOpcode() == ISD::UNDEF)
8619         return false;
8620       LDBase = cast<LoadSDNode>(Elt.getNode());
8621       LastLoadedElt = i;
8622       continue;
8623     }
8624     if (Elt.getOpcode() == ISD::UNDEF)
8625       continue;
8626
8627     LoadSDNode *LD = cast<LoadSDNode>(Elt);
8628     if (!DAG.isConsecutiveLoad(LD, LDBase, EltVT.getSizeInBits()/8, i))
8629       return false;
8630     LastLoadedElt = i;
8631   }
8632   return true;
8633 }
8634
8635 /// PerformShuffleCombine - Combine a vector_shuffle that is equal to
8636 /// build_vector load1, load2, load3, load4, <0, 1, 2, 3> into a 128-bit load
8637 /// if the load addresses are consecutive, non-overlapping, and in the right
8638 /// order.  In the case of v2i64, it will see if it can rewrite the
8639 /// shuffle to be an appropriate build vector so it can take advantage of
8640 // performBuildVectorCombine.
8641 static SDValue PerformShuffleCombine(SDNode *N, SelectionDAG &DAG,
8642                                      const TargetLowering &TLI) {
8643   DebugLoc dl = N->getDebugLoc();
8644   EVT VT = N->getValueType(0);
8645   EVT EltVT = VT.getVectorElementType();
8646   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
8647   unsigned NumElems = VT.getVectorNumElements();
8648
8649   if (VT.getSizeInBits() != 128)
8650     return SDValue();
8651
8652   // Try to combine a vector_shuffle into a 128-bit load.
8653   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
8654   LoadSDNode *LD = NULL;
8655   unsigned LastLoadedElt;
8656   if (!EltsFromConsecutiveLoads(SVN, NumElems, EltVT, LD, LastLoadedElt, DAG,
8657                                 MFI, TLI))
8658     return SDValue();
8659
8660   if (LastLoadedElt == NumElems - 1) {
8661     if (DAG.InferPtrAlignment(LD->getBasePtr()) >= 16)
8662       return DAG.getLoad(VT, dl, LD->getChain(), LD->getBasePtr(),
8663                          LD->getSrcValue(), LD->getSrcValueOffset(),
8664                          LD->isVolatile());
8665     return DAG.getLoad(VT, dl, LD->getChain(), LD->getBasePtr(),
8666                        LD->getSrcValue(), LD->getSrcValueOffset(),
8667                        LD->isVolatile(), LD->getAlignment());
8668   } else if (NumElems == 4 && LastLoadedElt == 1) {
8669     SDVTList Tys = DAG.getVTList(MVT::v2i64, MVT::Other);
8670     SDValue Ops[] = { LD->getChain(), LD->getBasePtr() };
8671     SDValue ResNode = DAG.getNode(X86ISD::VZEXT_LOAD, dl, Tys, Ops, 2);
8672     return DAG.getNode(ISD::BIT_CONVERT, dl, VT, ResNode);
8673   }
8674   return SDValue();
8675 }
8676
8677 /// PerformSELECTCombine - Do target-specific dag combines on SELECT nodes.
8678 static SDValue PerformSELECTCombine(SDNode *N, SelectionDAG &DAG,
8679                                     const X86Subtarget *Subtarget) {
8680   DebugLoc DL = N->getDebugLoc();
8681   SDValue Cond = N->getOperand(0);
8682   // Get the LHS/RHS of the select.
8683   SDValue LHS = N->getOperand(1);
8684   SDValue RHS = N->getOperand(2);
8685
8686   // If we have SSE[12] support, try to form min/max nodes. SSE min/max
8687   // instructions have the peculiarity that if either operand is a NaN,
8688   // they chose what we call the RHS operand (and as such are not symmetric).
8689   // It happens that this matches the semantics of the common C idiom
8690   // x<y?x:y and related forms, so we can recognize these cases.
8691   if (Subtarget->hasSSE2() &&
8692       (LHS.getValueType() == MVT::f32 || LHS.getValueType() == MVT::f64) &&
8693       Cond.getOpcode() == ISD::SETCC) {
8694     ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
8695
8696     unsigned Opcode = 0;
8697     // Check for x CC y ? x : y.
8698     if (LHS == Cond.getOperand(0) && RHS == Cond.getOperand(1)) {
8699       switch (CC) {
8700       default: break;
8701       case ISD::SETULT:
8702         // This can be a min if we can prove that at least one of the operands
8703         // is not a nan.
8704         if (!FiniteOnlyFPMath()) {
8705           if (DAG.isKnownNeverNaN(RHS)) {
8706             // Put the potential NaN in the RHS so that SSE will preserve it.
8707             std::swap(LHS, RHS);
8708           } else if (!DAG.isKnownNeverNaN(LHS))
8709             break;
8710         }
8711         Opcode = X86ISD::FMIN;
8712         break;
8713       case ISD::SETOLE:
8714         // This can be a min if we can prove that at least one of the operands
8715         // is not a nan.
8716         if (!FiniteOnlyFPMath()) {
8717           if (DAG.isKnownNeverNaN(LHS)) {
8718             // Put the potential NaN in the RHS so that SSE will preserve it.
8719             std::swap(LHS, RHS);
8720           } else if (!DAG.isKnownNeverNaN(RHS))
8721             break;
8722         }
8723         Opcode = X86ISD::FMIN;
8724         break;
8725       case ISD::SETULE:
8726         // This can be a min, but if either operand is a NaN we need it to
8727         // preserve the original LHS.
8728         std::swap(LHS, RHS);
8729       case ISD::SETOLT:
8730       case ISD::SETLT:
8731       case ISD::SETLE:
8732         Opcode = X86ISD::FMIN;
8733         break;
8734
8735       case ISD::SETOGE:
8736         // This can be a max if we can prove that at least one of the operands
8737         // is not a nan.
8738         if (!FiniteOnlyFPMath()) {
8739           if (DAG.isKnownNeverNaN(LHS)) {
8740             // Put the potential NaN in the RHS so that SSE will preserve it.
8741             std::swap(LHS, RHS);
8742           } else if (!DAG.isKnownNeverNaN(RHS))
8743             break;
8744         }
8745         Opcode = X86ISD::FMAX;
8746         break;
8747       case ISD::SETUGT:
8748         // This can be a max if we can prove that at least one of the operands
8749         // is not a nan.
8750         if (!FiniteOnlyFPMath()) {
8751           if (DAG.isKnownNeverNaN(RHS)) {
8752             // Put the potential NaN in the RHS so that SSE will preserve it.
8753             std::swap(LHS, RHS);
8754           } else if (!DAG.isKnownNeverNaN(LHS))
8755             break;
8756         }
8757         Opcode = X86ISD::FMAX;
8758         break;
8759       case ISD::SETUGE:
8760         // This can be a max, but if either operand is a NaN we need it to
8761         // preserve the original LHS.
8762         std::swap(LHS, RHS);
8763       case ISD::SETOGT:
8764       case ISD::SETGT:
8765       case ISD::SETGE:
8766         Opcode = X86ISD::FMAX;
8767         break;
8768       }
8769     // Check for x CC y ? y : x -- a min/max with reversed arms.
8770     } else if (LHS == Cond.getOperand(1) && RHS == Cond.getOperand(0)) {
8771       switch (CC) {
8772       default: break;
8773       case ISD::SETOGE:
8774         // This can be a min if we can prove that at least one of the operands
8775         // is not a nan.
8776         if (!FiniteOnlyFPMath()) {
8777           if (DAG.isKnownNeverNaN(RHS)) {
8778             // Put the potential NaN in the RHS so that SSE will preserve it.
8779             std::swap(LHS, RHS);
8780           } else if (!DAG.isKnownNeverNaN(LHS))
8781             break;
8782         }
8783         Opcode = X86ISD::FMIN;
8784         break;
8785       case ISD::SETUGT:
8786         // This can be a min if we can prove that at least one of the operands
8787         // is not a nan.
8788         if (!FiniteOnlyFPMath()) {
8789           if (DAG.isKnownNeverNaN(LHS)) {
8790             // Put the potential NaN in the RHS so that SSE will preserve it.
8791             std::swap(LHS, RHS);
8792           } else if (!DAG.isKnownNeverNaN(RHS))
8793             break;
8794         }
8795         Opcode = X86ISD::FMIN;
8796         break;
8797       case ISD::SETUGE:
8798         // This can be a min, but if either operand is a NaN we need it to
8799         // preserve the original LHS.
8800         std::swap(LHS, RHS);
8801       case ISD::SETOGT:
8802       case ISD::SETGT:
8803       case ISD::SETGE:
8804         Opcode = X86ISD::FMIN;
8805         break;
8806
8807       case ISD::SETULT:
8808         // This can be a max if we can prove that at least one of the operands
8809         // is not a nan.
8810         if (!FiniteOnlyFPMath()) {
8811           if (DAG.isKnownNeverNaN(LHS)) {
8812             // Put the potential NaN in the RHS so that SSE will preserve it.
8813             std::swap(LHS, RHS);
8814           } else if (!DAG.isKnownNeverNaN(RHS))
8815             break;
8816         }
8817         Opcode = X86ISD::FMAX;
8818         break;
8819       case ISD::SETOLE:
8820         // This can be a max if we can prove that at least one of the operands
8821         // is not a nan.
8822         if (!FiniteOnlyFPMath()) {
8823           if (DAG.isKnownNeverNaN(RHS)) {
8824             // Put the potential NaN in the RHS so that SSE will preserve it.
8825             std::swap(LHS, RHS);
8826           } else if (!DAG.isKnownNeverNaN(LHS))
8827             break;
8828         }
8829         Opcode = X86ISD::FMAX;
8830         break;
8831       case ISD::SETULE:
8832         // This can be a max, but if either operand is a NaN we need it to
8833         // preserve the original LHS.
8834         std::swap(LHS, RHS);
8835       case ISD::SETOLT:
8836       case ISD::SETLT:
8837       case ISD::SETLE:
8838         Opcode = X86ISD::FMAX;
8839         break;
8840       }
8841     }
8842
8843     if (Opcode)
8844       return DAG.getNode(Opcode, DL, N->getValueType(0), LHS, RHS);
8845   }
8846
8847   // If this is a select between two integer constants, try to do some
8848   // optimizations.
8849   if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(LHS)) {
8850     if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(RHS))
8851       // Don't do this for crazy integer types.
8852       if (DAG.getTargetLoweringInfo().isTypeLegal(LHS.getValueType())) {
8853         // If this is efficiently invertible, canonicalize the LHSC/RHSC values
8854         // so that TrueC (the true value) is larger than FalseC.
8855         bool NeedsCondInvert = false;
8856
8857         if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue()) &&
8858             // Efficiently invertible.
8859             (Cond.getOpcode() == ISD::SETCC ||  // setcc -> invertible.
8860              (Cond.getOpcode() == ISD::XOR &&   // xor(X, C) -> invertible.
8861               isa<ConstantSDNode>(Cond.getOperand(1))))) {
8862           NeedsCondInvert = true;
8863           std::swap(TrueC, FalseC);
8864         }
8865
8866         // Optimize C ? 8 : 0 -> zext(C) << 3.  Likewise for any pow2/0.
8867         if (FalseC->getAPIntValue() == 0 &&
8868             TrueC->getAPIntValue().isPowerOf2()) {
8869           if (NeedsCondInvert) // Invert the condition if needed.
8870             Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
8871                                DAG.getConstant(1, Cond.getValueType()));
8872
8873           // Zero extend the condition if needed.
8874           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, LHS.getValueType(), Cond);
8875
8876           unsigned ShAmt = TrueC->getAPIntValue().logBase2();
8877           return DAG.getNode(ISD::SHL, DL, LHS.getValueType(), Cond,
8878                              DAG.getConstant(ShAmt, MVT::i8));
8879         }
8880
8881         // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.
8882         if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
8883           if (NeedsCondInvert) // Invert the condition if needed.
8884             Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
8885                                DAG.getConstant(1, Cond.getValueType()));
8886
8887           // Zero extend the condition if needed.
8888           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
8889                              FalseC->getValueType(0), Cond);
8890           return DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
8891                              SDValue(FalseC, 0));
8892         }
8893
8894         // Optimize cases that will turn into an LEA instruction.  This requires
8895         // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
8896         if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
8897           uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
8898           if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
8899
8900           bool isFastMultiplier = false;
8901           if (Diff < 10) {
8902             switch ((unsigned char)Diff) {
8903               default: break;
8904               case 1:  // result = add base, cond
8905               case 2:  // result = lea base(    , cond*2)
8906               case 3:  // result = lea base(cond, cond*2)
8907               case 4:  // result = lea base(    , cond*4)
8908               case 5:  // result = lea base(cond, cond*4)
8909               case 8:  // result = lea base(    , cond*8)
8910               case 9:  // result = lea base(cond, cond*8)
8911                 isFastMultiplier = true;
8912                 break;
8913             }
8914           }
8915
8916           if (isFastMultiplier) {
8917             APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
8918             if (NeedsCondInvert) // Invert the condition if needed.
8919               Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
8920                                  DAG.getConstant(1, Cond.getValueType()));
8921
8922             // Zero extend the condition if needed.
8923             Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
8924                                Cond);
8925             // Scale the condition by the difference.
8926             if (Diff != 1)
8927               Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
8928                                  DAG.getConstant(Diff, Cond.getValueType()));
8929
8930             // Add the base if non-zero.
8931             if (FalseC->getAPIntValue() != 0)
8932               Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
8933                                  SDValue(FalseC, 0));
8934             return Cond;
8935           }
8936         }
8937       }
8938   }
8939
8940   return SDValue();
8941 }
8942
8943 /// Optimize X86ISD::CMOV [LHS, RHS, CONDCODE (e.g. X86::COND_NE), CONDVAL]
8944 static SDValue PerformCMOVCombine(SDNode *N, SelectionDAG &DAG,
8945                                   TargetLowering::DAGCombinerInfo &DCI) {
8946   DebugLoc DL = N->getDebugLoc();
8947
8948   // If the flag operand isn't dead, don't touch this CMOV.
8949   if (N->getNumValues() == 2 && !SDValue(N, 1).use_empty())
8950     return SDValue();
8951
8952   // If this is a select between two integer constants, try to do some
8953   // optimizations.  Note that the operands are ordered the opposite of SELECT
8954   // operands.
8955   if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(N->getOperand(1))) {
8956     if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(N->getOperand(0))) {
8957       // Canonicalize the TrueC/FalseC values so that TrueC (the true value) is
8958       // larger than FalseC (the false value).
8959       X86::CondCode CC = (X86::CondCode)N->getConstantOperandVal(2);
8960
8961       if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue())) {
8962         CC = X86::GetOppositeBranchCondition(CC);
8963         std::swap(TrueC, FalseC);
8964       }
8965
8966       // Optimize C ? 8 : 0 -> zext(setcc(C)) << 3.  Likewise for any pow2/0.
8967       // This is efficient for any integer data type (including i8/i16) and
8968       // shift amount.
8969       if (FalseC->getAPIntValue() == 0 && TrueC->getAPIntValue().isPowerOf2()) {
8970         SDValue Cond = N->getOperand(3);
8971         Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
8972                            DAG.getConstant(CC, MVT::i8), Cond);
8973
8974         // Zero extend the condition if needed.
8975         Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, TrueC->getValueType(0), Cond);
8976
8977         unsigned ShAmt = TrueC->getAPIntValue().logBase2();
8978         Cond = DAG.getNode(ISD::SHL, DL, Cond.getValueType(), Cond,
8979                            DAG.getConstant(ShAmt, MVT::i8));
8980         if (N->getNumValues() == 2)  // Dead flag value?
8981           return DCI.CombineTo(N, Cond, SDValue());
8982         return Cond;
8983       }
8984
8985       // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.  This is efficient
8986       // for any integer data type, including i8/i16.
8987       if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
8988         SDValue Cond = N->getOperand(3);
8989         Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
8990                            DAG.getConstant(CC, MVT::i8), Cond);
8991
8992         // Zero extend the condition if needed.
8993         Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
8994                            FalseC->getValueType(0), Cond);
8995         Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
8996                            SDValue(FalseC, 0));
8997
8998         if (N->getNumValues() == 2)  // Dead flag value?
8999           return DCI.CombineTo(N, Cond, SDValue());
9000         return Cond;
9001       }
9002
9003       // Optimize cases that will turn into an LEA instruction.  This requires
9004       // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
9005       if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
9006         uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
9007         if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
9008
9009         bool isFastMultiplier = false;
9010         if (Diff < 10) {
9011           switch ((unsigned char)Diff) {
9012           default: break;
9013           case 1:  // result = add base, cond
9014           case 2:  // result = lea base(    , cond*2)
9015           case 3:  // result = lea base(cond, cond*2)
9016           case 4:  // result = lea base(    , cond*4)
9017           case 5:  // result = lea base(cond, cond*4)
9018           case 8:  // result = lea base(    , cond*8)
9019           case 9:  // result = lea base(cond, cond*8)
9020             isFastMultiplier = true;
9021             break;
9022           }
9023         }
9024
9025         if (isFastMultiplier) {
9026           APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
9027           SDValue Cond = N->getOperand(3);
9028           Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
9029                              DAG.getConstant(CC, MVT::i8), Cond);
9030           // Zero extend the condition if needed.
9031           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
9032                              Cond);
9033           // Scale the condition by the difference.
9034           if (Diff != 1)
9035             Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
9036                                DAG.getConstant(Diff, Cond.getValueType()));
9037
9038           // Add the base if non-zero.
9039           if (FalseC->getAPIntValue() != 0)
9040             Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
9041                                SDValue(FalseC, 0));
9042           if (N->getNumValues() == 2)  // Dead flag value?
9043             return DCI.CombineTo(N, Cond, SDValue());
9044           return Cond;
9045         }
9046       }
9047     }
9048   }
9049   return SDValue();
9050 }
9051
9052
9053 /// PerformMulCombine - Optimize a single multiply with constant into two
9054 /// in order to implement it with two cheaper instructions, e.g.
9055 /// LEA + SHL, LEA + LEA.
9056 static SDValue PerformMulCombine(SDNode *N, SelectionDAG &DAG,
9057                                  TargetLowering::DAGCombinerInfo &DCI) {
9058   if (DAG.getMachineFunction().
9059       getFunction()->hasFnAttr(Attribute::OptimizeForSize))
9060     return SDValue();
9061
9062   if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
9063     return SDValue();
9064
9065   EVT VT = N->getValueType(0);
9066   if (VT != MVT::i64)
9067     return SDValue();
9068
9069   ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
9070   if (!C)
9071     return SDValue();
9072   uint64_t MulAmt = C->getZExtValue();
9073   if (isPowerOf2_64(MulAmt) || MulAmt == 3 || MulAmt == 5 || MulAmt == 9)
9074     return SDValue();
9075
9076   uint64_t MulAmt1 = 0;
9077   uint64_t MulAmt2 = 0;
9078   if ((MulAmt % 9) == 0) {
9079     MulAmt1 = 9;
9080     MulAmt2 = MulAmt / 9;
9081   } else if ((MulAmt % 5) == 0) {
9082     MulAmt1 = 5;
9083     MulAmt2 = MulAmt / 5;
9084   } else if ((MulAmt % 3) == 0) {
9085     MulAmt1 = 3;
9086     MulAmt2 = MulAmt / 3;
9087   }
9088   if (MulAmt2 &&
9089       (isPowerOf2_64(MulAmt2) || MulAmt2 == 3 || MulAmt2 == 5 || MulAmt2 == 9)){
9090     DebugLoc DL = N->getDebugLoc();
9091
9092     if (isPowerOf2_64(MulAmt2) &&
9093         !(N->hasOneUse() && N->use_begin()->getOpcode() == ISD::ADD))
9094       // If second multiplifer is pow2, issue it first. We want the multiply by
9095       // 3, 5, or 9 to be folded into the addressing mode unless the lone use
9096       // is an add.
9097       std::swap(MulAmt1, MulAmt2);
9098
9099     SDValue NewMul;
9100     if (isPowerOf2_64(MulAmt1))
9101       NewMul = DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
9102                            DAG.getConstant(Log2_64(MulAmt1), MVT::i8));
9103     else
9104       NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, N->getOperand(0),
9105                            DAG.getConstant(MulAmt1, VT));
9106
9107     if (isPowerOf2_64(MulAmt2))
9108       NewMul = DAG.getNode(ISD::SHL, DL, VT, NewMul,
9109                            DAG.getConstant(Log2_64(MulAmt2), MVT::i8));
9110     else
9111       NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, NewMul,
9112                            DAG.getConstant(MulAmt2, VT));
9113
9114     // Do not add new nodes to DAG combiner worklist.
9115     DCI.CombineTo(N, NewMul, false);
9116   }
9117   return SDValue();
9118 }
9119
9120 static SDValue PerformSHLCombine(SDNode *N, SelectionDAG &DAG) {
9121   SDValue N0 = N->getOperand(0);
9122   SDValue N1 = N->getOperand(1);
9123   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
9124   EVT VT = N0.getValueType();
9125
9126   // fold (shl (and (setcc_c), c1), c2) -> (and setcc_c, (c1 << c2))
9127   // since the result of setcc_c is all zero's or all ones.
9128   if (N1C && N0.getOpcode() == ISD::AND &&
9129       N0.getOperand(1).getOpcode() == ISD::Constant) {
9130     SDValue N00 = N0.getOperand(0);
9131     if (N00.getOpcode() == X86ISD::SETCC_CARRY ||
9132         ((N00.getOpcode() == ISD::ANY_EXTEND ||
9133           N00.getOpcode() == ISD::ZERO_EXTEND) &&
9134          N00.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY)) {
9135       APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
9136       APInt ShAmt = N1C->getAPIntValue();
9137       Mask = Mask.shl(ShAmt);
9138       if (Mask != 0)
9139         return DAG.getNode(ISD::AND, N->getDebugLoc(), VT,
9140                            N00, DAG.getConstant(Mask, VT));
9141     }
9142   }
9143
9144   return SDValue();
9145 }
9146
9147 /// PerformShiftCombine - Transforms vector shift nodes to use vector shifts
9148 ///                       when possible.
9149 static SDValue PerformShiftCombine(SDNode* N, SelectionDAG &DAG,
9150                                    const X86Subtarget *Subtarget) {
9151   EVT VT = N->getValueType(0);
9152   if (!VT.isVector() && VT.isInteger() &&
9153       N->getOpcode() == ISD::SHL)
9154     return PerformSHLCombine(N, DAG);
9155
9156   // On X86 with SSE2 support, we can transform this to a vector shift if
9157   // all elements are shifted by the same amount.  We can't do this in legalize
9158   // because the a constant vector is typically transformed to a constant pool
9159   // so we have no knowledge of the shift amount.
9160   if (!Subtarget->hasSSE2())
9161     return SDValue();
9162
9163   if (VT != MVT::v2i64 && VT != MVT::v4i32 && VT != MVT::v8i16)
9164     return SDValue();
9165
9166   SDValue ShAmtOp = N->getOperand(1);
9167   EVT EltVT = VT.getVectorElementType();
9168   DebugLoc DL = N->getDebugLoc();
9169   SDValue BaseShAmt = SDValue();
9170   if (ShAmtOp.getOpcode() == ISD::BUILD_VECTOR) {
9171     unsigned NumElts = VT.getVectorNumElements();
9172     unsigned i = 0;
9173     for (; i != NumElts; ++i) {
9174       SDValue Arg = ShAmtOp.getOperand(i);
9175       if (Arg.getOpcode() == ISD::UNDEF) continue;
9176       BaseShAmt = Arg;
9177       break;
9178     }
9179     for (; i != NumElts; ++i) {
9180       SDValue Arg = ShAmtOp.getOperand(i);
9181       if (Arg.getOpcode() == ISD::UNDEF) continue;
9182       if (Arg != BaseShAmt) {
9183         return SDValue();
9184       }
9185     }
9186   } else if (ShAmtOp.getOpcode() == ISD::VECTOR_SHUFFLE &&
9187              cast<ShuffleVectorSDNode>(ShAmtOp)->isSplat()) {
9188     SDValue InVec = ShAmtOp.getOperand(0);
9189     if (InVec.getOpcode() == ISD::BUILD_VECTOR) {
9190       unsigned NumElts = InVec.getValueType().getVectorNumElements();
9191       unsigned i = 0;
9192       for (; i != NumElts; ++i) {
9193         SDValue Arg = InVec.getOperand(i);
9194         if (Arg.getOpcode() == ISD::UNDEF) continue;
9195         BaseShAmt = Arg;
9196         break;
9197       }
9198     } else if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT) {
9199        if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(InVec.getOperand(2))) {
9200          unsigned SplatIdx = cast<ShuffleVectorSDNode>(ShAmtOp)->getSplatIndex();
9201          if (C->getZExtValue() == SplatIdx)
9202            BaseShAmt = InVec.getOperand(1);
9203        }
9204     }
9205     if (BaseShAmt.getNode() == 0)
9206       BaseShAmt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, EltVT, ShAmtOp,
9207                               DAG.getIntPtrConstant(0));
9208   } else
9209     return SDValue();
9210
9211   // The shift amount is an i32.
9212   if (EltVT.bitsGT(MVT::i32))
9213     BaseShAmt = DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, BaseShAmt);
9214   else if (EltVT.bitsLT(MVT::i32))
9215     BaseShAmt = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, BaseShAmt);
9216
9217   // The shift amount is identical so we can do a vector shift.
9218   SDValue  ValOp = N->getOperand(0);
9219   switch (N->getOpcode()) {
9220   default:
9221     llvm_unreachable("Unknown shift opcode!");
9222     break;
9223   case ISD::SHL:
9224     if (VT == MVT::v2i64)
9225       return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
9226                          DAG.getConstant(Intrinsic::x86_sse2_pslli_q, MVT::i32),
9227                          ValOp, BaseShAmt);
9228     if (VT == MVT::v4i32)
9229       return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
9230                          DAG.getConstant(Intrinsic::x86_sse2_pslli_d, MVT::i32),
9231                          ValOp, BaseShAmt);
9232     if (VT == MVT::v8i16)
9233       return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
9234                          DAG.getConstant(Intrinsic::x86_sse2_pslli_w, MVT::i32),
9235                          ValOp, BaseShAmt);
9236     break;
9237   case ISD::SRA:
9238     if (VT == MVT::v4i32)
9239       return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
9240                          DAG.getConstant(Intrinsic::x86_sse2_psrai_d, MVT::i32),
9241                          ValOp, BaseShAmt);
9242     if (VT == MVT::v8i16)
9243       return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
9244                          DAG.getConstant(Intrinsic::x86_sse2_psrai_w, MVT::i32),
9245                          ValOp, BaseShAmt);
9246     break;
9247   case ISD::SRL:
9248     if (VT == MVT::v2i64)
9249       return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
9250                          DAG.getConstant(Intrinsic::x86_sse2_psrli_q, MVT::i32),
9251                          ValOp, BaseShAmt);
9252     if (VT == MVT::v4i32)
9253       return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
9254                          DAG.getConstant(Intrinsic::x86_sse2_psrli_d, MVT::i32),
9255                          ValOp, BaseShAmt);
9256     if (VT ==  MVT::v8i16)
9257       return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
9258                          DAG.getConstant(Intrinsic::x86_sse2_psrli_w, MVT::i32),
9259                          ValOp, BaseShAmt);
9260     break;
9261   }
9262   return SDValue();
9263 }
9264
9265 static SDValue PerformOrCombine(SDNode *N, SelectionDAG &DAG,
9266                                 const X86Subtarget *Subtarget) {
9267   EVT VT = N->getValueType(0);
9268   if (VT != MVT::i64 || !Subtarget->is64Bit())
9269     return SDValue();
9270
9271   // fold (or (x << c) | (y >> (64 - c))) ==> (shld64 x, y, c)
9272   SDValue N0 = N->getOperand(0);
9273   SDValue N1 = N->getOperand(1);
9274   if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL)
9275     std::swap(N0, N1);
9276   if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL)
9277     return SDValue();
9278
9279   SDValue ShAmt0 = N0.getOperand(1);
9280   if (ShAmt0.getValueType() != MVT::i8)
9281     return SDValue();
9282   SDValue ShAmt1 = N1.getOperand(1);
9283   if (ShAmt1.getValueType() != MVT::i8)
9284     return SDValue();
9285   if (ShAmt0.getOpcode() == ISD::TRUNCATE)
9286     ShAmt0 = ShAmt0.getOperand(0);
9287   if (ShAmt1.getOpcode() == ISD::TRUNCATE)
9288     ShAmt1 = ShAmt1.getOperand(0);
9289
9290   DebugLoc DL = N->getDebugLoc();
9291   unsigned Opc = X86ISD::SHLD;
9292   SDValue Op0 = N0.getOperand(0);
9293   SDValue Op1 = N1.getOperand(0);
9294   if (ShAmt0.getOpcode() == ISD::SUB) {
9295     Opc = X86ISD::SHRD;
9296     std::swap(Op0, Op1);
9297     std::swap(ShAmt0, ShAmt1);
9298   }
9299
9300   if (ShAmt1.getOpcode() == ISD::SUB) {
9301     SDValue Sum = ShAmt1.getOperand(0);
9302     if (ConstantSDNode *SumC = dyn_cast<ConstantSDNode>(Sum)) {
9303       if (SumC->getSExtValue() == 64 &&
9304           ShAmt1.getOperand(1) == ShAmt0)
9305         return DAG.getNode(Opc, DL, VT,
9306                            Op0, Op1,
9307                            DAG.getNode(ISD::TRUNCATE, DL,
9308                                        MVT::i8, ShAmt0));
9309     }
9310   } else if (ConstantSDNode *ShAmt1C = dyn_cast<ConstantSDNode>(ShAmt1)) {
9311     ConstantSDNode *ShAmt0C = dyn_cast<ConstantSDNode>(ShAmt0);
9312     if (ShAmt0C &&
9313         ShAmt0C->getSExtValue() + ShAmt1C->getSExtValue() == 64)
9314       return DAG.getNode(Opc, DL, VT,
9315                          N0.getOperand(0), N1.getOperand(0),
9316                          DAG.getNode(ISD::TRUNCATE, DL,
9317                                        MVT::i8, ShAmt0));
9318   }
9319
9320   return SDValue();
9321 }
9322
9323 /// PerformSTORECombine - Do target-specific dag combines on STORE nodes.
9324 static SDValue PerformSTORECombine(SDNode *N, SelectionDAG &DAG,
9325                                    const X86Subtarget *Subtarget) {
9326   // Turn load->store of MMX types into GPR load/stores.  This avoids clobbering
9327   // the FP state in cases where an emms may be missing.
9328   // A preferable solution to the general problem is to figure out the right
9329   // places to insert EMMS.  This qualifies as a quick hack.
9330
9331   // Similarly, turn load->store of i64 into double load/stores in 32-bit mode.
9332   StoreSDNode *St = cast<StoreSDNode>(N);
9333   EVT VT = St->getValue().getValueType();
9334   if (VT.getSizeInBits() != 64)
9335     return SDValue();
9336
9337   const Function *F = DAG.getMachineFunction().getFunction();
9338   bool NoImplicitFloatOps = F->hasFnAttr(Attribute::NoImplicitFloat);
9339   bool F64IsLegal = !UseSoftFloat && !NoImplicitFloatOps
9340     && Subtarget->hasSSE2();
9341   if ((VT.isVector() ||
9342        (VT == MVT::i64 && F64IsLegal && !Subtarget->is64Bit())) &&
9343       isa<LoadSDNode>(St->getValue()) &&
9344       !cast<LoadSDNode>(St->getValue())->isVolatile() &&
9345       St->getChain().hasOneUse() && !St->isVolatile()) {
9346     SDNode* LdVal = St->getValue().getNode();
9347     LoadSDNode *Ld = 0;
9348     int TokenFactorIndex = -1;
9349     SmallVector<SDValue, 8> Ops;
9350     SDNode* ChainVal = St->getChain().getNode();
9351     // Must be a store of a load.  We currently handle two cases:  the load
9352     // is a direct child, and it's under an intervening TokenFactor.  It is
9353     // possible to dig deeper under nested TokenFactors.
9354     if (ChainVal == LdVal)
9355       Ld = cast<LoadSDNode>(St->getChain());
9356     else if (St->getValue().hasOneUse() &&
9357              ChainVal->getOpcode() == ISD::TokenFactor) {
9358       for (unsigned i=0, e = ChainVal->getNumOperands(); i != e; ++i) {
9359         if (ChainVal->getOperand(i).getNode() == LdVal) {
9360           TokenFactorIndex = i;
9361           Ld = cast<LoadSDNode>(St->getValue());
9362         } else
9363           Ops.push_back(ChainVal->getOperand(i));
9364       }
9365     }
9366
9367     if (!Ld || !ISD::isNormalLoad(Ld))
9368       return SDValue();
9369
9370     // If this is not the MMX case, i.e. we are just turning i64 load/store
9371     // into f64 load/store, avoid the transformation if there are multiple
9372     // uses of the loaded value.
9373     if (!VT.isVector() && !Ld->hasNUsesOfValue(1, 0))
9374       return SDValue();
9375
9376     DebugLoc LdDL = Ld->getDebugLoc();
9377     DebugLoc StDL = N->getDebugLoc();
9378     // If we are a 64-bit capable x86, lower to a single movq load/store pair.
9379     // Otherwise, if it's legal to use f64 SSE instructions, use f64 load/store
9380     // pair instead.
9381     if (Subtarget->is64Bit() || F64IsLegal) {
9382       EVT LdVT = Subtarget->is64Bit() ? MVT::i64 : MVT::f64;
9383       SDValue NewLd = DAG.getLoad(LdVT, LdDL, Ld->getChain(),
9384                                   Ld->getBasePtr(), Ld->getSrcValue(),
9385                                   Ld->getSrcValueOffset(), Ld->isVolatile(),
9386                                   Ld->getAlignment());
9387       SDValue NewChain = NewLd.getValue(1);
9388       if (TokenFactorIndex != -1) {
9389         Ops.push_back(NewChain);
9390         NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, &Ops[0],
9391                                Ops.size());
9392       }
9393       return DAG.getStore(NewChain, StDL, NewLd, St->getBasePtr(),
9394                           St->getSrcValue(), St->getSrcValueOffset(),
9395                           St->isVolatile(), St->getAlignment());
9396     }
9397
9398     // Otherwise, lower to two pairs of 32-bit loads / stores.
9399     SDValue LoAddr = Ld->getBasePtr();
9400     SDValue HiAddr = DAG.getNode(ISD::ADD, LdDL, MVT::i32, LoAddr,
9401                                  DAG.getConstant(4, MVT::i32));
9402
9403     SDValue LoLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), LoAddr,
9404                                Ld->getSrcValue(), Ld->getSrcValueOffset(),
9405                                Ld->isVolatile(), Ld->getAlignment());
9406     SDValue HiLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), HiAddr,
9407                                Ld->getSrcValue(), Ld->getSrcValueOffset()+4,
9408                                Ld->isVolatile(),
9409                                MinAlign(Ld->getAlignment(), 4));
9410
9411     SDValue NewChain = LoLd.getValue(1);
9412     if (TokenFactorIndex != -1) {
9413       Ops.push_back(LoLd);
9414       Ops.push_back(HiLd);
9415       NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, &Ops[0],
9416                              Ops.size());
9417     }
9418
9419     LoAddr = St->getBasePtr();
9420     HiAddr = DAG.getNode(ISD::ADD, StDL, MVT::i32, LoAddr,
9421                          DAG.getConstant(4, MVT::i32));
9422
9423     SDValue LoSt = DAG.getStore(NewChain, StDL, LoLd, LoAddr,
9424                                 St->getSrcValue(), St->getSrcValueOffset(),
9425                                 St->isVolatile(), St->getAlignment());
9426     SDValue HiSt = DAG.getStore(NewChain, StDL, HiLd, HiAddr,
9427                                 St->getSrcValue(),
9428                                 St->getSrcValueOffset() + 4,
9429                                 St->isVolatile(),
9430                                 MinAlign(St->getAlignment(), 4));
9431     return DAG.getNode(ISD::TokenFactor, StDL, MVT::Other, LoSt, HiSt);
9432   }
9433   return SDValue();
9434 }
9435
9436 /// PerformFORCombine - Do target-specific dag combines on X86ISD::FOR and
9437 /// X86ISD::FXOR nodes.
9438 static SDValue PerformFORCombine(SDNode *N, SelectionDAG &DAG) {
9439   assert(N->getOpcode() == X86ISD::FOR || N->getOpcode() == X86ISD::FXOR);
9440   // F[X]OR(0.0, x) -> x
9441   // F[X]OR(x, 0.0) -> x
9442   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
9443     if (C->getValueAPF().isPosZero())
9444       return N->getOperand(1);
9445   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
9446     if (C->getValueAPF().isPosZero())
9447       return N->getOperand(0);
9448   return SDValue();
9449 }
9450
9451 /// PerformFANDCombine - Do target-specific dag combines on X86ISD::FAND nodes.
9452 static SDValue PerformFANDCombine(SDNode *N, SelectionDAG &DAG) {
9453   // FAND(0.0, x) -> 0.0
9454   // FAND(x, 0.0) -> 0.0
9455   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
9456     if (C->getValueAPF().isPosZero())
9457       return N->getOperand(0);
9458   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
9459     if (C->getValueAPF().isPosZero())
9460       return N->getOperand(1);
9461   return SDValue();
9462 }
9463
9464 static SDValue PerformBTCombine(SDNode *N,
9465                                 SelectionDAG &DAG,
9466                                 TargetLowering::DAGCombinerInfo &DCI) {
9467   // BT ignores high bits in the bit index operand.
9468   SDValue Op1 = N->getOperand(1);
9469   if (Op1.hasOneUse()) {
9470     unsigned BitWidth = Op1.getValueSizeInBits();
9471     APInt DemandedMask = APInt::getLowBitsSet(BitWidth, Log2_32(BitWidth));
9472     APInt KnownZero, KnownOne;
9473     TargetLowering::TargetLoweringOpt TLO(DAG);
9474     TargetLowering &TLI = DAG.getTargetLoweringInfo();
9475     if (TLO.ShrinkDemandedConstant(Op1, DemandedMask) ||
9476         TLI.SimplifyDemandedBits(Op1, DemandedMask, KnownZero, KnownOne, TLO))
9477       DCI.CommitTargetLoweringOpt(TLO);
9478   }
9479   return SDValue();
9480 }
9481
9482 static SDValue PerformVZEXT_MOVLCombine(SDNode *N, SelectionDAG &DAG) {
9483   SDValue Op = N->getOperand(0);
9484   if (Op.getOpcode() == ISD::BIT_CONVERT)
9485     Op = Op.getOperand(0);
9486   EVT VT = N->getValueType(0), OpVT = Op.getValueType();
9487   if (Op.getOpcode() == X86ISD::VZEXT_LOAD &&
9488       VT.getVectorElementType().getSizeInBits() ==
9489       OpVT.getVectorElementType().getSizeInBits()) {
9490     return DAG.getNode(ISD::BIT_CONVERT, N->getDebugLoc(), VT, Op);
9491   }
9492   return SDValue();
9493 }
9494
9495 // On X86 and X86-64, atomic operations are lowered to locked instructions.
9496 // Locked instructions, in turn, have implicit fence semantics (all memory
9497 // operations are flushed before issuing the locked instruction, and the
9498 // are not buffered), so we can fold away the common pattern of
9499 // fence-atomic-fence.
9500 static SDValue PerformMEMBARRIERCombine(SDNode* N, SelectionDAG &DAG) {
9501   SDValue atomic = N->getOperand(0);
9502   switch (atomic.getOpcode()) {
9503     case ISD::ATOMIC_CMP_SWAP:
9504     case ISD::ATOMIC_SWAP:
9505     case ISD::ATOMIC_LOAD_ADD:
9506     case ISD::ATOMIC_LOAD_SUB:
9507     case ISD::ATOMIC_LOAD_AND:
9508     case ISD::ATOMIC_LOAD_OR:
9509     case ISD::ATOMIC_LOAD_XOR:
9510     case ISD::ATOMIC_LOAD_NAND:
9511     case ISD::ATOMIC_LOAD_MIN:
9512     case ISD::ATOMIC_LOAD_MAX:
9513     case ISD::ATOMIC_LOAD_UMIN:
9514     case ISD::ATOMIC_LOAD_UMAX:
9515       break;
9516     default:
9517       return SDValue();
9518   }
9519
9520   SDValue fence = atomic.getOperand(0);
9521   if (fence.getOpcode() != ISD::MEMBARRIER)
9522     return SDValue();
9523
9524   switch (atomic.getOpcode()) {
9525     case ISD::ATOMIC_CMP_SWAP:
9526       return DAG.UpdateNodeOperands(atomic, fence.getOperand(0),
9527                                     atomic.getOperand(1), atomic.getOperand(2),
9528                                     atomic.getOperand(3));
9529     case ISD::ATOMIC_SWAP:
9530     case ISD::ATOMIC_LOAD_ADD:
9531     case ISD::ATOMIC_LOAD_SUB:
9532     case ISD::ATOMIC_LOAD_AND:
9533     case ISD::ATOMIC_LOAD_OR:
9534     case ISD::ATOMIC_LOAD_XOR:
9535     case ISD::ATOMIC_LOAD_NAND:
9536     case ISD::ATOMIC_LOAD_MIN:
9537     case ISD::ATOMIC_LOAD_MAX:
9538     case ISD::ATOMIC_LOAD_UMIN:
9539     case ISD::ATOMIC_LOAD_UMAX:
9540       return DAG.UpdateNodeOperands(atomic, fence.getOperand(0),
9541                                     atomic.getOperand(1), atomic.getOperand(2));
9542     default:
9543       return SDValue();
9544   }
9545 }
9546
9547 static SDValue PerformZExtCombine(SDNode *N, SelectionDAG &DAG) {
9548   // (i32 zext (and (i8  x86isd::setcc_carry), 1)) ->
9549   //           (and (i32 x86isd::setcc_carry), 1)
9550   // This eliminates the zext. This transformation is necessary because
9551   // ISD::SETCC is always legalized to i8.
9552   DebugLoc dl = N->getDebugLoc();
9553   SDValue N0 = N->getOperand(0);
9554   EVT VT = N->getValueType(0);
9555   if (N0.getOpcode() == ISD::AND &&
9556       N0.hasOneUse() &&
9557       N0.getOperand(0).hasOneUse()) {
9558     SDValue N00 = N0.getOperand(0);
9559     if (N00.getOpcode() != X86ISD::SETCC_CARRY)
9560       return SDValue();
9561     ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
9562     if (!C || C->getZExtValue() != 1)
9563       return SDValue();
9564     return DAG.getNode(ISD::AND, dl, VT,
9565                        DAG.getNode(X86ISD::SETCC_CARRY, dl, VT,
9566                                    N00.getOperand(0), N00.getOperand(1)),
9567                        DAG.getConstant(1, VT));
9568   }
9569
9570   return SDValue();
9571 }
9572
9573 SDValue X86TargetLowering::PerformDAGCombine(SDNode *N,
9574                                              DAGCombinerInfo &DCI) const {
9575   SelectionDAG &DAG = DCI.DAG;
9576   switch (N->getOpcode()) {
9577   default: break;
9578   case ISD::VECTOR_SHUFFLE: return PerformShuffleCombine(N, DAG, *this);
9579   case ISD::SELECT:         return PerformSELECTCombine(N, DAG, Subtarget);
9580   case X86ISD::CMOV:        return PerformCMOVCombine(N, DAG, DCI);
9581   case ISD::MUL:            return PerformMulCombine(N, DAG, DCI);
9582   case ISD::SHL:
9583   case ISD::SRA:
9584   case ISD::SRL:            return PerformShiftCombine(N, DAG, Subtarget);
9585   case ISD::OR:             return PerformOrCombine(N, DAG, Subtarget);
9586   case ISD::STORE:          return PerformSTORECombine(N, DAG, Subtarget);
9587   case X86ISD::FXOR:
9588   case X86ISD::FOR:         return PerformFORCombine(N, DAG);
9589   case X86ISD::FAND:        return PerformFANDCombine(N, DAG);
9590   case X86ISD::BT:          return PerformBTCombine(N, DAG, DCI);
9591   case X86ISD::VZEXT_MOVL:  return PerformVZEXT_MOVLCombine(N, DAG);
9592   case ISD::MEMBARRIER:     return PerformMEMBARRIERCombine(N, DAG);
9593   case ISD::ZERO_EXTEND:    return PerformZExtCombine(N, DAG);
9594   }
9595
9596   return SDValue();
9597 }
9598
9599 //===----------------------------------------------------------------------===//
9600 //                           X86 Inline Assembly Support
9601 //===----------------------------------------------------------------------===//
9602
9603 static bool LowerToBSwap(CallInst *CI) {
9604   // FIXME: this should verify that we are targetting a 486 or better.  If not,
9605   // we will turn this bswap into something that will be lowered to logical ops
9606   // instead of emitting the bswap asm.  For now, we don't support 486 or lower
9607   // so don't worry about this.
9608
9609   // Verify this is a simple bswap.
9610   if (CI->getNumOperands() != 2 ||
9611       CI->getType() != CI->getOperand(1)->getType() ||
9612       !CI->getType()->isInteger())
9613     return false;
9614
9615   const IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
9616   if (!Ty || Ty->getBitWidth() % 16 != 0)
9617     return false;
9618
9619   // Okay, we can do this xform, do so now.
9620   const Type *Tys[] = { Ty };
9621   Module *M = CI->getParent()->getParent()->getParent();
9622   Constant *Int = Intrinsic::getDeclaration(M, Intrinsic::bswap, Tys, 1);
9623
9624   Value *Op = CI->getOperand(1);
9625   Op = CallInst::Create(Int, Op, CI->getName(), CI);
9626
9627   CI->replaceAllUsesWith(Op);
9628   CI->eraseFromParent();
9629   return true;
9630 }
9631
9632 bool X86TargetLowering::ExpandInlineAsm(CallInst *CI) const {
9633   InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue());
9634   std::vector<InlineAsm::ConstraintInfo> Constraints = IA->ParseConstraints();
9635
9636   std::string AsmStr = IA->getAsmString();
9637
9638   // TODO: should remove alternatives from the asmstring: "foo {a|b}" -> "foo a"
9639   SmallVector<StringRef, 4> AsmPieces;
9640   SplitString(AsmStr, AsmPieces, "\n");  // ; as separator?
9641
9642   switch (AsmPieces.size()) {
9643   default: return false;
9644   case 1:
9645     AsmStr = AsmPieces[0];
9646     AsmPieces.clear();
9647     SplitString(AsmStr, AsmPieces, " \t");  // Split with whitespace.
9648
9649     // bswap $0
9650     if (AsmPieces.size() == 2 &&
9651         (AsmPieces[0] == "bswap" ||
9652          AsmPieces[0] == "bswapq" ||
9653          AsmPieces[0] == "bswapl") &&
9654         (AsmPieces[1] == "$0" ||
9655          AsmPieces[1] == "${0:q}")) {
9656       // No need to check constraints, nothing other than the equivalent of
9657       // "=r,0" would be valid here.
9658       return LowerToBSwap(CI);
9659     }
9660     // rorw $$8, ${0:w}  -->  llvm.bswap.i16
9661     if (CI->getType()->isInteger(16) &&
9662         AsmPieces.size() == 3 &&
9663         AsmPieces[0] == "rorw" &&
9664         AsmPieces[1] == "$$8," &&
9665         AsmPieces[2] == "${0:w}" &&
9666         IA->getConstraintString() == "=r,0,~{dirflag},~{fpsr},~{flags},~{cc}") {
9667       return LowerToBSwap(CI);
9668     }
9669     break;
9670   case 3:
9671     if (CI->getType()->isInteger(64) &&
9672         Constraints.size() >= 2 &&
9673         Constraints[0].Codes.size() == 1 && Constraints[0].Codes[0] == "A" &&
9674         Constraints[1].Codes.size() == 1 && Constraints[1].Codes[0] == "0") {
9675       // bswap %eax / bswap %edx / xchgl %eax, %edx  -> llvm.bswap.i64
9676       SmallVector<StringRef, 4> Words;
9677       SplitString(AsmPieces[0], Words, " \t");
9678       if (Words.size() == 2 && Words[0] == "bswap" && Words[1] == "%eax") {
9679         Words.clear();
9680         SplitString(AsmPieces[1], Words, " \t");
9681         if (Words.size() == 2 && Words[0] == "bswap" && Words[1] == "%edx") {
9682           Words.clear();
9683           SplitString(AsmPieces[2], Words, " \t,");
9684           if (Words.size() == 3 && Words[0] == "xchgl" && Words[1] == "%eax" &&
9685               Words[2] == "%edx") {
9686             return LowerToBSwap(CI);
9687           }
9688         }
9689       }
9690     }
9691     break;
9692   }
9693   return false;
9694 }
9695
9696
9697
9698 /// getConstraintType - Given a constraint letter, return the type of
9699 /// constraint it is for this target.
9700 X86TargetLowering::ConstraintType
9701 X86TargetLowering::getConstraintType(const std::string &Constraint) const {
9702   if (Constraint.size() == 1) {
9703     switch (Constraint[0]) {
9704     case 'A':
9705       return C_Register;
9706     case 'f':
9707     case 'r':
9708     case 'R':
9709     case 'l':
9710     case 'q':
9711     case 'Q':
9712     case 'x':
9713     case 'y':
9714     case 'Y':
9715       return C_RegisterClass;
9716     case 'e':
9717     case 'Z':
9718       return C_Other;
9719     default:
9720       break;
9721     }
9722   }
9723   return TargetLowering::getConstraintType(Constraint);
9724 }
9725
9726 /// LowerXConstraint - try to replace an X constraint, which matches anything,
9727 /// with another that has more specific requirements based on the type of the
9728 /// corresponding operand.
9729 const char *X86TargetLowering::
9730 LowerXConstraint(EVT ConstraintVT) const {
9731   // FP X constraints get lowered to SSE1/2 registers if available, otherwise
9732   // 'f' like normal targets.
9733   if (ConstraintVT.isFloatingPoint()) {
9734     if (Subtarget->hasSSE2())
9735       return "Y";
9736     if (Subtarget->hasSSE1())
9737       return "x";
9738   }
9739
9740   return TargetLowering::LowerXConstraint(ConstraintVT);
9741 }
9742
9743 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
9744 /// vector.  If it is invalid, don't add anything to Ops.
9745 void X86TargetLowering::LowerAsmOperandForConstraint(SDValue Op,
9746                                                      char Constraint,
9747                                                      bool hasMemory,
9748                                                      std::vector<SDValue>&Ops,
9749                                                      SelectionDAG &DAG) const {
9750   SDValue Result(0, 0);
9751
9752   switch (Constraint) {
9753   default: break;
9754   case 'I':
9755     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
9756       if (C->getZExtValue() <= 31) {
9757         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
9758         break;
9759       }
9760     }
9761     return;
9762   case 'J':
9763     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
9764       if (C->getZExtValue() <= 63) {
9765         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
9766         break;
9767       }
9768     }
9769     return;
9770   case 'K':
9771     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
9772       if ((int8_t)C->getSExtValue() == C->getSExtValue()) {
9773         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
9774         break;
9775       }
9776     }
9777     return;
9778   case 'N':
9779     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
9780       if (C->getZExtValue() <= 255) {
9781         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
9782         break;
9783       }
9784     }
9785     return;
9786   case 'e': {
9787     // 32-bit signed value
9788     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
9789       const ConstantInt *CI = C->getConstantIntValue();
9790       if (CI->isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
9791                                   C->getSExtValue())) {
9792         // Widen to 64 bits here to get it sign extended.
9793         Result = DAG.getTargetConstant(C->getSExtValue(), MVT::i64);
9794         break;
9795       }
9796     // FIXME gcc accepts some relocatable values here too, but only in certain
9797     // memory models; it's complicated.
9798     }
9799     return;
9800   }
9801   case 'Z': {
9802     // 32-bit unsigned value
9803     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
9804       const ConstantInt *CI = C->getConstantIntValue();
9805       if (CI->isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
9806                                   C->getZExtValue())) {
9807         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
9808         break;
9809       }
9810     }
9811     // FIXME gcc accepts some relocatable values here too, but only in certain
9812     // memory models; it's complicated.
9813     return;
9814   }
9815   case 'i': {
9816     // Literal immediates are always ok.
9817     if (ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op)) {
9818       // Widen to 64 bits here to get it sign extended.
9819       Result = DAG.getTargetConstant(CST->getSExtValue(), MVT::i64);
9820       break;
9821     }
9822
9823     // If we are in non-pic codegen mode, we allow the address of a global (with
9824     // an optional displacement) to be used with 'i'.
9825     GlobalAddressSDNode *GA = 0;
9826     int64_t Offset = 0;
9827
9828     // Match either (GA), (GA+C), (GA+C1+C2), etc.
9829     while (1) {
9830       if ((GA = dyn_cast<GlobalAddressSDNode>(Op))) {
9831         Offset += GA->getOffset();
9832         break;
9833       } else if (Op.getOpcode() == ISD::ADD) {
9834         if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
9835           Offset += C->getZExtValue();
9836           Op = Op.getOperand(0);
9837           continue;
9838         }
9839       } else if (Op.getOpcode() == ISD::SUB) {
9840         if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
9841           Offset += -C->getZExtValue();
9842           Op = Op.getOperand(0);
9843           continue;
9844         }
9845       }
9846
9847       // Otherwise, this isn't something we can handle, reject it.
9848       return;
9849     }
9850
9851     GlobalValue *GV = GA->getGlobal();
9852     // If we require an extra load to get this address, as in PIC mode, we
9853     // can't accept it.
9854     if (isGlobalStubReference(Subtarget->ClassifyGlobalReference(GV,
9855                                                         getTargetMachine())))
9856       return;
9857
9858     if (hasMemory)
9859       Op = LowerGlobalAddress(GV, Op.getDebugLoc(), Offset, DAG);
9860     else
9861       Op = DAG.getTargetGlobalAddress(GV, GA->getValueType(0), Offset);
9862     Result = Op;
9863     break;
9864   }
9865   }
9866
9867   if (Result.getNode()) {
9868     Ops.push_back(Result);
9869     return;
9870   }
9871   return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, hasMemory,
9872                                                       Ops, DAG);
9873 }
9874
9875 std::vector<unsigned> X86TargetLowering::
9876 getRegClassForInlineAsmConstraint(const std::string &Constraint,
9877                                   EVT VT) const {
9878   if (Constraint.size() == 1) {
9879     // FIXME: not handling fp-stack yet!
9880     switch (Constraint[0]) {      // GCC X86 Constraint Letters
9881     default: break;  // Unknown constraint letter
9882     case 'q':   // GENERAL_REGS in 64-bit mode, Q_REGS in 32-bit mode.
9883       if (Subtarget->is64Bit()) {
9884         if (VT == MVT::i32)
9885           return make_vector<unsigned>(X86::EAX, X86::EDX, X86::ECX, X86::EBX,
9886                                        X86::ESI, X86::EDI, X86::R8D, X86::R9D,
9887                                        X86::R10D,X86::R11D,X86::R12D,
9888                                        X86::R13D,X86::R14D,X86::R15D,
9889                                        X86::EBP, X86::ESP, 0);
9890         else if (VT == MVT::i16)
9891           return make_vector<unsigned>(X86::AX,  X86::DX,  X86::CX, X86::BX,
9892                                        X86::SI,  X86::DI,  X86::R8W,X86::R9W,
9893                                        X86::R10W,X86::R11W,X86::R12W,
9894                                        X86::R13W,X86::R14W,X86::R15W,
9895                                        X86::BP,  X86::SP, 0);
9896         else if (VT == MVT::i8)
9897           return make_vector<unsigned>(X86::AL,  X86::DL,  X86::CL, X86::BL,
9898                                        X86::SIL, X86::DIL, X86::R8B,X86::R9B,
9899                                        X86::R10B,X86::R11B,X86::R12B,
9900                                        X86::R13B,X86::R14B,X86::R15B,
9901                                        X86::BPL, X86::SPL, 0);
9902
9903         else if (VT == MVT::i64)
9904           return make_vector<unsigned>(X86::RAX, X86::RDX, X86::RCX, X86::RBX,
9905                                        X86::RSI, X86::RDI, X86::R8,  X86::R9,
9906                                        X86::R10, X86::R11, X86::R12,
9907                                        X86::R13, X86::R14, X86::R15,
9908                                        X86::RBP, X86::RSP, 0);
9909
9910         break;
9911       }
9912       // 32-bit fallthrough
9913     case 'Q':   // Q_REGS
9914       if (VT == MVT::i32)
9915         return make_vector<unsigned>(X86::EAX, X86::EDX, X86::ECX, X86::EBX, 0);
9916       else if (VT == MVT::i16)
9917         return make_vector<unsigned>(X86::AX, X86::DX, X86::CX, X86::BX, 0);
9918       else if (VT == MVT::i8)
9919         return make_vector<unsigned>(X86::AL, X86::DL, X86::CL, X86::BL, 0);
9920       else if (VT == MVT::i64)
9921         return make_vector<unsigned>(X86::RAX, X86::RDX, X86::RCX, X86::RBX, 0);
9922       break;
9923     }
9924   }
9925
9926   return std::vector<unsigned>();
9927 }
9928
9929 std::pair<unsigned, const TargetRegisterClass*>
9930 X86TargetLowering::getRegForInlineAsmConstraint(const std::string &Constraint,
9931                                                 EVT VT) const {
9932   // First, see if this is a constraint that directly corresponds to an LLVM
9933   // register class.
9934   if (Constraint.size() == 1) {
9935     // GCC Constraint Letters
9936     switch (Constraint[0]) {
9937     default: break;
9938     case 'r':   // GENERAL_REGS
9939     case 'l':   // INDEX_REGS
9940       if (VT == MVT::i8)
9941         return std::make_pair(0U, X86::GR8RegisterClass);
9942       if (VT == MVT::i16)
9943         return std::make_pair(0U, X86::GR16RegisterClass);
9944       if (VT == MVT::i32 || !Subtarget->is64Bit())
9945         return std::make_pair(0U, X86::GR32RegisterClass);
9946       return std::make_pair(0U, X86::GR64RegisterClass);
9947     case 'R':   // LEGACY_REGS
9948       if (VT == MVT::i8)
9949         return std::make_pair(0U, X86::GR8_NOREXRegisterClass);
9950       if (VT == MVT::i16)
9951         return std::make_pair(0U, X86::GR16_NOREXRegisterClass);
9952       if (VT == MVT::i32 || !Subtarget->is64Bit())
9953         return std::make_pair(0U, X86::GR32_NOREXRegisterClass);
9954       return std::make_pair(0U, X86::GR64_NOREXRegisterClass);
9955     case 'f':  // FP Stack registers.
9956       // If SSE is enabled for this VT, use f80 to ensure the isel moves the
9957       // value to the correct fpstack register class.
9958       if (VT == MVT::f32 && !isScalarFPTypeInSSEReg(VT))
9959         return std::make_pair(0U, X86::RFP32RegisterClass);
9960       if (VT == MVT::f64 && !isScalarFPTypeInSSEReg(VT))
9961         return std::make_pair(0U, X86::RFP64RegisterClass);
9962       return std::make_pair(0U, X86::RFP80RegisterClass);
9963     case 'y':   // MMX_REGS if MMX allowed.
9964       if (!Subtarget->hasMMX()) break;
9965       return std::make_pair(0U, X86::VR64RegisterClass);
9966     case 'Y':   // SSE_REGS if SSE2 allowed
9967       if (!Subtarget->hasSSE2()) break;
9968       // FALL THROUGH.
9969     case 'x':   // SSE_REGS if SSE1 allowed
9970       if (!Subtarget->hasSSE1()) break;
9971
9972       switch (VT.getSimpleVT().SimpleTy) {
9973       default: break;
9974       // Scalar SSE types.
9975       case MVT::f32:
9976       case MVT::i32:
9977         return std::make_pair(0U, X86::FR32RegisterClass);
9978       case MVT::f64:
9979       case MVT::i64:
9980         return std::make_pair(0U, X86::FR64RegisterClass);
9981       // Vector types.
9982       case MVT::v16i8:
9983       case MVT::v8i16:
9984       case MVT::v4i32:
9985       case MVT::v2i64:
9986       case MVT::v4f32:
9987       case MVT::v2f64:
9988         return std::make_pair(0U, X86::VR128RegisterClass);
9989       }
9990       break;
9991     }
9992   }
9993
9994   // Use the default implementation in TargetLowering to convert the register
9995   // constraint into a member of a register class.
9996   std::pair<unsigned, const TargetRegisterClass*> Res;
9997   Res = TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
9998
9999   // Not found as a standard register?
10000   if (Res.second == 0) {
10001     // Map st(0) -> st(7) -> ST0
10002     if (Constraint.size() == 7 && Constraint[0] == '{' &&
10003         tolower(Constraint[1]) == 's' &&
10004         tolower(Constraint[2]) == 't' &&
10005         Constraint[3] == '(' &&
10006         (Constraint[4] >= '0' && Constraint[4] <= '7') &&
10007         Constraint[5] == ')' &&
10008         Constraint[6] == '}') {
10009
10010       Res.first = X86::ST0+Constraint[4]-'0';
10011       Res.second = X86::RFP80RegisterClass;
10012       return Res;
10013     }
10014
10015     // GCC allows "st(0)" to be called just plain "st".
10016     if (StringRef("{st}").equals_lower(Constraint)) {
10017       Res.first = X86::ST0;
10018       Res.second = X86::RFP80RegisterClass;
10019       return Res;
10020     }
10021
10022     // flags -> EFLAGS
10023     if (StringRef("{flags}").equals_lower(Constraint)) {
10024       Res.first = X86::EFLAGS;
10025       Res.second = X86::CCRRegisterClass;
10026       return Res;
10027     }
10028
10029     // 'A' means EAX + EDX.
10030     if (Constraint == "A") {
10031       Res.first = X86::EAX;
10032       Res.second = X86::GR32_ADRegisterClass;
10033       return Res;
10034     }
10035     return Res;
10036   }
10037
10038   // Otherwise, check to see if this is a register class of the wrong value
10039   // type.  For example, we want to map "{ax},i32" -> {eax}, we don't want it to
10040   // turn into {ax},{dx}.
10041   if (Res.second->hasType(VT))
10042     return Res;   // Correct type already, nothing to do.
10043
10044   // All of the single-register GCC register classes map their values onto
10045   // 16-bit register pieces "ax","dx","cx","bx","si","di","bp","sp".  If we
10046   // really want an 8-bit or 32-bit register, map to the appropriate register
10047   // class and return the appropriate register.
10048   if (Res.second == X86::GR16RegisterClass) {
10049     if (VT == MVT::i8) {
10050       unsigned DestReg = 0;
10051       switch (Res.first) {
10052       default: break;
10053       case X86::AX: DestReg = X86::AL; break;
10054       case X86::DX: DestReg = X86::DL; break;
10055       case X86::CX: DestReg = X86::CL; break;
10056       case X86::BX: DestReg = X86::BL; break;
10057       }
10058       if (DestReg) {
10059         Res.first = DestReg;
10060         Res.second = X86::GR8RegisterClass;
10061       }
10062     } else if (VT == MVT::i32) {
10063       unsigned DestReg = 0;
10064       switch (Res.first) {
10065       default: break;
10066       case X86::AX: DestReg = X86::EAX; break;
10067       case X86::DX: DestReg = X86::EDX; break;
10068       case X86::CX: DestReg = X86::ECX; break;
10069       case X86::BX: DestReg = X86::EBX; break;
10070       case X86::SI: DestReg = X86::ESI; break;
10071       case X86::DI: DestReg = X86::EDI; break;
10072       case X86::BP: DestReg = X86::EBP; break;
10073       case X86::SP: DestReg = X86::ESP; break;
10074       }
10075       if (DestReg) {
10076         Res.first = DestReg;
10077         Res.second = X86::GR32RegisterClass;
10078       }
10079     } else if (VT == MVT::i64) {
10080       unsigned DestReg = 0;
10081       switch (Res.first) {
10082       default: break;
10083       case X86::AX: DestReg = X86::RAX; break;
10084       case X86::DX: DestReg = X86::RDX; break;
10085       case X86::CX: DestReg = X86::RCX; break;
10086       case X86::BX: DestReg = X86::RBX; break;
10087       case X86::SI: DestReg = X86::RSI; break;
10088       case X86::DI: DestReg = X86::RDI; break;
10089       case X86::BP: DestReg = X86::RBP; break;
10090       case X86::SP: DestReg = X86::RSP; break;
10091       }
10092       if (DestReg) {
10093         Res.first = DestReg;
10094         Res.second = X86::GR64RegisterClass;
10095       }
10096     }
10097   } else if (Res.second == X86::FR32RegisterClass ||
10098              Res.second == X86::FR64RegisterClass ||
10099              Res.second == X86::VR128RegisterClass) {
10100     // Handle references to XMM physical registers that got mapped into the
10101     // wrong class.  This can happen with constraints like {xmm0} where the
10102     // target independent register mapper will just pick the first match it can
10103     // find, ignoring the required type.
10104     if (VT == MVT::f32)
10105       Res.second = X86::FR32RegisterClass;
10106     else if (VT == MVT::f64)
10107       Res.second = X86::FR64RegisterClass;
10108     else if (X86::VR128RegisterClass->hasType(VT))
10109       Res.second = X86::VR128RegisterClass;
10110   }
10111
10112   return Res;
10113 }
10114
10115 //===----------------------------------------------------------------------===//
10116 //                           X86 Widen vector type
10117 //===----------------------------------------------------------------------===//
10118
10119 /// getWidenVectorType: given a vector type, returns the type to widen
10120 /// to (e.g., v7i8 to v8i8). If the vector type is legal, it returns itself.
10121 /// If there is no vector type that we want to widen to, returns MVT::Other
10122 /// When and where to widen is target dependent based on the cost of
10123 /// scalarizing vs using the wider vector type.
10124
10125 EVT X86TargetLowering::getWidenVectorType(EVT VT) const {
10126   assert(VT.isVector());
10127   if (isTypeLegal(VT))
10128     return VT;
10129
10130   // TODO: In computeRegisterProperty, we can compute the list of legal vector
10131   //       type based on element type.  This would speed up our search (though
10132   //       it may not be worth it since the size of the list is relatively
10133   //       small).
10134   EVT EltVT = VT.getVectorElementType();
10135   unsigned NElts = VT.getVectorNumElements();
10136
10137   // On X86, it make sense to widen any vector wider than 1
10138   if (NElts <= 1)
10139     return MVT::Other;
10140
10141   for (unsigned nVT = MVT::FIRST_VECTOR_VALUETYPE;
10142        nVT <= MVT::LAST_VECTOR_VALUETYPE; ++nVT) {
10143     EVT SVT = (MVT::SimpleValueType)nVT;
10144
10145     if (isTypeLegal(SVT) &&
10146         SVT.getVectorElementType() == EltVT &&
10147         SVT.getVectorNumElements() > NElts)
10148       return SVT;
10149   }
10150   return MVT::Other;
10151 }