switch MCSectionCOFF from a syntactic to semantic representation,
[oota-llvm.git] / lib / Target / X86 / X86ISelLowering.cpp
1 //===-- X86ISelLowering.cpp - X86 DAG Lowering Implementation -------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file defines the interfaces that X86 uses to lower LLVM code into a
11 // selection DAG.
12 //
13 //===----------------------------------------------------------------------===//
14
15 #define DEBUG_TYPE "x86-isel"
16 #include "X86.h"
17 #include "X86InstrBuilder.h"
18 #include "X86ISelLowering.h"
19 #include "X86TargetMachine.h"
20 #include "X86TargetObjectFile.h"
21 #include "llvm/CallingConv.h"
22 #include "llvm/Constants.h"
23 #include "llvm/DerivedTypes.h"
24 #include "llvm/GlobalAlias.h"
25 #include "llvm/GlobalVariable.h"
26 #include "llvm/Function.h"
27 #include "llvm/Instructions.h"
28 #include "llvm/Intrinsics.h"
29 #include "llvm/LLVMContext.h"
30 #include "llvm/CodeGen/MachineFrameInfo.h"
31 #include "llvm/CodeGen/MachineFunction.h"
32 #include "llvm/CodeGen/MachineInstrBuilder.h"
33 #include "llvm/CodeGen/MachineJumpTableInfo.h"
34 #include "llvm/CodeGen/MachineModuleInfo.h"
35 #include "llvm/CodeGen/MachineRegisterInfo.h"
36 #include "llvm/CodeGen/PseudoSourceValue.h"
37 #include "llvm/MC/MCAsmInfo.h"
38 #include "llvm/MC/MCContext.h"
39 #include "llvm/MC/MCExpr.h"
40 #include "llvm/MC/MCSymbol.h"
41 #include "llvm/ADT/BitVector.h"
42 #include "llvm/ADT/SmallSet.h"
43 #include "llvm/ADT/Statistic.h"
44 #include "llvm/ADT/StringExtras.h"
45 #include "llvm/ADT/VectorExtras.h"
46 #include "llvm/Support/CommandLine.h"
47 #include "llvm/Support/Debug.h"
48 #include "llvm/Support/Dwarf.h"
49 #include "llvm/Support/ErrorHandling.h"
50 #include "llvm/Support/MathExtras.h"
51 #include "llvm/Support/raw_ostream.h"
52 using namespace llvm;
53 using namespace dwarf;
54
55 STATISTIC(NumTailCalls, "Number of tail calls");
56
57 static cl::opt<bool>
58 DisableMMX("disable-mmx", cl::Hidden, cl::desc("Disable use of MMX"));
59
60 // Forward declarations.
61 static SDValue getMOVL(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
62                        SDValue V2);
63
64 static TargetLoweringObjectFile *createTLOF(X86TargetMachine &TM) {
65   switch (TM.getSubtarget<X86Subtarget>().TargetType) {
66   default: llvm_unreachable("unknown subtarget type");
67   case X86Subtarget::isDarwin:
68     if (TM.getSubtarget<X86Subtarget>().is64Bit())
69       return new X8664_MachoTargetObjectFile();
70     return new TargetLoweringObjectFileMachO();
71   case X86Subtarget::isELF:
72    if (TM.getSubtarget<X86Subtarget>().is64Bit())
73      return new X8664_ELFTargetObjectFile(TM);
74     return new X8632_ELFTargetObjectFile(TM);
75   case X86Subtarget::isMingw:
76   case X86Subtarget::isCygwin:
77   case X86Subtarget::isWindows:
78     return new TargetLoweringObjectFileCOFF();
79   }
80 }
81
82 X86TargetLowering::X86TargetLowering(X86TargetMachine &TM)
83   : TargetLowering(TM, createTLOF(TM)) {
84   Subtarget = &TM.getSubtarget<X86Subtarget>();
85   X86ScalarSSEf64 = Subtarget->hasSSE2();
86   X86ScalarSSEf32 = Subtarget->hasSSE1();
87   X86StackPtr = Subtarget->is64Bit() ? X86::RSP : X86::ESP;
88
89   RegInfo = TM.getRegisterInfo();
90   TD = getTargetData();
91
92   // Set up the TargetLowering object.
93
94   // X86 is weird, it always uses i8 for shift amounts and setcc results.
95   setShiftAmountType(MVT::i8);
96   setBooleanContents(ZeroOrOneBooleanContent);
97   setSchedulingPreference(SchedulingForRegPressure);
98   setStackPointerRegisterToSaveRestore(X86StackPtr);
99
100   if (Subtarget->isTargetDarwin()) {
101     // Darwin should use _setjmp/_longjmp instead of setjmp/longjmp.
102     setUseUnderscoreSetJmp(false);
103     setUseUnderscoreLongJmp(false);
104   } else if (Subtarget->isTargetMingw()) {
105     // MS runtime is weird: it exports _setjmp, but longjmp!
106     setUseUnderscoreSetJmp(true);
107     setUseUnderscoreLongJmp(false);
108   } else {
109     setUseUnderscoreSetJmp(true);
110     setUseUnderscoreLongJmp(true);
111   }
112
113   // Set up the register classes.
114   addRegisterClass(MVT::i8, X86::GR8RegisterClass);
115   addRegisterClass(MVT::i16, X86::GR16RegisterClass);
116   addRegisterClass(MVT::i32, X86::GR32RegisterClass);
117   if (Subtarget->is64Bit())
118     addRegisterClass(MVT::i64, X86::GR64RegisterClass);
119
120   setLoadExtAction(ISD::SEXTLOAD, MVT::i1, Promote);
121
122   // We don't accept any truncstore of integer registers.
123   setTruncStoreAction(MVT::i64, MVT::i32, Expand);
124   setTruncStoreAction(MVT::i64, MVT::i16, Expand);
125   setTruncStoreAction(MVT::i64, MVT::i8 , Expand);
126   setTruncStoreAction(MVT::i32, MVT::i16, Expand);
127   setTruncStoreAction(MVT::i32, MVT::i8 , Expand);
128   setTruncStoreAction(MVT::i16, MVT::i8,  Expand);
129
130   // SETOEQ and SETUNE require checking two conditions.
131   setCondCodeAction(ISD::SETOEQ, MVT::f32, Expand);
132   setCondCodeAction(ISD::SETOEQ, MVT::f64, Expand);
133   setCondCodeAction(ISD::SETOEQ, MVT::f80, Expand);
134   setCondCodeAction(ISD::SETUNE, MVT::f32, Expand);
135   setCondCodeAction(ISD::SETUNE, MVT::f64, Expand);
136   setCondCodeAction(ISD::SETUNE, MVT::f80, Expand);
137
138   // Promote all UINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have this
139   // operation.
140   setOperationAction(ISD::UINT_TO_FP       , MVT::i1   , Promote);
141   setOperationAction(ISD::UINT_TO_FP       , MVT::i8   , Promote);
142   setOperationAction(ISD::UINT_TO_FP       , MVT::i16  , Promote);
143
144   if (Subtarget->is64Bit()) {
145     setOperationAction(ISD::UINT_TO_FP     , MVT::i32  , Promote);
146     setOperationAction(ISD::UINT_TO_FP     , MVT::i64  , Expand);
147   } else if (!UseSoftFloat) {
148     if (X86ScalarSSEf64) {
149       // We have an impenetrably clever algorithm for ui64->double only.
150       setOperationAction(ISD::UINT_TO_FP   , MVT::i64  , Custom);
151     }
152     // We have an algorithm for SSE2, and we turn this into a 64-bit
153     // FILD for other targets.
154     setOperationAction(ISD::UINT_TO_FP   , MVT::i32  , Custom);
155   }
156
157   // Promote i1/i8 SINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have
158   // this operation.
159   setOperationAction(ISD::SINT_TO_FP       , MVT::i1   , Promote);
160   setOperationAction(ISD::SINT_TO_FP       , MVT::i8   , Promote);
161
162   if (!UseSoftFloat) {
163     // SSE has no i16 to fp conversion, only i32
164     if (X86ScalarSSEf32) {
165       setOperationAction(ISD::SINT_TO_FP     , MVT::i16  , Promote);
166       // f32 and f64 cases are Legal, f80 case is not
167       setOperationAction(ISD::SINT_TO_FP     , MVT::i32  , Custom);
168     } else {
169       setOperationAction(ISD::SINT_TO_FP     , MVT::i16  , Custom);
170       setOperationAction(ISD::SINT_TO_FP     , MVT::i32  , Custom);
171     }
172   } else {
173     setOperationAction(ISD::SINT_TO_FP     , MVT::i16  , Promote);
174     setOperationAction(ISD::SINT_TO_FP     , MVT::i32  , Promote);
175   }
176
177   // In 32-bit mode these are custom lowered.  In 64-bit mode F32 and F64
178   // are Legal, f80 is custom lowered.
179   setOperationAction(ISD::FP_TO_SINT     , MVT::i64  , Custom);
180   setOperationAction(ISD::SINT_TO_FP     , MVT::i64  , Custom);
181
182   // Promote i1/i8 FP_TO_SINT to larger FP_TO_SINTS's, as X86 doesn't have
183   // this operation.
184   setOperationAction(ISD::FP_TO_SINT       , MVT::i1   , Promote);
185   setOperationAction(ISD::FP_TO_SINT       , MVT::i8   , Promote);
186
187   if (X86ScalarSSEf32) {
188     setOperationAction(ISD::FP_TO_SINT     , MVT::i16  , Promote);
189     // f32 and f64 cases are Legal, f80 case is not
190     setOperationAction(ISD::FP_TO_SINT     , MVT::i32  , Custom);
191   } else {
192     setOperationAction(ISD::FP_TO_SINT     , MVT::i16  , Custom);
193     setOperationAction(ISD::FP_TO_SINT     , MVT::i32  , Custom);
194   }
195
196   // Handle FP_TO_UINT by promoting the destination to a larger signed
197   // conversion.
198   setOperationAction(ISD::FP_TO_UINT       , MVT::i1   , Promote);
199   setOperationAction(ISD::FP_TO_UINT       , MVT::i8   , Promote);
200   setOperationAction(ISD::FP_TO_UINT       , MVT::i16  , Promote);
201
202   if (Subtarget->is64Bit()) {
203     setOperationAction(ISD::FP_TO_UINT     , MVT::i64  , Expand);
204     setOperationAction(ISD::FP_TO_UINT     , MVT::i32  , Promote);
205   } else if (!UseSoftFloat) {
206     if (X86ScalarSSEf32 && !Subtarget->hasSSE3())
207       // Expand FP_TO_UINT into a select.
208       // FIXME: We would like to use a Custom expander here eventually to do
209       // the optimal thing for SSE vs. the default expansion in the legalizer.
210       setOperationAction(ISD::FP_TO_UINT   , MVT::i32  , Expand);
211     else
212       // With SSE3 we can use fisttpll to convert to a signed i64; without
213       // SSE, we're stuck with a fistpll.
214       setOperationAction(ISD::FP_TO_UINT   , MVT::i32  , Custom);
215   }
216
217   // TODO: when we have SSE, these could be more efficient, by using movd/movq.
218   if (!X86ScalarSSEf64) {
219     setOperationAction(ISD::BIT_CONVERT      , MVT::f32  , Expand);
220     setOperationAction(ISD::BIT_CONVERT      , MVT::i32  , Expand);
221   }
222
223   // Scalar integer divide and remainder are lowered to use operations that
224   // produce two results, to match the available instructions. This exposes
225   // the two-result form to trivial CSE, which is able to combine x/y and x%y
226   // into a single instruction.
227   //
228   // Scalar integer multiply-high is also lowered to use two-result
229   // operations, to match the available instructions. However, plain multiply
230   // (low) operations are left as Legal, as there are single-result
231   // instructions for this in x86. Using the two-result multiply instructions
232   // when both high and low results are needed must be arranged by dagcombine.
233   setOperationAction(ISD::MULHS           , MVT::i8    , Expand);
234   setOperationAction(ISD::MULHU           , MVT::i8    , Expand);
235   setOperationAction(ISD::SDIV            , MVT::i8    , Expand);
236   setOperationAction(ISD::UDIV            , MVT::i8    , Expand);
237   setOperationAction(ISD::SREM            , MVT::i8    , Expand);
238   setOperationAction(ISD::UREM            , MVT::i8    , Expand);
239   setOperationAction(ISD::MULHS           , MVT::i16   , Expand);
240   setOperationAction(ISD::MULHU           , MVT::i16   , Expand);
241   setOperationAction(ISD::SDIV            , MVT::i16   , Expand);
242   setOperationAction(ISD::UDIV            , MVT::i16   , Expand);
243   setOperationAction(ISD::SREM            , MVT::i16   , Expand);
244   setOperationAction(ISD::UREM            , MVT::i16   , Expand);
245   setOperationAction(ISD::MULHS           , MVT::i32   , Expand);
246   setOperationAction(ISD::MULHU           , MVT::i32   , Expand);
247   setOperationAction(ISD::SDIV            , MVT::i32   , Expand);
248   setOperationAction(ISD::UDIV            , MVT::i32   , Expand);
249   setOperationAction(ISD::SREM            , MVT::i32   , Expand);
250   setOperationAction(ISD::UREM            , MVT::i32   , Expand);
251   setOperationAction(ISD::MULHS           , MVT::i64   , Expand);
252   setOperationAction(ISD::MULHU           , MVT::i64   , Expand);
253   setOperationAction(ISD::SDIV            , MVT::i64   , Expand);
254   setOperationAction(ISD::UDIV            , MVT::i64   , Expand);
255   setOperationAction(ISD::SREM            , MVT::i64   , Expand);
256   setOperationAction(ISD::UREM            , MVT::i64   , Expand);
257
258   setOperationAction(ISD::BR_JT            , MVT::Other, Expand);
259   setOperationAction(ISD::BRCOND           , MVT::Other, Custom);
260   setOperationAction(ISD::BR_CC            , MVT::Other, Expand);
261   setOperationAction(ISD::SELECT_CC        , MVT::Other, Expand);
262   if (Subtarget->is64Bit())
263     setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i32, Legal);
264   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16  , Legal);
265   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8   , Legal);
266   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1   , Expand);
267   setOperationAction(ISD::FP_ROUND_INREG   , MVT::f32  , Expand);
268   setOperationAction(ISD::FREM             , MVT::f32  , Expand);
269   setOperationAction(ISD::FREM             , MVT::f64  , Expand);
270   setOperationAction(ISD::FREM             , MVT::f80  , Expand);
271   setOperationAction(ISD::FLT_ROUNDS_      , MVT::i32  , Custom);
272
273   setOperationAction(ISD::CTPOP            , MVT::i8   , Expand);
274   setOperationAction(ISD::CTTZ             , MVT::i8   , Custom);
275   setOperationAction(ISD::CTLZ             , MVT::i8   , Custom);
276   setOperationAction(ISD::CTPOP            , MVT::i16  , Expand);
277   setOperationAction(ISD::CTTZ             , MVT::i16  , Custom);
278   setOperationAction(ISD::CTLZ             , MVT::i16  , Custom);
279   setOperationAction(ISD::CTPOP            , MVT::i32  , Expand);
280   setOperationAction(ISD::CTTZ             , MVT::i32  , Custom);
281   setOperationAction(ISD::CTLZ             , MVT::i32  , Custom);
282   if (Subtarget->is64Bit()) {
283     setOperationAction(ISD::CTPOP          , MVT::i64  , Expand);
284     setOperationAction(ISD::CTTZ           , MVT::i64  , Custom);
285     setOperationAction(ISD::CTLZ           , MVT::i64  , Custom);
286   }
287
288   setOperationAction(ISD::READCYCLECOUNTER , MVT::i64  , Custom);
289   setOperationAction(ISD::BSWAP            , MVT::i16  , Expand);
290
291   // These should be promoted to a larger select which is supported.
292   setOperationAction(ISD::SELECT          , MVT::i1   , Promote);
293   // X86 wants to expand cmov itself.
294   setOperationAction(ISD::SELECT          , MVT::i8   , Custom);
295   setOperationAction(ISD::SELECT        , MVT::i16  , Custom);
296   setOperationAction(ISD::SELECT          , MVT::i32  , Custom);
297   setOperationAction(ISD::SELECT          , MVT::f32  , Custom);
298   setOperationAction(ISD::SELECT          , MVT::f64  , Custom);
299   setOperationAction(ISD::SELECT          , MVT::f80  , Custom);
300   setOperationAction(ISD::SETCC           , MVT::i8   , Custom);
301   setOperationAction(ISD::SETCC           , MVT::i16  , Custom);
302   setOperationAction(ISD::SETCC           , MVT::i32  , Custom);
303   setOperationAction(ISD::SETCC           , MVT::f32  , Custom);
304   setOperationAction(ISD::SETCC           , MVT::f64  , Custom);
305   setOperationAction(ISD::SETCC           , MVT::f80  , Custom);
306   if (Subtarget->is64Bit()) {
307     setOperationAction(ISD::SELECT        , MVT::i64  , Custom);
308     setOperationAction(ISD::SETCC         , MVT::i64  , Custom);
309   }
310   setOperationAction(ISD::EH_RETURN       , MVT::Other, Custom);
311
312   // Darwin ABI issue.
313   setOperationAction(ISD::ConstantPool    , MVT::i32  , Custom);
314   setOperationAction(ISD::JumpTable       , MVT::i32  , Custom);
315   setOperationAction(ISD::GlobalAddress   , MVT::i32  , Custom);
316   setOperationAction(ISD::GlobalTLSAddress, MVT::i32  , Custom);
317   if (Subtarget->is64Bit())
318     setOperationAction(ISD::GlobalTLSAddress, MVT::i64, Custom);
319   setOperationAction(ISD::ExternalSymbol  , MVT::i32  , Custom);
320   setOperationAction(ISD::BlockAddress    , MVT::i32  , Custom);
321   if (Subtarget->is64Bit()) {
322     setOperationAction(ISD::ConstantPool  , MVT::i64  , Custom);
323     setOperationAction(ISD::JumpTable     , MVT::i64  , Custom);
324     setOperationAction(ISD::GlobalAddress , MVT::i64  , Custom);
325     setOperationAction(ISD::ExternalSymbol, MVT::i64  , Custom);
326     setOperationAction(ISD::BlockAddress  , MVT::i64  , Custom);
327   }
328   // 64-bit addm sub, shl, sra, srl (iff 32-bit x86)
329   setOperationAction(ISD::SHL_PARTS       , MVT::i32  , Custom);
330   setOperationAction(ISD::SRA_PARTS       , MVT::i32  , Custom);
331   setOperationAction(ISD::SRL_PARTS       , MVT::i32  , Custom);
332   if (Subtarget->is64Bit()) {
333     setOperationAction(ISD::SHL_PARTS     , MVT::i64  , Custom);
334     setOperationAction(ISD::SRA_PARTS     , MVT::i64  , Custom);
335     setOperationAction(ISD::SRL_PARTS     , MVT::i64  , Custom);
336   }
337
338   if (Subtarget->hasSSE1())
339     setOperationAction(ISD::PREFETCH      , MVT::Other, Legal);
340
341   if (!Subtarget->hasSSE2())
342     setOperationAction(ISD::MEMBARRIER    , MVT::Other, Expand);
343
344   // Expand certain atomics
345   setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i8, Custom);
346   setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i16, Custom);
347   setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i32, Custom);
348   setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i64, Custom);
349
350   setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i8, Custom);
351   setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i16, Custom);
352   setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i32, Custom);
353   setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i64, Custom);
354
355   if (!Subtarget->is64Bit()) {
356     setOperationAction(ISD::ATOMIC_LOAD_ADD, MVT::i64, Custom);
357     setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i64, Custom);
358     setOperationAction(ISD::ATOMIC_LOAD_AND, MVT::i64, Custom);
359     setOperationAction(ISD::ATOMIC_LOAD_OR, MVT::i64, Custom);
360     setOperationAction(ISD::ATOMIC_LOAD_XOR, MVT::i64, Custom);
361     setOperationAction(ISD::ATOMIC_LOAD_NAND, MVT::i64, Custom);
362     setOperationAction(ISD::ATOMIC_SWAP, MVT::i64, Custom);
363   }
364
365   // FIXME - use subtarget debug flags
366   if (!Subtarget->isTargetDarwin() &&
367       !Subtarget->isTargetELF() &&
368       !Subtarget->isTargetCygMing()) {
369     setOperationAction(ISD::EH_LABEL, MVT::Other, Expand);
370   }
371
372   setOperationAction(ISD::EXCEPTIONADDR, MVT::i64, Expand);
373   setOperationAction(ISD::EHSELECTION,   MVT::i64, Expand);
374   setOperationAction(ISD::EXCEPTIONADDR, MVT::i32, Expand);
375   setOperationAction(ISD::EHSELECTION,   MVT::i32, Expand);
376   if (Subtarget->is64Bit()) {
377     setExceptionPointerRegister(X86::RAX);
378     setExceptionSelectorRegister(X86::RDX);
379   } else {
380     setExceptionPointerRegister(X86::EAX);
381     setExceptionSelectorRegister(X86::EDX);
382   }
383   setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i32, Custom);
384   setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i64, Custom);
385
386   setOperationAction(ISD::TRAMPOLINE, MVT::Other, Custom);
387
388   setOperationAction(ISD::TRAP, MVT::Other, Legal);
389
390   // VASTART needs to be custom lowered to use the VarArgsFrameIndex
391   setOperationAction(ISD::VASTART           , MVT::Other, Custom);
392   setOperationAction(ISD::VAEND             , MVT::Other, Expand);
393   if (Subtarget->is64Bit()) {
394     setOperationAction(ISD::VAARG           , MVT::Other, Custom);
395     setOperationAction(ISD::VACOPY          , MVT::Other, Custom);
396   } else {
397     setOperationAction(ISD::VAARG           , MVT::Other, Expand);
398     setOperationAction(ISD::VACOPY          , MVT::Other, Expand);
399   }
400
401   setOperationAction(ISD::STACKSAVE,          MVT::Other, Expand);
402   setOperationAction(ISD::STACKRESTORE,       MVT::Other, Expand);
403   if (Subtarget->is64Bit())
404     setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i64, Expand);
405   if (Subtarget->isTargetCygMing())
406     setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Custom);
407   else
408     setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Expand);
409
410   if (!UseSoftFloat && X86ScalarSSEf64) {
411     // f32 and f64 use SSE.
412     // Set up the FP register classes.
413     addRegisterClass(MVT::f32, X86::FR32RegisterClass);
414     addRegisterClass(MVT::f64, X86::FR64RegisterClass);
415
416     // Use ANDPD to simulate FABS.
417     setOperationAction(ISD::FABS , MVT::f64, Custom);
418     setOperationAction(ISD::FABS , MVT::f32, Custom);
419
420     // Use XORP to simulate FNEG.
421     setOperationAction(ISD::FNEG , MVT::f64, Custom);
422     setOperationAction(ISD::FNEG , MVT::f32, Custom);
423
424     // Use ANDPD and ORPD to simulate FCOPYSIGN.
425     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
426     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
427
428     // We don't support sin/cos/fmod
429     setOperationAction(ISD::FSIN , MVT::f64, Expand);
430     setOperationAction(ISD::FCOS , MVT::f64, Expand);
431     setOperationAction(ISD::FSIN , MVT::f32, Expand);
432     setOperationAction(ISD::FCOS , MVT::f32, Expand);
433
434     // Expand FP immediates into loads from the stack, except for the special
435     // cases we handle.
436     addLegalFPImmediate(APFloat(+0.0)); // xorpd
437     addLegalFPImmediate(APFloat(+0.0f)); // xorps
438   } else if (!UseSoftFloat && X86ScalarSSEf32) {
439     // Use SSE for f32, x87 for f64.
440     // Set up the FP register classes.
441     addRegisterClass(MVT::f32, X86::FR32RegisterClass);
442     addRegisterClass(MVT::f64, X86::RFP64RegisterClass);
443
444     // Use ANDPS to simulate FABS.
445     setOperationAction(ISD::FABS , MVT::f32, Custom);
446
447     // Use XORP to simulate FNEG.
448     setOperationAction(ISD::FNEG , MVT::f32, Custom);
449
450     setOperationAction(ISD::UNDEF,     MVT::f64, Expand);
451
452     // Use ANDPS and ORPS to simulate FCOPYSIGN.
453     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
454     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
455
456     // We don't support sin/cos/fmod
457     setOperationAction(ISD::FSIN , MVT::f32, Expand);
458     setOperationAction(ISD::FCOS , MVT::f32, Expand);
459
460     // Special cases we handle for FP constants.
461     addLegalFPImmediate(APFloat(+0.0f)); // xorps
462     addLegalFPImmediate(APFloat(+0.0)); // FLD0
463     addLegalFPImmediate(APFloat(+1.0)); // FLD1
464     addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
465     addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
466
467     if (!UnsafeFPMath) {
468       setOperationAction(ISD::FSIN           , MVT::f64  , Expand);
469       setOperationAction(ISD::FCOS           , MVT::f64  , Expand);
470     }
471   } else if (!UseSoftFloat) {
472     // f32 and f64 in x87.
473     // Set up the FP register classes.
474     addRegisterClass(MVT::f64, X86::RFP64RegisterClass);
475     addRegisterClass(MVT::f32, X86::RFP32RegisterClass);
476
477     setOperationAction(ISD::UNDEF,     MVT::f64, Expand);
478     setOperationAction(ISD::UNDEF,     MVT::f32, Expand);
479     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
480     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand);
481
482     if (!UnsafeFPMath) {
483       setOperationAction(ISD::FSIN           , MVT::f64  , Expand);
484       setOperationAction(ISD::FCOS           , MVT::f64  , Expand);
485     }
486     addLegalFPImmediate(APFloat(+0.0)); // FLD0
487     addLegalFPImmediate(APFloat(+1.0)); // FLD1
488     addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
489     addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
490     addLegalFPImmediate(APFloat(+0.0f)); // FLD0
491     addLegalFPImmediate(APFloat(+1.0f)); // FLD1
492     addLegalFPImmediate(APFloat(-0.0f)); // FLD0/FCHS
493     addLegalFPImmediate(APFloat(-1.0f)); // FLD1/FCHS
494   }
495
496   // Long double always uses X87.
497   if (!UseSoftFloat) {
498     addRegisterClass(MVT::f80, X86::RFP80RegisterClass);
499     setOperationAction(ISD::UNDEF,     MVT::f80, Expand);
500     setOperationAction(ISD::FCOPYSIGN, MVT::f80, Expand);
501     {
502       bool ignored;
503       APFloat TmpFlt(+0.0);
504       TmpFlt.convert(APFloat::x87DoubleExtended, APFloat::rmNearestTiesToEven,
505                      &ignored);
506       addLegalFPImmediate(TmpFlt);  // FLD0
507       TmpFlt.changeSign();
508       addLegalFPImmediate(TmpFlt);  // FLD0/FCHS
509       APFloat TmpFlt2(+1.0);
510       TmpFlt2.convert(APFloat::x87DoubleExtended, APFloat::rmNearestTiesToEven,
511                       &ignored);
512       addLegalFPImmediate(TmpFlt2);  // FLD1
513       TmpFlt2.changeSign();
514       addLegalFPImmediate(TmpFlt2);  // FLD1/FCHS
515     }
516
517     if (!UnsafeFPMath) {
518       setOperationAction(ISD::FSIN           , MVT::f80  , Expand);
519       setOperationAction(ISD::FCOS           , MVT::f80  , Expand);
520     }
521   }
522
523   // Always use a library call for pow.
524   setOperationAction(ISD::FPOW             , MVT::f32  , Expand);
525   setOperationAction(ISD::FPOW             , MVT::f64  , Expand);
526   setOperationAction(ISD::FPOW             , MVT::f80  , Expand);
527
528   setOperationAction(ISD::FLOG, MVT::f80, Expand);
529   setOperationAction(ISD::FLOG2, MVT::f80, Expand);
530   setOperationAction(ISD::FLOG10, MVT::f80, Expand);
531   setOperationAction(ISD::FEXP, MVT::f80, Expand);
532   setOperationAction(ISD::FEXP2, MVT::f80, Expand);
533
534   // First set operation action for all vector types to either promote
535   // (for widening) or expand (for scalarization). Then we will selectively
536   // turn on ones that can be effectively codegen'd.
537   for (unsigned VT = (unsigned)MVT::FIRST_VECTOR_VALUETYPE;
538        VT <= (unsigned)MVT::LAST_VECTOR_VALUETYPE; ++VT) {
539     setOperationAction(ISD::ADD , (MVT::SimpleValueType)VT, Expand);
540     setOperationAction(ISD::SUB , (MVT::SimpleValueType)VT, Expand);
541     setOperationAction(ISD::FADD, (MVT::SimpleValueType)VT, Expand);
542     setOperationAction(ISD::FNEG, (MVT::SimpleValueType)VT, Expand);
543     setOperationAction(ISD::FSUB, (MVT::SimpleValueType)VT, Expand);
544     setOperationAction(ISD::MUL , (MVT::SimpleValueType)VT, Expand);
545     setOperationAction(ISD::FMUL, (MVT::SimpleValueType)VT, Expand);
546     setOperationAction(ISD::SDIV, (MVT::SimpleValueType)VT, Expand);
547     setOperationAction(ISD::UDIV, (MVT::SimpleValueType)VT, Expand);
548     setOperationAction(ISD::FDIV, (MVT::SimpleValueType)VT, Expand);
549     setOperationAction(ISD::SREM, (MVT::SimpleValueType)VT, Expand);
550     setOperationAction(ISD::UREM, (MVT::SimpleValueType)VT, Expand);
551     setOperationAction(ISD::LOAD, (MVT::SimpleValueType)VT, Expand);
552     setOperationAction(ISD::VECTOR_SHUFFLE, (MVT::SimpleValueType)VT, Expand);
553     setOperationAction(ISD::EXTRACT_VECTOR_ELT,(MVT::SimpleValueType)VT,Expand);
554     setOperationAction(ISD::EXTRACT_SUBVECTOR,(MVT::SimpleValueType)VT,Expand);
555     setOperationAction(ISD::INSERT_VECTOR_ELT,(MVT::SimpleValueType)VT, Expand);
556     setOperationAction(ISD::FABS, (MVT::SimpleValueType)VT, Expand);
557     setOperationAction(ISD::FSIN, (MVT::SimpleValueType)VT, Expand);
558     setOperationAction(ISD::FCOS, (MVT::SimpleValueType)VT, Expand);
559     setOperationAction(ISD::FREM, (MVT::SimpleValueType)VT, Expand);
560     setOperationAction(ISD::FPOWI, (MVT::SimpleValueType)VT, Expand);
561     setOperationAction(ISD::FSQRT, (MVT::SimpleValueType)VT, Expand);
562     setOperationAction(ISD::FCOPYSIGN, (MVT::SimpleValueType)VT, Expand);
563     setOperationAction(ISD::SMUL_LOHI, (MVT::SimpleValueType)VT, Expand);
564     setOperationAction(ISD::UMUL_LOHI, (MVT::SimpleValueType)VT, Expand);
565     setOperationAction(ISD::SDIVREM, (MVT::SimpleValueType)VT, Expand);
566     setOperationAction(ISD::UDIVREM, (MVT::SimpleValueType)VT, Expand);
567     setOperationAction(ISD::FPOW, (MVT::SimpleValueType)VT, Expand);
568     setOperationAction(ISD::CTPOP, (MVT::SimpleValueType)VT, Expand);
569     setOperationAction(ISD::CTTZ, (MVT::SimpleValueType)VT, Expand);
570     setOperationAction(ISD::CTLZ, (MVT::SimpleValueType)VT, Expand);
571     setOperationAction(ISD::SHL, (MVT::SimpleValueType)VT, Expand);
572     setOperationAction(ISD::SRA, (MVT::SimpleValueType)VT, Expand);
573     setOperationAction(ISD::SRL, (MVT::SimpleValueType)VT, Expand);
574     setOperationAction(ISD::ROTL, (MVT::SimpleValueType)VT, Expand);
575     setOperationAction(ISD::ROTR, (MVT::SimpleValueType)VT, Expand);
576     setOperationAction(ISD::BSWAP, (MVT::SimpleValueType)VT, Expand);
577     setOperationAction(ISD::VSETCC, (MVT::SimpleValueType)VT, Expand);
578     setOperationAction(ISD::FLOG, (MVT::SimpleValueType)VT, Expand);
579     setOperationAction(ISD::FLOG2, (MVT::SimpleValueType)VT, Expand);
580     setOperationAction(ISD::FLOG10, (MVT::SimpleValueType)VT, Expand);
581     setOperationAction(ISD::FEXP, (MVT::SimpleValueType)VT, Expand);
582     setOperationAction(ISD::FEXP2, (MVT::SimpleValueType)VT, Expand);
583     setOperationAction(ISD::FP_TO_UINT, (MVT::SimpleValueType)VT, Expand);
584     setOperationAction(ISD::FP_TO_SINT, (MVT::SimpleValueType)VT, Expand);
585     setOperationAction(ISD::UINT_TO_FP, (MVT::SimpleValueType)VT, Expand);
586     setOperationAction(ISD::SINT_TO_FP, (MVT::SimpleValueType)VT, Expand);
587     setOperationAction(ISD::SIGN_EXTEND_INREG, (MVT::SimpleValueType)VT,Expand);
588     setOperationAction(ISD::TRUNCATE,  (MVT::SimpleValueType)VT, Expand);
589     setOperationAction(ISD::SIGN_EXTEND,  (MVT::SimpleValueType)VT, Expand);
590     setOperationAction(ISD::ZERO_EXTEND,  (MVT::SimpleValueType)VT, Expand);
591     setOperationAction(ISD::ANY_EXTEND,  (MVT::SimpleValueType)VT, Expand);
592     for (unsigned InnerVT = (unsigned)MVT::FIRST_VECTOR_VALUETYPE;
593          InnerVT <= (unsigned)MVT::LAST_VECTOR_VALUETYPE; ++InnerVT)
594       setTruncStoreAction((MVT::SimpleValueType)VT,
595                           (MVT::SimpleValueType)InnerVT, Expand);
596     setLoadExtAction(ISD::SEXTLOAD, (MVT::SimpleValueType)VT, Expand);
597     setLoadExtAction(ISD::ZEXTLOAD, (MVT::SimpleValueType)VT, Expand);
598     setLoadExtAction(ISD::EXTLOAD, (MVT::SimpleValueType)VT, Expand);
599   }
600
601   // FIXME: In order to prevent SSE instructions being expanded to MMX ones
602   // with -msoft-float, disable use of MMX as well.
603   if (!UseSoftFloat && !DisableMMX && Subtarget->hasMMX()) {
604     addRegisterClass(MVT::v8i8,  X86::VR64RegisterClass, false);
605     addRegisterClass(MVT::v4i16, X86::VR64RegisterClass, false);
606     addRegisterClass(MVT::v2i32, X86::VR64RegisterClass, false);
607     addRegisterClass(MVT::v2f32, X86::VR64RegisterClass, false);
608     addRegisterClass(MVT::v1i64, X86::VR64RegisterClass, false);
609
610     setOperationAction(ISD::ADD,                MVT::v8i8,  Legal);
611     setOperationAction(ISD::ADD,                MVT::v4i16, Legal);
612     setOperationAction(ISD::ADD,                MVT::v2i32, Legal);
613     setOperationAction(ISD::ADD,                MVT::v1i64, Legal);
614
615     setOperationAction(ISD::SUB,                MVT::v8i8,  Legal);
616     setOperationAction(ISD::SUB,                MVT::v4i16, Legal);
617     setOperationAction(ISD::SUB,                MVT::v2i32, Legal);
618     setOperationAction(ISD::SUB,                MVT::v1i64, Legal);
619
620     setOperationAction(ISD::MULHS,              MVT::v4i16, Legal);
621     setOperationAction(ISD::MUL,                MVT::v4i16, Legal);
622
623     setOperationAction(ISD::AND,                MVT::v8i8,  Promote);
624     AddPromotedToType (ISD::AND,                MVT::v8i8,  MVT::v1i64);
625     setOperationAction(ISD::AND,                MVT::v4i16, Promote);
626     AddPromotedToType (ISD::AND,                MVT::v4i16, MVT::v1i64);
627     setOperationAction(ISD::AND,                MVT::v2i32, Promote);
628     AddPromotedToType (ISD::AND,                MVT::v2i32, MVT::v1i64);
629     setOperationAction(ISD::AND,                MVT::v1i64, Legal);
630
631     setOperationAction(ISD::OR,                 MVT::v8i8,  Promote);
632     AddPromotedToType (ISD::OR,                 MVT::v8i8,  MVT::v1i64);
633     setOperationAction(ISD::OR,                 MVT::v4i16, Promote);
634     AddPromotedToType (ISD::OR,                 MVT::v4i16, MVT::v1i64);
635     setOperationAction(ISD::OR,                 MVT::v2i32, Promote);
636     AddPromotedToType (ISD::OR,                 MVT::v2i32, MVT::v1i64);
637     setOperationAction(ISD::OR,                 MVT::v1i64, Legal);
638
639     setOperationAction(ISD::XOR,                MVT::v8i8,  Promote);
640     AddPromotedToType (ISD::XOR,                MVT::v8i8,  MVT::v1i64);
641     setOperationAction(ISD::XOR,                MVT::v4i16, Promote);
642     AddPromotedToType (ISD::XOR,                MVT::v4i16, MVT::v1i64);
643     setOperationAction(ISD::XOR,                MVT::v2i32, Promote);
644     AddPromotedToType (ISD::XOR,                MVT::v2i32, MVT::v1i64);
645     setOperationAction(ISD::XOR,                MVT::v1i64, Legal);
646
647     setOperationAction(ISD::LOAD,               MVT::v8i8,  Promote);
648     AddPromotedToType (ISD::LOAD,               MVT::v8i8,  MVT::v1i64);
649     setOperationAction(ISD::LOAD,               MVT::v4i16, Promote);
650     AddPromotedToType (ISD::LOAD,               MVT::v4i16, MVT::v1i64);
651     setOperationAction(ISD::LOAD,               MVT::v2i32, Promote);
652     AddPromotedToType (ISD::LOAD,               MVT::v2i32, MVT::v1i64);
653     setOperationAction(ISD::LOAD,               MVT::v2f32, Promote);
654     AddPromotedToType (ISD::LOAD,               MVT::v2f32, MVT::v1i64);
655     setOperationAction(ISD::LOAD,               MVT::v1i64, Legal);
656
657     setOperationAction(ISD::BUILD_VECTOR,       MVT::v8i8,  Custom);
658     setOperationAction(ISD::BUILD_VECTOR,       MVT::v4i16, Custom);
659     setOperationAction(ISD::BUILD_VECTOR,       MVT::v2i32, Custom);
660     setOperationAction(ISD::BUILD_VECTOR,       MVT::v2f32, Custom);
661     setOperationAction(ISD::BUILD_VECTOR,       MVT::v1i64, Custom);
662
663     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v8i8,  Custom);
664     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v4i16, Custom);
665     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v2i32, Custom);
666     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v1i64, Custom);
667
668     setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v2f32, Custom);
669     setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v8i8,  Custom);
670     setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v4i16, Custom);
671     setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v1i64, Custom);
672
673     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4i16, Custom);
674
675     setOperationAction(ISD::SELECT,             MVT::v8i8, Promote);
676     setOperationAction(ISD::SELECT,             MVT::v4i16, Promote);
677     setOperationAction(ISD::SELECT,             MVT::v2i32, Promote);
678     setOperationAction(ISD::SELECT,             MVT::v1i64, Custom);
679     setOperationAction(ISD::VSETCC,             MVT::v8i8, Custom);
680     setOperationAction(ISD::VSETCC,             MVT::v4i16, Custom);
681     setOperationAction(ISD::VSETCC,             MVT::v2i32, Custom);
682   }
683
684   if (!UseSoftFloat && Subtarget->hasSSE1()) {
685     addRegisterClass(MVT::v4f32, X86::VR128RegisterClass);
686
687     setOperationAction(ISD::FADD,               MVT::v4f32, Legal);
688     setOperationAction(ISD::FSUB,               MVT::v4f32, Legal);
689     setOperationAction(ISD::FMUL,               MVT::v4f32, Legal);
690     setOperationAction(ISD::FDIV,               MVT::v4f32, Legal);
691     setOperationAction(ISD::FSQRT,              MVT::v4f32, Legal);
692     setOperationAction(ISD::FNEG,               MVT::v4f32, Custom);
693     setOperationAction(ISD::LOAD,               MVT::v4f32, Legal);
694     setOperationAction(ISD::BUILD_VECTOR,       MVT::v4f32, Custom);
695     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v4f32, Custom);
696     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
697     setOperationAction(ISD::SELECT,             MVT::v4f32, Custom);
698     setOperationAction(ISD::VSETCC,             MVT::v4f32, Custom);
699   }
700
701   if (!UseSoftFloat && Subtarget->hasSSE2()) {
702     addRegisterClass(MVT::v2f64, X86::VR128RegisterClass);
703
704     // FIXME: Unfortunately -soft-float and -no-implicit-float means XMM
705     // registers cannot be used even for integer operations.
706     addRegisterClass(MVT::v16i8, X86::VR128RegisterClass);
707     addRegisterClass(MVT::v8i16, X86::VR128RegisterClass);
708     addRegisterClass(MVT::v4i32, X86::VR128RegisterClass);
709     addRegisterClass(MVT::v2i64, X86::VR128RegisterClass);
710
711     setOperationAction(ISD::ADD,                MVT::v16i8, Legal);
712     setOperationAction(ISD::ADD,                MVT::v8i16, Legal);
713     setOperationAction(ISD::ADD,                MVT::v4i32, Legal);
714     setOperationAction(ISD::ADD,                MVT::v2i64, Legal);
715     setOperationAction(ISD::MUL,                MVT::v2i64, Custom);
716     setOperationAction(ISD::SUB,                MVT::v16i8, Legal);
717     setOperationAction(ISD::SUB,                MVT::v8i16, Legal);
718     setOperationAction(ISD::SUB,                MVT::v4i32, Legal);
719     setOperationAction(ISD::SUB,                MVT::v2i64, Legal);
720     setOperationAction(ISD::MUL,                MVT::v8i16, Legal);
721     setOperationAction(ISD::FADD,               MVT::v2f64, Legal);
722     setOperationAction(ISD::FSUB,               MVT::v2f64, Legal);
723     setOperationAction(ISD::FMUL,               MVT::v2f64, Legal);
724     setOperationAction(ISD::FDIV,               MVT::v2f64, Legal);
725     setOperationAction(ISD::FSQRT,              MVT::v2f64, Legal);
726     setOperationAction(ISD::FNEG,               MVT::v2f64, Custom);
727
728     setOperationAction(ISD::VSETCC,             MVT::v2f64, Custom);
729     setOperationAction(ISD::VSETCC,             MVT::v16i8, Custom);
730     setOperationAction(ISD::VSETCC,             MVT::v8i16, Custom);
731     setOperationAction(ISD::VSETCC,             MVT::v4i32, Custom);
732
733     setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v16i8, Custom);
734     setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v8i16, Custom);
735     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v8i16, Custom);
736     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4i32, Custom);
737     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4f32, Custom);
738
739     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v2f64, Custom);
740     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v2i64, Custom);
741     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v16i8, Custom);
742     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v8i16, Custom);
743     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v4i32, Custom);
744
745     // Custom lower build_vector, vector_shuffle, and extract_vector_elt.
746     for (unsigned i = (unsigned)MVT::v16i8; i != (unsigned)MVT::v2i64; ++i) {
747       EVT VT = (MVT::SimpleValueType)i;
748       // Do not attempt to custom lower non-power-of-2 vectors
749       if (!isPowerOf2_32(VT.getVectorNumElements()))
750         continue;
751       // Do not attempt to custom lower non-128-bit vectors
752       if (!VT.is128BitVector())
753         continue;
754       setOperationAction(ISD::BUILD_VECTOR,
755                          VT.getSimpleVT().SimpleTy, Custom);
756       setOperationAction(ISD::VECTOR_SHUFFLE,
757                          VT.getSimpleVT().SimpleTy, Custom);
758       setOperationAction(ISD::EXTRACT_VECTOR_ELT,
759                          VT.getSimpleVT().SimpleTy, Custom);
760     }
761
762     setOperationAction(ISD::BUILD_VECTOR,       MVT::v2f64, Custom);
763     setOperationAction(ISD::BUILD_VECTOR,       MVT::v2i64, Custom);
764     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v2f64, Custom);
765     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v2i64, Custom);
766     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2f64, Custom);
767     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Custom);
768
769     if (Subtarget->is64Bit()) {
770       setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2i64, Custom);
771       setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
772     }
773
774     // Promote v16i8, v8i16, v4i32 load, select, and, or, xor to v2i64.
775     for (unsigned i = (unsigned)MVT::v16i8; i != (unsigned)MVT::v2i64; i++) {
776       MVT::SimpleValueType SVT = (MVT::SimpleValueType)i;
777       EVT VT = SVT;
778
779       // Do not attempt to promote non-128-bit vectors
780       if (!VT.is128BitVector()) {
781         continue;
782       }
783       
784       setOperationAction(ISD::AND,    SVT, Promote);
785       AddPromotedToType (ISD::AND,    SVT, MVT::v2i64);
786       setOperationAction(ISD::OR,     SVT, Promote);
787       AddPromotedToType (ISD::OR,     SVT, MVT::v2i64);
788       setOperationAction(ISD::XOR,    SVT, Promote);
789       AddPromotedToType (ISD::XOR,    SVT, MVT::v2i64);
790       setOperationAction(ISD::LOAD,   SVT, Promote);
791       AddPromotedToType (ISD::LOAD,   SVT, MVT::v2i64);
792       setOperationAction(ISD::SELECT, SVT, Promote);
793       AddPromotedToType (ISD::SELECT, SVT, MVT::v2i64);
794     }
795
796     setTruncStoreAction(MVT::f64, MVT::f32, Expand);
797
798     // Custom lower v2i64 and v2f64 selects.
799     setOperationAction(ISD::LOAD,               MVT::v2f64, Legal);
800     setOperationAction(ISD::LOAD,               MVT::v2i64, Legal);
801     setOperationAction(ISD::SELECT,             MVT::v2f64, Custom);
802     setOperationAction(ISD::SELECT,             MVT::v2i64, Custom);
803
804     setOperationAction(ISD::FP_TO_SINT,         MVT::v4i32, Legal);
805     setOperationAction(ISD::SINT_TO_FP,         MVT::v4i32, Legal);
806     if (!DisableMMX && Subtarget->hasMMX()) {
807       setOperationAction(ISD::FP_TO_SINT,         MVT::v2i32, Custom);
808       setOperationAction(ISD::SINT_TO_FP,         MVT::v2i32, Custom);
809     }
810   }
811
812   if (Subtarget->hasSSE41()) {
813     // FIXME: Do we need to handle scalar-to-vector here?
814     setOperationAction(ISD::MUL,                MVT::v4i32, Legal);
815
816     // i8 and i16 vectors are custom , because the source register and source
817     // source memory operand types are not the same width.  f32 vectors are
818     // custom since the immediate controlling the insert encodes additional
819     // information.
820     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v16i8, Custom);
821     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v8i16, Custom);
822     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4i32, Custom);
823     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4f32, Custom);
824
825     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i8, Custom);
826     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i16, Custom);
827     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i32, Custom);
828     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
829
830     if (Subtarget->is64Bit()) {
831       setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2i64, Legal);
832       setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Legal);
833     }
834   }
835
836   if (Subtarget->hasSSE42()) {
837     setOperationAction(ISD::VSETCC,             MVT::v2i64, Custom);
838   }
839
840   if (!UseSoftFloat && Subtarget->hasAVX()) {
841     addRegisterClass(MVT::v8f32, X86::VR256RegisterClass);
842     addRegisterClass(MVT::v4f64, X86::VR256RegisterClass);
843     addRegisterClass(MVT::v8i32, X86::VR256RegisterClass);
844     addRegisterClass(MVT::v4i64, X86::VR256RegisterClass);
845
846     setOperationAction(ISD::LOAD,               MVT::v8f32, Legal);
847     setOperationAction(ISD::LOAD,               MVT::v8i32, Legal);
848     setOperationAction(ISD::LOAD,               MVT::v4f64, Legal);
849     setOperationAction(ISD::LOAD,               MVT::v4i64, Legal);
850     setOperationAction(ISD::FADD,               MVT::v8f32, Legal);
851     setOperationAction(ISD::FSUB,               MVT::v8f32, Legal);
852     setOperationAction(ISD::FMUL,               MVT::v8f32, Legal);
853     setOperationAction(ISD::FDIV,               MVT::v8f32, Legal);
854     setOperationAction(ISD::FSQRT,              MVT::v8f32, Legal);
855     setOperationAction(ISD::FNEG,               MVT::v8f32, Custom);
856     //setOperationAction(ISD::BUILD_VECTOR,       MVT::v8f32, Custom);
857     //setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v8f32, Custom);
858     //setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8f32, Custom);
859     //setOperationAction(ISD::SELECT,             MVT::v8f32, Custom);
860     //setOperationAction(ISD::VSETCC,             MVT::v8f32, Custom);
861
862     // Operations to consider commented out -v16i16 v32i8
863     //setOperationAction(ISD::ADD,                MVT::v16i16, Legal);
864     setOperationAction(ISD::ADD,                MVT::v8i32, Custom);
865     setOperationAction(ISD::ADD,                MVT::v4i64, Custom);
866     //setOperationAction(ISD::SUB,                MVT::v32i8, Legal);
867     //setOperationAction(ISD::SUB,                MVT::v16i16, Legal);
868     setOperationAction(ISD::SUB,                MVT::v8i32, Custom);
869     setOperationAction(ISD::SUB,                MVT::v4i64, Custom);
870     //setOperationAction(ISD::MUL,                MVT::v16i16, Legal);
871     setOperationAction(ISD::FADD,               MVT::v4f64, Legal);
872     setOperationAction(ISD::FSUB,               MVT::v4f64, Legal);
873     setOperationAction(ISD::FMUL,               MVT::v4f64, Legal);
874     setOperationAction(ISD::FDIV,               MVT::v4f64, Legal);
875     setOperationAction(ISD::FSQRT,              MVT::v4f64, Legal);
876     setOperationAction(ISD::FNEG,               MVT::v4f64, Custom);
877
878     setOperationAction(ISD::VSETCC,             MVT::v4f64, Custom);
879     // setOperationAction(ISD::VSETCC,             MVT::v32i8, Custom);
880     // setOperationAction(ISD::VSETCC,             MVT::v16i16, Custom);
881     setOperationAction(ISD::VSETCC,             MVT::v8i32, Custom);
882
883     // setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v32i8, Custom);
884     // setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v16i16, Custom);
885     // setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v16i16, Custom);
886     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v8i32, Custom);
887     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v8f32, Custom);
888
889     setOperationAction(ISD::BUILD_VECTOR,       MVT::v4f64, Custom);
890     setOperationAction(ISD::BUILD_VECTOR,       MVT::v4i64, Custom);
891     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v4f64, Custom);
892     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v4i64, Custom);
893     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4f64, Custom);
894     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f64, Custom);
895
896 #if 0
897     // Not sure we want to do this since there are no 256-bit integer
898     // operations in AVX
899
900     // Custom lower build_vector, vector_shuffle, and extract_vector_elt.
901     // This includes 256-bit vectors
902     for (unsigned i = (unsigned)MVT::v16i8; i != (unsigned)MVT::v4i64; ++i) {
903       EVT VT = (MVT::SimpleValueType)i;
904
905       // Do not attempt to custom lower non-power-of-2 vectors
906       if (!isPowerOf2_32(VT.getVectorNumElements()))
907         continue;
908
909       setOperationAction(ISD::BUILD_VECTOR,       VT, Custom);
910       setOperationAction(ISD::VECTOR_SHUFFLE,     VT, Custom);
911       setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
912     }
913
914     if (Subtarget->is64Bit()) {
915       setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4i64, Custom);
916       setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i64, Custom);
917     }
918 #endif
919
920 #if 0
921     // Not sure we want to do this since there are no 256-bit integer
922     // operations in AVX
923
924     // Promote v32i8, v16i16, v8i32 load, select, and, or, xor to v4i64.
925     // Including 256-bit vectors
926     for (unsigned i = (unsigned)MVT::v16i8; i != (unsigned)MVT::v4i64; i++) {
927       EVT VT = (MVT::SimpleValueType)i;
928
929       if (!VT.is256BitVector()) {
930         continue;
931       }
932       setOperationAction(ISD::AND,    VT, Promote);
933       AddPromotedToType (ISD::AND,    VT, MVT::v4i64);
934       setOperationAction(ISD::OR,     VT, Promote);
935       AddPromotedToType (ISD::OR,     VT, MVT::v4i64);
936       setOperationAction(ISD::XOR,    VT, Promote);
937       AddPromotedToType (ISD::XOR,    VT, MVT::v4i64);
938       setOperationAction(ISD::LOAD,   VT, Promote);
939       AddPromotedToType (ISD::LOAD,   VT, MVT::v4i64);
940       setOperationAction(ISD::SELECT, VT, Promote);
941       AddPromotedToType (ISD::SELECT, VT, MVT::v4i64);
942     }
943
944     setTruncStoreAction(MVT::f64, MVT::f32, Expand);
945 #endif
946   }
947
948   // We want to custom lower some of our intrinsics.
949   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
950
951   // Add/Sub/Mul with overflow operations are custom lowered.
952   setOperationAction(ISD::SADDO, MVT::i32, Custom);
953   setOperationAction(ISD::SADDO, MVT::i64, Custom);
954   setOperationAction(ISD::UADDO, MVT::i32, Custom);
955   setOperationAction(ISD::UADDO, MVT::i64, Custom);
956   setOperationAction(ISD::SSUBO, MVT::i32, Custom);
957   setOperationAction(ISD::SSUBO, MVT::i64, Custom);
958   setOperationAction(ISD::USUBO, MVT::i32, Custom);
959   setOperationAction(ISD::USUBO, MVT::i64, Custom);
960   setOperationAction(ISD::SMULO, MVT::i32, Custom);
961   setOperationAction(ISD::SMULO, MVT::i64, Custom);
962
963   if (!Subtarget->is64Bit()) {
964     // These libcalls are not available in 32-bit.
965     setLibcallName(RTLIB::SHL_I128, 0);
966     setLibcallName(RTLIB::SRL_I128, 0);
967     setLibcallName(RTLIB::SRA_I128, 0);
968   }
969
970   // We have target-specific dag combine patterns for the following nodes:
971   setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
972   setTargetDAGCombine(ISD::EXTRACT_VECTOR_ELT);
973   setTargetDAGCombine(ISD::BUILD_VECTOR);
974   setTargetDAGCombine(ISD::SELECT);
975   setTargetDAGCombine(ISD::SHL);
976   setTargetDAGCombine(ISD::SRA);
977   setTargetDAGCombine(ISD::SRL);
978   setTargetDAGCombine(ISD::OR);
979   setTargetDAGCombine(ISD::STORE);
980   setTargetDAGCombine(ISD::MEMBARRIER);
981   setTargetDAGCombine(ISD::ZERO_EXTEND);
982   if (Subtarget->is64Bit())
983     setTargetDAGCombine(ISD::MUL);
984
985   computeRegisterProperties();
986
987   // FIXME: These should be based on subtarget info. Plus, the values should
988   // be smaller when we are in optimizing for size mode.
989   maxStoresPerMemset = 16; // For @llvm.memset -> sequence of stores
990   maxStoresPerMemcpy = 8; // For @llvm.memcpy -> sequence of stores
991   maxStoresPerMemmove = 3; // For @llvm.memmove -> sequence of stores
992   setPrefLoopAlignment(16);
993   benefitFromCodePlacementOpt = true;
994 }
995
996
997 MVT::SimpleValueType X86TargetLowering::getSetCCResultType(EVT VT) const {
998   return MVT::i8;
999 }
1000
1001
1002 /// getMaxByValAlign - Helper for getByValTypeAlignment to determine
1003 /// the desired ByVal argument alignment.
1004 static void getMaxByValAlign(const Type *Ty, unsigned &MaxAlign) {
1005   if (MaxAlign == 16)
1006     return;
1007   if (const VectorType *VTy = dyn_cast<VectorType>(Ty)) {
1008     if (VTy->getBitWidth() == 128)
1009       MaxAlign = 16;
1010   } else if (const ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
1011     unsigned EltAlign = 0;
1012     getMaxByValAlign(ATy->getElementType(), EltAlign);
1013     if (EltAlign > MaxAlign)
1014       MaxAlign = EltAlign;
1015   } else if (const StructType *STy = dyn_cast<StructType>(Ty)) {
1016     for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
1017       unsigned EltAlign = 0;
1018       getMaxByValAlign(STy->getElementType(i), EltAlign);
1019       if (EltAlign > MaxAlign)
1020         MaxAlign = EltAlign;
1021       if (MaxAlign == 16)
1022         break;
1023     }
1024   }
1025   return;
1026 }
1027
1028 /// getByValTypeAlignment - Return the desired alignment for ByVal aggregate
1029 /// function arguments in the caller parameter area. For X86, aggregates
1030 /// that contain SSE vectors are placed at 16-byte boundaries while the rest
1031 /// are at 4-byte boundaries.
1032 unsigned X86TargetLowering::getByValTypeAlignment(const Type *Ty) const {
1033   if (Subtarget->is64Bit()) {
1034     // Max of 8 and alignment of type.
1035     unsigned TyAlign = TD->getABITypeAlignment(Ty);
1036     if (TyAlign > 8)
1037       return TyAlign;
1038     return 8;
1039   }
1040
1041   unsigned Align = 4;
1042   if (Subtarget->hasSSE1())
1043     getMaxByValAlign(Ty, Align);
1044   return Align;
1045 }
1046
1047 /// getOptimalMemOpType - Returns the target specific optimal type for load
1048 /// and store operations as a result of memset, memcpy, and memmove
1049 /// lowering. If DstAlign is zero that means it's safe to destination
1050 /// alignment can satisfy any constraint. Similarly if SrcAlign is zero it
1051 /// means there isn't a need to check it against alignment requirement,
1052 /// probably because the source does not need to be loaded. If
1053 /// 'NonScalarIntSafe' is true, that means it's safe to return a
1054 /// non-scalar-integer type, e.g. empty string source, constant, or loaded
1055 /// from memory. 'MemcpyStrSrc' indicates whether the memcpy source is
1056 /// constant so it does not need to be loaded.
1057 /// It returns EVT::Other if the type should be determined using generic
1058 /// target-independent logic.
1059 EVT
1060 X86TargetLowering::getOptimalMemOpType(uint64_t Size,
1061                                        unsigned DstAlign, unsigned SrcAlign,
1062                                        bool NonScalarIntSafe,
1063                                        bool MemcpyStrSrc,
1064                                        MachineFunction &MF) const {
1065   // FIXME: This turns off use of xmm stores for memset/memcpy on targets like
1066   // linux.  This is because the stack realignment code can't handle certain
1067   // cases like PR2962.  This should be removed when PR2962 is fixed.
1068   const Function *F = MF.getFunction();
1069   if (NonScalarIntSafe &&
1070       !F->hasFnAttr(Attribute::NoImplicitFloat)) {
1071     if (Size >= 16 &&
1072         (Subtarget->isUnalignedMemAccessFast() ||
1073          ((DstAlign == 0 || DstAlign >= 16) &&
1074           (SrcAlign == 0 || SrcAlign >= 16))) &&
1075         Subtarget->getStackAlignment() >= 16) {
1076       if (Subtarget->hasSSE2())
1077         return MVT::v4i32;
1078       if (Subtarget->hasSSE1())
1079         return MVT::v4f32;
1080     } else if (!MemcpyStrSrc && Size >= 8 &&
1081                !Subtarget->is64Bit() &&
1082                Subtarget->getStackAlignment() >= 8 &&
1083                Subtarget->hasSSE2()) {
1084       // Do not use f64 to lower memcpy if source is string constant. It's
1085       // better to use i32 to avoid the loads.
1086       return MVT::f64;
1087     }
1088   }
1089   if (Subtarget->is64Bit() && Size >= 8)
1090     return MVT::i64;
1091   return MVT::i32;
1092 }
1093
1094 /// getJumpTableEncoding - Return the entry encoding for a jump table in the
1095 /// current function.  The returned value is a member of the
1096 /// MachineJumpTableInfo::JTEntryKind enum.
1097 unsigned X86TargetLowering::getJumpTableEncoding() const {
1098   // In GOT pic mode, each entry in the jump table is emitted as a @GOTOFF
1099   // symbol.
1100   if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1101       Subtarget->isPICStyleGOT())
1102     return MachineJumpTableInfo::EK_Custom32;
1103   
1104   // Otherwise, use the normal jump table encoding heuristics.
1105   return TargetLowering::getJumpTableEncoding();
1106 }
1107
1108 /// getPICBaseSymbol - Return the X86-32 PIC base.
1109 MCSymbol *
1110 X86TargetLowering::getPICBaseSymbol(const MachineFunction *MF,
1111                                     MCContext &Ctx) const {
1112   const MCAsmInfo &MAI = *getTargetMachine().getMCAsmInfo();
1113   return Ctx.GetOrCreateSymbol(Twine(MAI.getPrivateGlobalPrefix())+
1114                                Twine(MF->getFunctionNumber())+"$pb");
1115 }
1116
1117
1118 const MCExpr *
1119 X86TargetLowering::LowerCustomJumpTableEntry(const MachineJumpTableInfo *MJTI,
1120                                              const MachineBasicBlock *MBB,
1121                                              unsigned uid,MCContext &Ctx) const{
1122   assert(getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1123          Subtarget->isPICStyleGOT());
1124   // In 32-bit ELF systems, our jump table entries are formed with @GOTOFF
1125   // entries.
1126   return MCSymbolRefExpr::Create(MBB->getSymbol(),
1127                                  MCSymbolRefExpr::VK_GOTOFF, Ctx);
1128 }
1129
1130 /// getPICJumpTableRelocaBase - Returns relocation base for the given PIC
1131 /// jumptable.
1132 SDValue X86TargetLowering::getPICJumpTableRelocBase(SDValue Table,
1133                                                     SelectionDAG &DAG) const {
1134   if (!Subtarget->is64Bit())
1135     // This doesn't have DebugLoc associated with it, but is not really the
1136     // same as a Register.
1137     return DAG.getNode(X86ISD::GlobalBaseReg, DebugLoc(), getPointerTy());
1138   return Table;
1139 }
1140
1141 /// getPICJumpTableRelocBaseExpr - This returns the relocation base for the
1142 /// given PIC jumptable, the same as getPICJumpTableRelocBase, but as an
1143 /// MCExpr.
1144 const MCExpr *X86TargetLowering::
1145 getPICJumpTableRelocBaseExpr(const MachineFunction *MF, unsigned JTI,
1146                              MCContext &Ctx) const {
1147   // X86-64 uses RIP relative addressing based on the jump table label.
1148   if (Subtarget->isPICStyleRIPRel())
1149     return TargetLowering::getPICJumpTableRelocBaseExpr(MF, JTI, Ctx);
1150
1151   // Otherwise, the reference is relative to the PIC base.
1152   return MCSymbolRefExpr::Create(getPICBaseSymbol(MF, Ctx), Ctx);
1153 }
1154
1155 /// getFunctionAlignment - Return the Log2 alignment of this function.
1156 unsigned X86TargetLowering::getFunctionAlignment(const Function *F) const {
1157   return F->hasFnAttr(Attribute::OptimizeForSize) ? 0 : 4;
1158 }
1159
1160 //===----------------------------------------------------------------------===//
1161 //               Return Value Calling Convention Implementation
1162 //===----------------------------------------------------------------------===//
1163
1164 #include "X86GenCallingConv.inc"
1165
1166 bool 
1167 X86TargetLowering::CanLowerReturn(CallingConv::ID CallConv, bool isVarArg,
1168                         const SmallVectorImpl<EVT> &OutTys,
1169                         const SmallVectorImpl<ISD::ArgFlagsTy> &ArgsFlags,
1170                         SelectionDAG &DAG) const {
1171   SmallVector<CCValAssign, 16> RVLocs;
1172   CCState CCInfo(CallConv, isVarArg, getTargetMachine(),
1173                  RVLocs, *DAG.getContext());
1174   return CCInfo.CheckReturn(OutTys, ArgsFlags, RetCC_X86);
1175 }
1176
1177 SDValue
1178 X86TargetLowering::LowerReturn(SDValue Chain,
1179                                CallingConv::ID CallConv, bool isVarArg,
1180                                const SmallVectorImpl<ISD::OutputArg> &Outs,
1181                                DebugLoc dl, SelectionDAG &DAG) const {
1182   MachineFunction &MF = DAG.getMachineFunction();
1183   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1184
1185   SmallVector<CCValAssign, 16> RVLocs;
1186   CCState CCInfo(CallConv, isVarArg, getTargetMachine(),
1187                  RVLocs, *DAG.getContext());
1188   CCInfo.AnalyzeReturn(Outs, RetCC_X86);
1189
1190   // Add the regs to the liveout set for the function.
1191   MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo();
1192   for (unsigned i = 0; i != RVLocs.size(); ++i)
1193     if (RVLocs[i].isRegLoc() && !MRI.isLiveOut(RVLocs[i].getLocReg()))
1194       MRI.addLiveOut(RVLocs[i].getLocReg());
1195
1196   SDValue Flag;
1197
1198   SmallVector<SDValue, 6> RetOps;
1199   RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
1200   // Operand #1 = Bytes To Pop
1201   RetOps.push_back(DAG.getTargetConstant(FuncInfo->getBytesToPopOnReturn(),
1202                    MVT::i16));
1203
1204   // Copy the result values into the output registers.
1205   for (unsigned i = 0; i != RVLocs.size(); ++i) {
1206     CCValAssign &VA = RVLocs[i];
1207     assert(VA.isRegLoc() && "Can only return in registers!");
1208     SDValue ValToCopy = Outs[i].Val;
1209
1210     // Returns in ST0/ST1 are handled specially: these are pushed as operands to
1211     // the RET instruction and handled by the FP Stackifier.
1212     if (VA.getLocReg() == X86::ST0 ||
1213         VA.getLocReg() == X86::ST1) {
1214       // If this is a copy from an xmm register to ST(0), use an FPExtend to
1215       // change the value to the FP stack register class.
1216       if (isScalarFPTypeInSSEReg(VA.getValVT()))
1217         ValToCopy = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f80, ValToCopy);
1218       RetOps.push_back(ValToCopy);
1219       // Don't emit a copytoreg.
1220       continue;
1221     }
1222
1223     // 64-bit vector (MMX) values are returned in XMM0 / XMM1 except for v1i64
1224     // which is returned in RAX / RDX.
1225     if (Subtarget->is64Bit()) {
1226       EVT ValVT = ValToCopy.getValueType();
1227       if (ValVT.isVector() && ValVT.getSizeInBits() == 64) {
1228         ValToCopy = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::i64, ValToCopy);
1229         if (VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1)
1230           ValToCopy = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64, ValToCopy);
1231       }
1232     }
1233
1234     Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), ValToCopy, Flag);
1235     Flag = Chain.getValue(1);
1236   }
1237
1238   // The x86-64 ABI for returning structs by value requires that we copy
1239   // the sret argument into %rax for the return. We saved the argument into
1240   // a virtual register in the entry block, so now we copy the value out
1241   // and into %rax.
1242   if (Subtarget->is64Bit() &&
1243       DAG.getMachineFunction().getFunction()->hasStructRetAttr()) {
1244     MachineFunction &MF = DAG.getMachineFunction();
1245     X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1246     unsigned Reg = FuncInfo->getSRetReturnReg();
1247     if (!Reg) {
1248       Reg = MRI.createVirtualRegister(getRegClassFor(MVT::i64));
1249       FuncInfo->setSRetReturnReg(Reg);
1250     }
1251     SDValue Val = DAG.getCopyFromReg(Chain, dl, Reg, getPointerTy());
1252
1253     Chain = DAG.getCopyToReg(Chain, dl, X86::RAX, Val, Flag);
1254     Flag = Chain.getValue(1);
1255
1256     // RAX now acts like a return value.
1257     MRI.addLiveOut(X86::RAX);
1258   }
1259
1260   RetOps[0] = Chain;  // Update chain.
1261
1262   // Add the flag if we have it.
1263   if (Flag.getNode())
1264     RetOps.push_back(Flag);
1265
1266   return DAG.getNode(X86ISD::RET_FLAG, dl,
1267                      MVT::Other, &RetOps[0], RetOps.size());
1268 }
1269
1270 /// LowerCallResult - Lower the result values of a call into the
1271 /// appropriate copies out of appropriate physical registers.
1272 ///
1273 SDValue
1274 X86TargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
1275                                    CallingConv::ID CallConv, bool isVarArg,
1276                                    const SmallVectorImpl<ISD::InputArg> &Ins,
1277                                    DebugLoc dl, SelectionDAG &DAG,
1278                                    SmallVectorImpl<SDValue> &InVals) const {
1279
1280   // Assign locations to each value returned by this call.
1281   SmallVector<CCValAssign, 16> RVLocs;
1282   bool Is64Bit = Subtarget->is64Bit();
1283   CCState CCInfo(CallConv, isVarArg, getTargetMachine(),
1284                  RVLocs, *DAG.getContext());
1285   CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
1286
1287   // Copy all of the result registers out of their specified physreg.
1288   for (unsigned i = 0; i != RVLocs.size(); ++i) {
1289     CCValAssign &VA = RVLocs[i];
1290     EVT CopyVT = VA.getValVT();
1291
1292     // If this is x86-64, and we disabled SSE, we can't return FP values
1293     if ((CopyVT == MVT::f32 || CopyVT == MVT::f64) &&
1294         ((Is64Bit || Ins[i].Flags.isInReg()) && !Subtarget->hasSSE1())) {
1295       report_fatal_error("SSE register return with SSE disabled");
1296     }
1297
1298     // If this is a call to a function that returns an fp value on the floating
1299     // point stack, but where we prefer to use the value in xmm registers, copy
1300     // it out as F80 and use a truncate to move it from fp stack reg to xmm reg.
1301     if ((VA.getLocReg() == X86::ST0 ||
1302          VA.getLocReg() == X86::ST1) &&
1303         isScalarFPTypeInSSEReg(VA.getValVT())) {
1304       CopyVT = MVT::f80;
1305     }
1306
1307     SDValue Val;
1308     if (Is64Bit && CopyVT.isVector() && CopyVT.getSizeInBits() == 64) {
1309       // For x86-64, MMX values are returned in XMM0 / XMM1 except for v1i64.
1310       if (VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) {
1311         Chain = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(),
1312                                    MVT::v2i64, InFlag).getValue(1);
1313         Val = Chain.getValue(0);
1314         Val = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i64,
1315                           Val, DAG.getConstant(0, MVT::i64));
1316       } else {
1317         Chain = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(),
1318                                    MVT::i64, InFlag).getValue(1);
1319         Val = Chain.getValue(0);
1320       }
1321       Val = DAG.getNode(ISD::BIT_CONVERT, dl, CopyVT, Val);
1322     } else {
1323       Chain = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(),
1324                                  CopyVT, InFlag).getValue(1);
1325       Val = Chain.getValue(0);
1326     }
1327     InFlag = Chain.getValue(2);
1328
1329     if (CopyVT != VA.getValVT()) {
1330       // Round the F80 the right size, which also moves to the appropriate xmm
1331       // register.
1332       Val = DAG.getNode(ISD::FP_ROUND, dl, VA.getValVT(), Val,
1333                         // This truncation won't change the value.
1334                         DAG.getIntPtrConstant(1));
1335     }
1336
1337     InVals.push_back(Val);
1338   }
1339
1340   return Chain;
1341 }
1342
1343
1344 //===----------------------------------------------------------------------===//
1345 //                C & StdCall & Fast Calling Convention implementation
1346 //===----------------------------------------------------------------------===//
1347 //  StdCall calling convention seems to be standard for many Windows' API
1348 //  routines and around. It differs from C calling convention just a little:
1349 //  callee should clean up the stack, not caller. Symbols should be also
1350 //  decorated in some fancy way :) It doesn't support any vector arguments.
1351 //  For info on fast calling convention see Fast Calling Convention (tail call)
1352 //  implementation LowerX86_32FastCCCallTo.
1353
1354 /// CallIsStructReturn - Determines whether a call uses struct return
1355 /// semantics.
1356 static bool CallIsStructReturn(const SmallVectorImpl<ISD::OutputArg> &Outs) {
1357   if (Outs.empty())
1358     return false;
1359
1360   return Outs[0].Flags.isSRet();
1361 }
1362
1363 /// ArgsAreStructReturn - Determines whether a function uses struct
1364 /// return semantics.
1365 static bool
1366 ArgsAreStructReturn(const SmallVectorImpl<ISD::InputArg> &Ins) {
1367   if (Ins.empty())
1368     return false;
1369
1370   return Ins[0].Flags.isSRet();
1371 }
1372
1373 /// IsCalleePop - Determines whether the callee is required to pop its
1374 /// own arguments. Callee pop is necessary to support tail calls.
1375 bool X86TargetLowering::IsCalleePop(bool IsVarArg,
1376                                     CallingConv::ID CallingConv) const {
1377   if (IsVarArg)
1378     return false;
1379
1380   switch (CallingConv) {
1381   default:
1382     return false;
1383   case CallingConv::X86_StdCall:
1384     return !Subtarget->is64Bit();
1385   case CallingConv::X86_FastCall:
1386     return !Subtarget->is64Bit();
1387   case CallingConv::Fast:
1388     return GuaranteedTailCallOpt;
1389   case CallingConv::GHC:
1390     return GuaranteedTailCallOpt;
1391   }
1392 }
1393
1394 /// CCAssignFnForNode - Selects the correct CCAssignFn for a the
1395 /// given CallingConvention value.
1396 CCAssignFn *X86TargetLowering::CCAssignFnForNode(CallingConv::ID CC) const {
1397   if (Subtarget->is64Bit()) {
1398     if (CC == CallingConv::GHC)
1399       return CC_X86_64_GHC;
1400     else 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 if (CC == CallingConv::GHC)
1411     return CC_X86_32_GHC;
1412   else
1413     return CC_X86_32_C;
1414 }
1415
1416 /// CreateCopyOfByValArgument - Make a copy of an aggregate at address specified
1417 /// by "Src" to address "Dst" with size and alignment information specified by
1418 /// the specific parameter attribute. The copy will be passed as a byval
1419 /// function parameter.
1420 static SDValue
1421 CreateCopyOfByValArgument(SDValue Src, SDValue Dst, SDValue Chain,
1422                           ISD::ArgFlagsTy Flags, SelectionDAG &DAG,
1423                           DebugLoc dl) {
1424   SDValue SizeNode     = DAG.getConstant(Flags.getByValSize(), MVT::i32);
1425   return DAG.getMemcpy(Chain, dl, Dst, Src, SizeNode, Flags.getByValAlign(),
1426                        /*isVolatile*/false, /*AlwaysInline=*/true,
1427                        NULL, 0, NULL, 0);
1428 }
1429
1430 /// IsTailCallConvention - Return true if the calling convention is one that
1431 /// supports tail call optimization.
1432 static bool IsTailCallConvention(CallingConv::ID CC) {
1433   return (CC == CallingConv::Fast || CC == CallingConv::GHC);
1434 }
1435
1436 /// FuncIsMadeTailCallSafe - Return true if the function is being made into
1437 /// a tailcall target by changing its ABI.
1438 static bool FuncIsMadeTailCallSafe(CallingConv::ID CC) {
1439   return GuaranteedTailCallOpt && IsTailCallConvention(CC);
1440 }
1441
1442 SDValue
1443 X86TargetLowering::LowerMemArgument(SDValue Chain,
1444                                     CallingConv::ID CallConv,
1445                                     const SmallVectorImpl<ISD::InputArg> &Ins,
1446                                     DebugLoc dl, SelectionDAG &DAG,
1447                                     const CCValAssign &VA,
1448                                     MachineFrameInfo *MFI,
1449                                     unsigned i) const {
1450   // Create the nodes corresponding to a load from this parameter slot.
1451   ISD::ArgFlagsTy Flags = Ins[i].Flags;
1452   bool AlwaysUseMutable = FuncIsMadeTailCallSafe(CallConv);
1453   bool isImmutable = !AlwaysUseMutable && !Flags.isByVal();
1454   EVT ValVT;
1455
1456   // If value is passed by pointer we have address passed instead of the value
1457   // itself.
1458   if (VA.getLocInfo() == CCValAssign::Indirect)
1459     ValVT = VA.getLocVT();
1460   else
1461     ValVT = VA.getValVT();
1462
1463   // FIXME: For now, all byval parameter objects are marked mutable. This can be
1464   // changed with more analysis.
1465   // In case of tail call optimization mark all arguments mutable. Since they
1466   // could be overwritten by lowering of arguments in case of a tail call.
1467   if (Flags.isByVal()) {
1468     int FI = MFI->CreateFixedObject(Flags.getByValSize(),
1469                                     VA.getLocMemOffset(), isImmutable, false);
1470     return DAG.getFrameIndex(FI, getPointerTy());
1471   } else {
1472     int FI = MFI->CreateFixedObject(ValVT.getSizeInBits()/8,
1473                                     VA.getLocMemOffset(), isImmutable, false);
1474     SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
1475     return DAG.getLoad(ValVT, dl, Chain, FIN,
1476                        PseudoSourceValue::getFixedStack(FI), 0,
1477                        false, false, 0);
1478   }
1479 }
1480
1481 SDValue
1482 X86TargetLowering::LowerFormalArguments(SDValue Chain,
1483                                         CallingConv::ID CallConv,
1484                                         bool isVarArg,
1485                                       const SmallVectorImpl<ISD::InputArg> &Ins,
1486                                         DebugLoc dl,
1487                                         SelectionDAG &DAG,
1488                                         SmallVectorImpl<SDValue> &InVals)
1489                                           const {
1490   MachineFunction &MF = DAG.getMachineFunction();
1491   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1492
1493   const Function* Fn = MF.getFunction();
1494   if (Fn->hasExternalLinkage() &&
1495       Subtarget->isTargetCygMing() &&
1496       Fn->getName() == "main")
1497     FuncInfo->setForceFramePointer(true);
1498
1499   MachineFrameInfo *MFI = MF.getFrameInfo();
1500   bool Is64Bit = Subtarget->is64Bit();
1501   bool IsWin64 = Subtarget->isTargetWin64();
1502
1503   assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
1504          "Var args not supported with calling convention fastcc or ghc");
1505
1506   // Assign locations to all of the incoming arguments.
1507   SmallVector<CCValAssign, 16> ArgLocs;
1508   CCState CCInfo(CallConv, isVarArg, getTargetMachine(),
1509                  ArgLocs, *DAG.getContext());
1510   CCInfo.AnalyzeFormalArguments(Ins, CCAssignFnForNode(CallConv));
1511
1512   unsigned LastVal = ~0U;
1513   SDValue ArgValue;
1514   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
1515     CCValAssign &VA = ArgLocs[i];
1516     // TODO: If an arg is passed in two places (e.g. reg and stack), skip later
1517     // places.
1518     assert(VA.getValNo() != LastVal &&
1519            "Don't support value assigned to multiple locs yet");
1520     LastVal = VA.getValNo();
1521
1522     if (VA.isRegLoc()) {
1523       EVT RegVT = VA.getLocVT();
1524       TargetRegisterClass *RC = NULL;
1525       if (RegVT == MVT::i32)
1526         RC = X86::GR32RegisterClass;
1527       else if (Is64Bit && RegVT == MVT::i64)
1528         RC = X86::GR64RegisterClass;
1529       else if (RegVT == MVT::f32)
1530         RC = X86::FR32RegisterClass;
1531       else if (RegVT == MVT::f64)
1532         RC = X86::FR64RegisterClass;
1533       else if (RegVT.isVector() && RegVT.getSizeInBits() == 128)
1534         RC = X86::VR128RegisterClass;
1535       else if (RegVT.isVector() && RegVT.getSizeInBits() == 64)
1536         RC = X86::VR64RegisterClass;
1537       else
1538         llvm_unreachable("Unknown argument type!");
1539
1540       unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
1541       ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
1542
1543       // If this is an 8 or 16-bit value, it is really passed promoted to 32
1544       // bits.  Insert an assert[sz]ext to capture this, then truncate to the
1545       // right size.
1546       if (VA.getLocInfo() == CCValAssign::SExt)
1547         ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
1548                                DAG.getValueType(VA.getValVT()));
1549       else if (VA.getLocInfo() == CCValAssign::ZExt)
1550         ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
1551                                DAG.getValueType(VA.getValVT()));
1552       else if (VA.getLocInfo() == CCValAssign::BCvt)
1553         ArgValue = DAG.getNode(ISD::BIT_CONVERT, dl, VA.getValVT(), ArgValue);
1554
1555       if (VA.isExtInLoc()) {
1556         // Handle MMX values passed in XMM regs.
1557         if (RegVT.isVector()) {
1558           ArgValue = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i64,
1559                                  ArgValue, DAG.getConstant(0, MVT::i64));
1560           ArgValue = DAG.getNode(ISD::BIT_CONVERT, dl, VA.getValVT(), ArgValue);
1561         } else
1562           ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
1563       }
1564     } else {
1565       assert(VA.isMemLoc());
1566       ArgValue = LowerMemArgument(Chain, CallConv, Ins, dl, DAG, VA, MFI, i);
1567     }
1568
1569     // If value is passed via pointer - do a load.
1570     if (VA.getLocInfo() == CCValAssign::Indirect)
1571       ArgValue = DAG.getLoad(VA.getValVT(), dl, Chain, ArgValue, NULL, 0,
1572                              false, false, 0);
1573
1574     InVals.push_back(ArgValue);
1575   }
1576
1577   // The x86-64 ABI for returning structs by value requires that we copy
1578   // the sret argument into %rax for the return. Save the argument into
1579   // a virtual register so that we can access it from the return points.
1580   if (Is64Bit && MF.getFunction()->hasStructRetAttr()) {
1581     X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1582     unsigned Reg = FuncInfo->getSRetReturnReg();
1583     if (!Reg) {
1584       Reg = MF.getRegInfo().createVirtualRegister(getRegClassFor(MVT::i64));
1585       FuncInfo->setSRetReturnReg(Reg);
1586     }
1587     SDValue Copy = DAG.getCopyToReg(DAG.getEntryNode(), dl, Reg, InVals[0]);
1588     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Copy, Chain);
1589   }
1590
1591   unsigned StackSize = CCInfo.getNextStackOffset();
1592   // Align stack specially for tail calls.
1593   if (FuncIsMadeTailCallSafe(CallConv))
1594     StackSize = GetAlignedArgumentStackSize(StackSize, DAG);
1595
1596   // If the function takes variable number of arguments, make a frame index for
1597   // the start of the first vararg value... for expansion of llvm.va_start.
1598   if (isVarArg) {
1599     if (Is64Bit || CallConv != CallingConv::X86_FastCall) {
1600       FuncInfo->setVarArgsFrameIndex(MFI->CreateFixedObject(1, StackSize,
1601                                                             true, false));
1602     }
1603     if (Is64Bit) {
1604       unsigned TotalNumIntRegs = 0, TotalNumXMMRegs = 0;
1605
1606       // FIXME: We should really autogenerate these arrays
1607       static const unsigned GPR64ArgRegsWin64[] = {
1608         X86::RCX, X86::RDX, X86::R8,  X86::R9
1609       };
1610       static const unsigned XMMArgRegsWin64[] = {
1611         X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3
1612       };
1613       static const unsigned GPR64ArgRegs64Bit[] = {
1614         X86::RDI, X86::RSI, X86::RDX, X86::RCX, X86::R8, X86::R9
1615       };
1616       static const unsigned XMMArgRegs64Bit[] = {
1617         X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
1618         X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
1619       };
1620       const unsigned *GPR64ArgRegs, *XMMArgRegs;
1621
1622       if (IsWin64) {
1623         TotalNumIntRegs = 4; TotalNumXMMRegs = 4;
1624         GPR64ArgRegs = GPR64ArgRegsWin64;
1625         XMMArgRegs = XMMArgRegsWin64;
1626       } else {
1627         TotalNumIntRegs = 6; TotalNumXMMRegs = 8;
1628         GPR64ArgRegs = GPR64ArgRegs64Bit;
1629         XMMArgRegs = XMMArgRegs64Bit;
1630       }
1631       unsigned NumIntRegs = CCInfo.getFirstUnallocated(GPR64ArgRegs,
1632                                                        TotalNumIntRegs);
1633       unsigned NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs,
1634                                                        TotalNumXMMRegs);
1635
1636       bool NoImplicitFloatOps = Fn->hasFnAttr(Attribute::NoImplicitFloat);
1637       assert(!(NumXMMRegs && !Subtarget->hasSSE1()) &&
1638              "SSE register cannot be used when SSE is disabled!");
1639       assert(!(NumXMMRegs && UseSoftFloat && NoImplicitFloatOps) &&
1640              "SSE register cannot be used when SSE is disabled!");
1641       if (UseSoftFloat || NoImplicitFloatOps || !Subtarget->hasSSE1())
1642         // Kernel mode asks for SSE to be disabled, so don't push them
1643         // on the stack.
1644         TotalNumXMMRegs = 0;
1645
1646       // For X86-64, if there are vararg parameters that are passed via
1647       // registers, then we must store them to their spots on the stack so they
1648       // may be loaded by deferencing the result of va_next.
1649       FuncInfo->setVarArgsGPOffset(NumIntRegs * 8);
1650       FuncInfo->setVarArgsFPOffset(TotalNumIntRegs * 8 + NumXMMRegs * 16);
1651       FuncInfo->setRegSaveFrameIndex(
1652         MFI->CreateStackObject(TotalNumIntRegs * 8 + TotalNumXMMRegs * 16, 16,
1653                                false));
1654
1655       // Store the integer parameter registers.
1656       SmallVector<SDValue, 8> MemOps;
1657       SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
1658                                         getPointerTy());
1659       unsigned Offset = FuncInfo->getVarArgsGPOffset();
1660       for (; NumIntRegs != TotalNumIntRegs; ++NumIntRegs) {
1661         SDValue FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(), RSFIN,
1662                                   DAG.getIntPtrConstant(Offset));
1663         unsigned VReg = MF.addLiveIn(GPR64ArgRegs[NumIntRegs],
1664                                      X86::GR64RegisterClass);
1665         SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
1666         SDValue Store =
1667           DAG.getStore(Val.getValue(1), dl, Val, FIN,
1668                        PseudoSourceValue::getFixedStack(
1669                          FuncInfo->getRegSaveFrameIndex()),
1670                        Offset, false, false, 0);
1671         MemOps.push_back(Store);
1672         Offset += 8;
1673       }
1674
1675       if (TotalNumXMMRegs != 0 && NumXMMRegs != TotalNumXMMRegs) {
1676         // Now store the XMM (fp + vector) parameter registers.
1677         SmallVector<SDValue, 11> SaveXMMOps;
1678         SaveXMMOps.push_back(Chain);
1679
1680         unsigned AL = MF.addLiveIn(X86::AL, X86::GR8RegisterClass);
1681         SDValue ALVal = DAG.getCopyFromReg(DAG.getEntryNode(), dl, AL, MVT::i8);
1682         SaveXMMOps.push_back(ALVal);
1683
1684         SaveXMMOps.push_back(DAG.getIntPtrConstant(
1685                                FuncInfo->getRegSaveFrameIndex()));
1686         SaveXMMOps.push_back(DAG.getIntPtrConstant(
1687                                FuncInfo->getVarArgsFPOffset()));
1688
1689         for (; NumXMMRegs != TotalNumXMMRegs; ++NumXMMRegs) {
1690           unsigned VReg = MF.addLiveIn(XMMArgRegs[NumXMMRegs],
1691                                        X86::VR128RegisterClass);
1692           SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::v4f32);
1693           SaveXMMOps.push_back(Val);
1694         }
1695         MemOps.push_back(DAG.getNode(X86ISD::VASTART_SAVE_XMM_REGS, dl,
1696                                      MVT::Other,
1697                                      &SaveXMMOps[0], SaveXMMOps.size()));
1698       }
1699
1700       if (!MemOps.empty())
1701         Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
1702                             &MemOps[0], MemOps.size());
1703     }
1704   }
1705
1706   // Some CCs need callee pop.
1707   if (IsCalleePop(isVarArg, CallConv)) {
1708     FuncInfo->setBytesToPopOnReturn(StackSize); // Callee pops everything.
1709   } else {
1710     FuncInfo->setBytesToPopOnReturn(0); // Callee pops nothing.
1711     // If this is an sret function, the return should pop the hidden pointer.
1712     if (!Is64Bit && !IsTailCallConvention(CallConv) && ArgsAreStructReturn(Ins))
1713       FuncInfo->setBytesToPopOnReturn(4);
1714   }
1715
1716   if (!Is64Bit) {
1717     // RegSaveFrameIndex is X86-64 only.
1718     FuncInfo->setRegSaveFrameIndex(0xAAAAAAA);
1719     if (CallConv == CallingConv::X86_FastCall)
1720       // fastcc functions can't have varargs.
1721       FuncInfo->setVarArgsFrameIndex(0xAAAAAAA);
1722   }
1723
1724   return Chain;
1725 }
1726
1727 SDValue
1728 X86TargetLowering::LowerMemOpCallTo(SDValue Chain,
1729                                     SDValue StackPtr, SDValue Arg,
1730                                     DebugLoc dl, SelectionDAG &DAG,
1731                                     const CCValAssign &VA,
1732                                     ISD::ArgFlagsTy Flags) const {
1733   const unsigned FirstStackArgOffset = (Subtarget->isTargetWin64() ? 32 : 0);
1734   unsigned LocMemOffset = FirstStackArgOffset + VA.getLocMemOffset();
1735   SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset);
1736   PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, PtrOff);
1737   if (Flags.isByVal()) {
1738     return CreateCopyOfByValArgument(Arg, PtrOff, Chain, Flags, DAG, dl);
1739   }
1740   return DAG.getStore(Chain, dl, Arg, PtrOff,
1741                       PseudoSourceValue::getStack(), LocMemOffset,
1742                       false, false, 0);
1743 }
1744
1745 /// EmitTailCallLoadRetAddr - Emit a load of return address if tail call
1746 /// optimization is performed and it is required.
1747 SDValue
1748 X86TargetLowering::EmitTailCallLoadRetAddr(SelectionDAG &DAG,
1749                                            SDValue &OutRetAddr, SDValue Chain,
1750                                            bool IsTailCall, bool Is64Bit,
1751                                            int FPDiff, DebugLoc dl) const {
1752   // Adjust the Return address stack slot.
1753   EVT VT = getPointerTy();
1754   OutRetAddr = getReturnAddressFrameIndex(DAG);
1755
1756   // Load the "old" Return address.
1757   OutRetAddr = DAG.getLoad(VT, dl, Chain, OutRetAddr, NULL, 0, false, false, 0);
1758   return SDValue(OutRetAddr.getNode(), 1);
1759 }
1760
1761 /// EmitTailCallStoreRetAddr - Emit a store of the return adress if tail call
1762 /// optimization is performed and it is required (FPDiff!=0).
1763 static SDValue
1764 EmitTailCallStoreRetAddr(SelectionDAG & DAG, MachineFunction &MF,
1765                          SDValue Chain, SDValue RetAddrFrIdx,
1766                          bool Is64Bit, int FPDiff, DebugLoc dl) {
1767   // Store the return address to the appropriate stack slot.
1768   if (!FPDiff) return Chain;
1769   // Calculate the new stack slot for the return address.
1770   int SlotSize = Is64Bit ? 8 : 4;
1771   int NewReturnAddrFI =
1772     MF.getFrameInfo()->CreateFixedObject(SlotSize, FPDiff-SlotSize, false, false);
1773   EVT VT = Is64Bit ? MVT::i64 : MVT::i32;
1774   SDValue NewRetAddrFrIdx = DAG.getFrameIndex(NewReturnAddrFI, VT);
1775   Chain = DAG.getStore(Chain, dl, RetAddrFrIdx, NewRetAddrFrIdx,
1776                        PseudoSourceValue::getFixedStack(NewReturnAddrFI), 0,
1777                        false, false, 0);
1778   return Chain;
1779 }
1780
1781 SDValue
1782 X86TargetLowering::LowerCall(SDValue Chain, SDValue Callee,
1783                              CallingConv::ID CallConv, bool isVarArg,
1784                              bool &isTailCall,
1785                              const SmallVectorImpl<ISD::OutputArg> &Outs,
1786                              const SmallVectorImpl<ISD::InputArg> &Ins,
1787                              DebugLoc dl, SelectionDAG &DAG,
1788                              SmallVectorImpl<SDValue> &InVals) const {
1789   MachineFunction &MF = DAG.getMachineFunction();
1790   bool Is64Bit        = Subtarget->is64Bit();
1791   bool IsStructRet    = CallIsStructReturn(Outs);
1792   bool IsSibcall      = false;
1793
1794   if (isTailCall) {
1795     // Check if it's really possible to do a tail call.
1796     isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv,
1797                     isVarArg, IsStructRet, MF.getFunction()->hasStructRetAttr(),
1798                                                    Outs, Ins, DAG);
1799
1800     // Sibcalls are automatically detected tailcalls which do not require
1801     // ABI changes.
1802     if (!GuaranteedTailCallOpt && isTailCall)
1803       IsSibcall = true;
1804
1805     if (isTailCall)
1806       ++NumTailCalls;
1807   }
1808
1809   assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
1810          "Var args not supported with calling convention fastcc or ghc");
1811
1812   // Analyze operands of the call, assigning locations to each operand.
1813   SmallVector<CCValAssign, 16> ArgLocs;
1814   CCState CCInfo(CallConv, isVarArg, getTargetMachine(),
1815                  ArgLocs, *DAG.getContext());
1816   CCInfo.AnalyzeCallOperands(Outs, CCAssignFnForNode(CallConv));
1817
1818   // Get a count of how many bytes are to be pushed on the stack.
1819   unsigned NumBytes = CCInfo.getNextStackOffset();
1820   if (IsSibcall)
1821     // This is a sibcall. The memory operands are available in caller's
1822     // own caller's stack.
1823     NumBytes = 0;
1824   else if (GuaranteedTailCallOpt && IsTailCallConvention(CallConv))
1825     NumBytes = GetAlignedArgumentStackSize(NumBytes, DAG);
1826
1827   int FPDiff = 0;
1828   if (isTailCall && !IsSibcall) {
1829     // Lower arguments at fp - stackoffset + fpdiff.
1830     unsigned NumBytesCallerPushed =
1831       MF.getInfo<X86MachineFunctionInfo>()->getBytesToPopOnReturn();
1832     FPDiff = NumBytesCallerPushed - NumBytes;
1833
1834     // Set the delta of movement of the returnaddr stackslot.
1835     // But only set if delta is greater than previous delta.
1836     if (FPDiff < (MF.getInfo<X86MachineFunctionInfo>()->getTCReturnAddrDelta()))
1837       MF.getInfo<X86MachineFunctionInfo>()->setTCReturnAddrDelta(FPDiff);
1838   }
1839
1840   if (!IsSibcall)
1841     Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes, true));
1842
1843   SDValue RetAddrFrIdx;
1844   // Load return adress for tail calls.
1845   if (isTailCall && FPDiff)
1846     Chain = EmitTailCallLoadRetAddr(DAG, RetAddrFrIdx, Chain, isTailCall,
1847                                     Is64Bit, FPDiff, dl);
1848
1849   SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
1850   SmallVector<SDValue, 8> MemOpChains;
1851   SDValue StackPtr;
1852
1853   // Walk the register/memloc assignments, inserting copies/loads.  In the case
1854   // of tail call optimization arguments are handle later.
1855   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
1856     CCValAssign &VA = ArgLocs[i];
1857     EVT RegVT = VA.getLocVT();
1858     SDValue Arg = Outs[i].Val;
1859     ISD::ArgFlagsTy Flags = Outs[i].Flags;
1860     bool isByVal = Flags.isByVal();
1861
1862     // Promote the value if needed.
1863     switch (VA.getLocInfo()) {
1864     default: llvm_unreachable("Unknown loc info!");
1865     case CCValAssign::Full: break;
1866     case CCValAssign::SExt:
1867       Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, RegVT, Arg);
1868       break;
1869     case CCValAssign::ZExt:
1870       Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, RegVT, Arg);
1871       break;
1872     case CCValAssign::AExt:
1873       if (RegVT.isVector() && RegVT.getSizeInBits() == 128) {
1874         // Special case: passing MMX values in XMM registers.
1875         Arg = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::i64, Arg);
1876         Arg = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64, Arg);
1877         Arg = getMOVL(DAG, dl, MVT::v2i64, DAG.getUNDEF(MVT::v2i64), Arg);
1878       } else
1879         Arg = DAG.getNode(ISD::ANY_EXTEND, dl, RegVT, Arg);
1880       break;
1881     case CCValAssign::BCvt:
1882       Arg = DAG.getNode(ISD::BIT_CONVERT, dl, RegVT, Arg);
1883       break;
1884     case CCValAssign::Indirect: {
1885       // Store the argument.
1886       SDValue SpillSlot = DAG.CreateStackTemporary(VA.getValVT());
1887       int FI = cast<FrameIndexSDNode>(SpillSlot)->getIndex();
1888       Chain = DAG.getStore(Chain, dl, Arg, SpillSlot,
1889                            PseudoSourceValue::getFixedStack(FI), 0,
1890                            false, false, 0);
1891       Arg = SpillSlot;
1892       break;
1893     }
1894     }
1895
1896     if (VA.isRegLoc()) {
1897       RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
1898     } else if (!IsSibcall && (!isTailCall || isByVal)) {
1899       assert(VA.isMemLoc());
1900       if (StackPtr.getNode() == 0)
1901         StackPtr = DAG.getCopyFromReg(Chain, dl, X86StackPtr, getPointerTy());
1902       MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg,
1903                                              dl, DAG, VA, Flags));
1904     }
1905   }
1906
1907   if (!MemOpChains.empty())
1908     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
1909                         &MemOpChains[0], MemOpChains.size());
1910
1911   // Build a sequence of copy-to-reg nodes chained together with token chain
1912   // and flag operands which copy the outgoing args into registers.
1913   SDValue InFlag;
1914   // Tail call byval lowering might overwrite argument registers so in case of
1915   // tail call optimization the copies to registers are lowered later.
1916   if (!isTailCall)
1917     for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
1918       Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
1919                                RegsToPass[i].second, InFlag);
1920       InFlag = Chain.getValue(1);
1921     }
1922
1923   if (Subtarget->isPICStyleGOT()) {
1924     // ELF / PIC requires GOT in the EBX register before function calls via PLT
1925     // GOT pointer.
1926     if (!isTailCall) {
1927       Chain = DAG.getCopyToReg(Chain, dl, X86::EBX,
1928                                DAG.getNode(X86ISD::GlobalBaseReg,
1929                                            DebugLoc(), getPointerTy()),
1930                                InFlag);
1931       InFlag = Chain.getValue(1);
1932     } else {
1933       // If we are tail calling and generating PIC/GOT style code load the
1934       // address of the callee into ECX. The value in ecx is used as target of
1935       // the tail jump. This is done to circumvent the ebx/callee-saved problem
1936       // for tail calls on PIC/GOT architectures. Normally we would just put the
1937       // address of GOT into ebx and then call target@PLT. But for tail calls
1938       // ebx would be restored (since ebx is callee saved) before jumping to the
1939       // target@PLT.
1940
1941       // Note: The actual moving to ECX is done further down.
1942       GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee);
1943       if (G && !G->getGlobal()->hasHiddenVisibility() &&
1944           !G->getGlobal()->hasProtectedVisibility())
1945         Callee = LowerGlobalAddress(Callee, DAG);
1946       else if (isa<ExternalSymbolSDNode>(Callee))
1947         Callee = LowerExternalSymbol(Callee, DAG);
1948     }
1949   }
1950
1951   if (Is64Bit && isVarArg) {
1952     // From AMD64 ABI document:
1953     // For calls that may call functions that use varargs or stdargs
1954     // (prototype-less calls or calls to functions containing ellipsis (...) in
1955     // the declaration) %al is used as hidden argument to specify the number
1956     // of SSE registers used. The contents of %al do not need to match exactly
1957     // the number of registers, but must be an ubound on the number of SSE
1958     // registers used and is in the range 0 - 8 inclusive.
1959
1960     // FIXME: Verify this on Win64
1961     // Count the number of XMM registers allocated.
1962     static const unsigned XMMArgRegs[] = {
1963       X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
1964       X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
1965     };
1966     unsigned NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs, 8);
1967     assert((Subtarget->hasSSE1() || !NumXMMRegs)
1968            && "SSE registers cannot be used when SSE is disabled");
1969
1970     Chain = DAG.getCopyToReg(Chain, dl, X86::AL,
1971                              DAG.getConstant(NumXMMRegs, MVT::i8), InFlag);
1972     InFlag = Chain.getValue(1);
1973   }
1974
1975
1976   // For tail calls lower the arguments to the 'real' stack slot.
1977   if (isTailCall) {
1978     // Force all the incoming stack arguments to be loaded from the stack
1979     // before any new outgoing arguments are stored to the stack, because the
1980     // outgoing stack slots may alias the incoming argument stack slots, and
1981     // the alias isn't otherwise explicit. This is slightly more conservative
1982     // than necessary, because it means that each store effectively depends
1983     // on every argument instead of just those arguments it would clobber.
1984     SDValue ArgChain = DAG.getStackArgumentTokenFactor(Chain);
1985
1986     SmallVector<SDValue, 8> MemOpChains2;
1987     SDValue FIN;
1988     int FI = 0;
1989     // Do not flag preceeding copytoreg stuff together with the following stuff.
1990     InFlag = SDValue();
1991     if (GuaranteedTailCallOpt) {
1992       for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
1993         CCValAssign &VA = ArgLocs[i];
1994         if (VA.isRegLoc())
1995           continue;
1996         assert(VA.isMemLoc());
1997         SDValue Arg = Outs[i].Val;
1998         ISD::ArgFlagsTy Flags = Outs[i].Flags;
1999         // Create frame index.
2000         int32_t Offset = VA.getLocMemOffset()+FPDiff;
2001         uint32_t OpSize = (VA.getLocVT().getSizeInBits()+7)/8;
2002         FI = MF.getFrameInfo()->CreateFixedObject(OpSize, Offset, true, false);
2003         FIN = DAG.getFrameIndex(FI, getPointerTy());
2004
2005         if (Flags.isByVal()) {
2006           // Copy relative to framepointer.
2007           SDValue Source = DAG.getIntPtrConstant(VA.getLocMemOffset());
2008           if (StackPtr.getNode() == 0)
2009             StackPtr = DAG.getCopyFromReg(Chain, dl, X86StackPtr,
2010                                           getPointerTy());
2011           Source = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, Source);
2012
2013           MemOpChains2.push_back(CreateCopyOfByValArgument(Source, FIN,
2014                                                            ArgChain,
2015                                                            Flags, DAG, dl));
2016         } else {
2017           // Store relative to framepointer.
2018           MemOpChains2.push_back(
2019             DAG.getStore(ArgChain, dl, Arg, FIN,
2020                          PseudoSourceValue::getFixedStack(FI), 0,
2021                          false, false, 0));
2022         }
2023       }
2024     }
2025
2026     if (!MemOpChains2.empty())
2027       Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
2028                           &MemOpChains2[0], MemOpChains2.size());
2029
2030     // Copy arguments to their registers.
2031     for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
2032       Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
2033                                RegsToPass[i].second, InFlag);
2034       InFlag = Chain.getValue(1);
2035     }
2036     InFlag =SDValue();
2037
2038     // Store the return address to the appropriate stack slot.
2039     Chain = EmitTailCallStoreRetAddr(DAG, MF, Chain, RetAddrFrIdx, Is64Bit,
2040                                      FPDiff, dl);
2041   }
2042
2043   bool WasGlobalOrExternal = false;
2044   if (getTargetMachine().getCodeModel() == CodeModel::Large) {
2045     assert(Is64Bit && "Large code model is only legal in 64-bit mode.");
2046     // In the 64-bit large code model, we have to make all calls
2047     // through a register, since the call instruction's 32-bit
2048     // pc-relative offset may not be large enough to hold the whole
2049     // address.
2050   } else if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
2051     WasGlobalOrExternal = true;
2052     // If the callee is a GlobalAddress node (quite common, every direct call
2053     // is) turn it into a TargetGlobalAddress node so that legalize doesn't hack
2054     // it.
2055
2056     // We should use extra load for direct calls to dllimported functions in
2057     // non-JIT mode.
2058     const GlobalValue *GV = G->getGlobal();
2059     if (!GV->hasDLLImportLinkage()) {
2060       unsigned char OpFlags = 0;
2061
2062       // On ELF targets, in both X86-64 and X86-32 mode, direct calls to
2063       // external symbols most go through the PLT in PIC mode.  If the symbol
2064       // has hidden or protected visibility, or if it is static or local, then
2065       // we don't need to use the PLT - we can directly call it.
2066       if (Subtarget->isTargetELF() &&
2067           getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
2068           GV->hasDefaultVisibility() && !GV->hasLocalLinkage()) {
2069         OpFlags = X86II::MO_PLT;
2070       } else if (Subtarget->isPICStyleStubAny() &&
2071                (GV->isDeclaration() || GV->isWeakForLinker()) &&
2072                Subtarget->getDarwinVers() < 9) {
2073         // PC-relative references to external symbols should go through $stub,
2074         // unless we're building with the leopard linker or later, which
2075         // automatically synthesizes these stubs.
2076         OpFlags = X86II::MO_DARWIN_STUB;
2077       }
2078
2079       Callee = DAG.getTargetGlobalAddress(GV, getPointerTy(),
2080                                           G->getOffset(), OpFlags);
2081     }
2082   } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
2083     WasGlobalOrExternal = true;
2084     unsigned char OpFlags = 0;
2085
2086     // On ELF targets, in either X86-64 or X86-32 mode, direct calls to external
2087     // symbols should go through the PLT.
2088     if (Subtarget->isTargetELF() &&
2089         getTargetMachine().getRelocationModel() == Reloc::PIC_) {
2090       OpFlags = X86II::MO_PLT;
2091     } else if (Subtarget->isPICStyleStubAny() &&
2092              Subtarget->getDarwinVers() < 9) {
2093       // PC-relative references to external symbols should go through $stub,
2094       // unless we're building with the leopard linker or later, which
2095       // automatically synthesizes these stubs.
2096       OpFlags = X86II::MO_DARWIN_STUB;
2097     }
2098
2099     Callee = DAG.getTargetExternalSymbol(S->getSymbol(), getPointerTy(),
2100                                          OpFlags);
2101   }
2102
2103   // Returns a chain & a flag for retval copy to use.
2104   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Flag);
2105   SmallVector<SDValue, 8> Ops;
2106
2107   if (!IsSibcall && isTailCall) {
2108     Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, true),
2109                            DAG.getIntPtrConstant(0, true), InFlag);
2110     InFlag = Chain.getValue(1);
2111   }
2112
2113   Ops.push_back(Chain);
2114   Ops.push_back(Callee);
2115
2116   if (isTailCall)
2117     Ops.push_back(DAG.getConstant(FPDiff, MVT::i32));
2118
2119   // Add argument registers to the end of the list so that they are known live
2120   // into the call.
2121   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
2122     Ops.push_back(DAG.getRegister(RegsToPass[i].first,
2123                                   RegsToPass[i].second.getValueType()));
2124
2125   // Add an implicit use GOT pointer in EBX.
2126   if (!isTailCall && Subtarget->isPICStyleGOT())
2127     Ops.push_back(DAG.getRegister(X86::EBX, getPointerTy()));
2128
2129   // Add an implicit use of AL for x86 vararg functions.
2130   if (Is64Bit && isVarArg)
2131     Ops.push_back(DAG.getRegister(X86::AL, MVT::i8));
2132
2133   if (InFlag.getNode())
2134     Ops.push_back(InFlag);
2135
2136   if (isTailCall) {
2137     // If this is the first return lowered for this function, add the regs
2138     // to the liveout set for the function.
2139     if (MF.getRegInfo().liveout_empty()) {
2140       SmallVector<CCValAssign, 16> RVLocs;
2141       CCState CCInfo(CallConv, isVarArg, getTargetMachine(), RVLocs,
2142                      *DAG.getContext());
2143       CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
2144       for (unsigned i = 0; i != RVLocs.size(); ++i)
2145         if (RVLocs[i].isRegLoc())
2146           MF.getRegInfo().addLiveOut(RVLocs[i].getLocReg());
2147     }
2148     return DAG.getNode(X86ISD::TC_RETURN, dl,
2149                        NodeTys, &Ops[0], Ops.size());
2150   }
2151
2152   Chain = DAG.getNode(X86ISD::CALL, dl, NodeTys, &Ops[0], Ops.size());
2153   InFlag = Chain.getValue(1);
2154
2155   // Create the CALLSEQ_END node.
2156   unsigned NumBytesForCalleeToPush;
2157   if (IsCalleePop(isVarArg, CallConv))
2158     NumBytesForCalleeToPush = NumBytes;    // Callee pops everything
2159   else if (!Is64Bit && !IsTailCallConvention(CallConv) && IsStructRet)
2160     // If this is a call to a struct-return function, the callee
2161     // pops the hidden struct pointer, so we have to push it back.
2162     // This is common for Darwin/X86, Linux & Mingw32 targets.
2163     NumBytesForCalleeToPush = 4;
2164   else
2165     NumBytesForCalleeToPush = 0;  // Callee pops nothing.
2166
2167   // Returns a flag for retval copy to use.
2168   if (!IsSibcall) {
2169     Chain = DAG.getCALLSEQ_END(Chain,
2170                                DAG.getIntPtrConstant(NumBytes, true),
2171                                DAG.getIntPtrConstant(NumBytesForCalleeToPush,
2172                                                      true),
2173                                InFlag);
2174     InFlag = Chain.getValue(1);
2175   }
2176
2177   // Handle result values, copying them out of physregs into vregs that we
2178   // return.
2179   return LowerCallResult(Chain, InFlag, CallConv, isVarArg,
2180                          Ins, dl, DAG, InVals);
2181 }
2182
2183
2184 //===----------------------------------------------------------------------===//
2185 //                Fast Calling Convention (tail call) implementation
2186 //===----------------------------------------------------------------------===//
2187
2188 //  Like std call, callee cleans arguments, convention except that ECX is
2189 //  reserved for storing the tail called function address. Only 2 registers are
2190 //  free for argument passing (inreg). Tail call optimization is performed
2191 //  provided:
2192 //                * tailcallopt is enabled
2193 //                * caller/callee are fastcc
2194 //  On X86_64 architecture with GOT-style position independent code only local
2195 //  (within module) calls are supported at the moment.
2196 //  To keep the stack aligned according to platform abi the function
2197 //  GetAlignedArgumentStackSize ensures that argument delta is always multiples
2198 //  of stack alignment. (Dynamic linkers need this - darwin's dyld for example)
2199 //  If a tail called function callee has more arguments than the caller the
2200 //  caller needs to make sure that there is room to move the RETADDR to. This is
2201 //  achieved by reserving an area the size of the argument delta right after the
2202 //  original REtADDR, but before the saved framepointer or the spilled registers
2203 //  e.g. caller(arg1, arg2) calls callee(arg1, arg2,arg3,arg4)
2204 //  stack layout:
2205 //    arg1
2206 //    arg2
2207 //    RETADDR
2208 //    [ new RETADDR
2209 //      move area ]
2210 //    (possible EBP)
2211 //    ESI
2212 //    EDI
2213 //    local1 ..
2214
2215 /// GetAlignedArgumentStackSize - Make the stack size align e.g 16n + 12 aligned
2216 /// for a 16 byte align requirement.
2217 unsigned
2218 X86TargetLowering::GetAlignedArgumentStackSize(unsigned StackSize,
2219                                                SelectionDAG& DAG) const {
2220   MachineFunction &MF = DAG.getMachineFunction();
2221   const TargetMachine &TM = MF.getTarget();
2222   const TargetFrameInfo &TFI = *TM.getFrameInfo();
2223   unsigned StackAlignment = TFI.getStackAlignment();
2224   uint64_t AlignMask = StackAlignment - 1;
2225   int64_t Offset = StackSize;
2226   uint64_t SlotSize = TD->getPointerSize();
2227   if ( (Offset & AlignMask) <= (StackAlignment - SlotSize) ) {
2228     // Number smaller than 12 so just add the difference.
2229     Offset += ((StackAlignment - SlotSize) - (Offset & AlignMask));
2230   } else {
2231     // Mask out lower bits, add stackalignment once plus the 12 bytes.
2232     Offset = ((~AlignMask) & Offset) + StackAlignment +
2233       (StackAlignment-SlotSize);
2234   }
2235   return Offset;
2236 }
2237
2238 /// MatchingStackOffset - Return true if the given stack call argument is
2239 /// already available in the same position (relatively) of the caller's
2240 /// incoming argument stack.
2241 static
2242 bool MatchingStackOffset(SDValue Arg, unsigned Offset, ISD::ArgFlagsTy Flags,
2243                          MachineFrameInfo *MFI, const MachineRegisterInfo *MRI,
2244                          const X86InstrInfo *TII) {
2245   unsigned Bytes = Arg.getValueType().getSizeInBits() / 8;
2246   int FI = INT_MAX;
2247   if (Arg.getOpcode() == ISD::CopyFromReg) {
2248     unsigned VR = cast<RegisterSDNode>(Arg.getOperand(1))->getReg();
2249     if (!VR || TargetRegisterInfo::isPhysicalRegister(VR))
2250       return false;
2251     MachineInstr *Def = MRI->getVRegDef(VR);
2252     if (!Def)
2253       return false;
2254     if (!Flags.isByVal()) {
2255       if (!TII->isLoadFromStackSlot(Def, FI))
2256         return false;
2257     } else {
2258       unsigned Opcode = Def->getOpcode();
2259       if ((Opcode == X86::LEA32r || Opcode == X86::LEA64r) &&
2260           Def->getOperand(1).isFI()) {
2261         FI = Def->getOperand(1).getIndex();
2262         Bytes = Flags.getByValSize();
2263       } else
2264         return false;
2265     }
2266   } else if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Arg)) {
2267     if (Flags.isByVal())
2268       // ByVal argument is passed in as a pointer but it's now being
2269       // dereferenced. e.g.
2270       // define @foo(%struct.X* %A) {
2271       //   tail call @bar(%struct.X* byval %A)
2272       // }
2273       return false;
2274     SDValue Ptr = Ld->getBasePtr();
2275     FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr);
2276     if (!FINode)
2277       return false;
2278     FI = FINode->getIndex();
2279   } else
2280     return false;
2281
2282   assert(FI != INT_MAX);
2283   if (!MFI->isFixedObjectIndex(FI))
2284     return false;
2285   return Offset == MFI->getObjectOffset(FI) && Bytes == MFI->getObjectSize(FI);
2286 }
2287
2288 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
2289 /// for tail call optimization. Targets which want to do tail call
2290 /// optimization should implement this function.
2291 bool
2292 X86TargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
2293                                                      CallingConv::ID CalleeCC,
2294                                                      bool isVarArg,
2295                                                      bool isCalleeStructRet,
2296                                                      bool isCallerStructRet,
2297                                     const SmallVectorImpl<ISD::OutputArg> &Outs,
2298                                     const SmallVectorImpl<ISD::InputArg> &Ins,
2299                                                      SelectionDAG& DAG) const {
2300   if (!IsTailCallConvention(CalleeCC) &&
2301       CalleeCC != CallingConv::C)
2302     return false;
2303
2304   // If -tailcallopt is specified, make fastcc functions tail-callable.
2305   const MachineFunction &MF = DAG.getMachineFunction();
2306   const Function *CallerF = DAG.getMachineFunction().getFunction();
2307   CallingConv::ID CallerCC = CallerF->getCallingConv();
2308   bool CCMatch = CallerCC == CalleeCC;
2309
2310   if (GuaranteedTailCallOpt) {
2311     if (IsTailCallConvention(CalleeCC) && CCMatch)
2312       return true;
2313     return false;
2314   }
2315
2316   // Look for obvious safe cases to perform tail call optimization that does not
2317   // requite ABI changes. This is what gcc calls sibcall.
2318
2319   // Can't do sibcall if stack needs to be dynamically re-aligned. PEI needs to
2320   // emit a special epilogue.
2321   if (RegInfo->needsStackRealignment(MF))
2322     return false;
2323
2324   // Do not sibcall optimize vararg calls unless the call site is not passing any
2325   // arguments.
2326   if (isVarArg && !Outs.empty())
2327     return false;
2328
2329   // Also avoid sibcall optimization if either caller or callee uses struct
2330   // return semantics.
2331   if (isCalleeStructRet || isCallerStructRet)
2332     return false;
2333
2334   // If the call result is in ST0 / ST1, it needs to be popped off the x87 stack.
2335   // Therefore if it's not used by the call it is not safe to optimize this into
2336   // a sibcall.
2337   bool Unused = false;
2338   for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
2339     if (!Ins[i].Used) {
2340       Unused = true;
2341       break;
2342     }
2343   }
2344   if (Unused) {
2345     SmallVector<CCValAssign, 16> RVLocs;
2346     CCState CCInfo(CalleeCC, false, getTargetMachine(),
2347                    RVLocs, *DAG.getContext());
2348     CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
2349     for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
2350       CCValAssign &VA = RVLocs[i];
2351       if (VA.getLocReg() == X86::ST0 || VA.getLocReg() == X86::ST1)
2352         return false;
2353     }
2354   }
2355
2356   // If the calling conventions do not match, then we'd better make sure the
2357   // results are returned in the same way as what the caller expects.
2358   if (!CCMatch) {
2359     SmallVector<CCValAssign, 16> RVLocs1;
2360     CCState CCInfo1(CalleeCC, false, getTargetMachine(),
2361                     RVLocs1, *DAG.getContext());
2362     CCInfo1.AnalyzeCallResult(Ins, RetCC_X86);
2363
2364     SmallVector<CCValAssign, 16> RVLocs2;
2365     CCState CCInfo2(CallerCC, false, getTargetMachine(),
2366                     RVLocs2, *DAG.getContext());
2367     CCInfo2.AnalyzeCallResult(Ins, RetCC_X86);
2368
2369     if (RVLocs1.size() != RVLocs2.size())
2370       return false;
2371     for (unsigned i = 0, e = RVLocs1.size(); i != e; ++i) {
2372       if (RVLocs1[i].isRegLoc() != RVLocs2[i].isRegLoc())
2373         return false;
2374       if (RVLocs1[i].getLocInfo() != RVLocs2[i].getLocInfo())
2375         return false;
2376       if (RVLocs1[i].isRegLoc()) {
2377         if (RVLocs1[i].getLocReg() != RVLocs2[i].getLocReg())
2378           return false;
2379       } else {
2380         if (RVLocs1[i].getLocMemOffset() != RVLocs2[i].getLocMemOffset())
2381           return false;
2382       }
2383     }
2384   }
2385
2386   // If the callee takes no arguments then go on to check the results of the
2387   // call.
2388   if (!Outs.empty()) {
2389     // Check if stack adjustment is needed. For now, do not do this if any
2390     // argument is passed on the stack.
2391     SmallVector<CCValAssign, 16> ArgLocs;
2392     CCState CCInfo(CalleeCC, isVarArg, getTargetMachine(),
2393                    ArgLocs, *DAG.getContext());
2394     CCInfo.AnalyzeCallOperands(Outs, CCAssignFnForNode(CalleeCC));
2395     if (CCInfo.getNextStackOffset()) {
2396       MachineFunction &MF = DAG.getMachineFunction();
2397       if (MF.getInfo<X86MachineFunctionInfo>()->getBytesToPopOnReturn())
2398         return false;
2399       if (Subtarget->isTargetWin64())
2400         // Win64 ABI has additional complications.
2401         return false;
2402
2403       // Check if the arguments are already laid out in the right way as
2404       // the caller's fixed stack objects.
2405       MachineFrameInfo *MFI = MF.getFrameInfo();
2406       const MachineRegisterInfo *MRI = &MF.getRegInfo();
2407       const X86InstrInfo *TII =
2408         ((X86TargetMachine&)getTargetMachine()).getInstrInfo();
2409       for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2410         CCValAssign &VA = ArgLocs[i];
2411         EVT RegVT = VA.getLocVT();
2412         SDValue Arg = Outs[i].Val;
2413         ISD::ArgFlagsTy Flags = Outs[i].Flags;
2414         if (VA.getLocInfo() == CCValAssign::Indirect)
2415           return false;
2416         if (!VA.isRegLoc()) {
2417           if (!MatchingStackOffset(Arg, VA.getLocMemOffset(), Flags,
2418                                    MFI, MRI, TII))
2419             return false;
2420         }
2421       }
2422     }
2423   }
2424
2425   return true;
2426 }
2427
2428 FastISel *
2429 X86TargetLowering::createFastISel(MachineFunction &mf,
2430                             DenseMap<const Value *, unsigned> &vm,
2431                             DenseMap<const BasicBlock*, MachineBasicBlock*> &bm,
2432                             DenseMap<const AllocaInst *, int> &am,
2433                             std::vector<std::pair<MachineInstr*, unsigned> > &pn
2434 #ifndef NDEBUG
2435                           , SmallSet<const Instruction *, 8> &cil
2436 #endif
2437                                   ) const {
2438   return X86::createFastISel(mf, vm, bm, am, pn
2439 #ifndef NDEBUG
2440                              , cil
2441 #endif
2442                              );
2443 }
2444
2445
2446 //===----------------------------------------------------------------------===//
2447 //                           Other Lowering Hooks
2448 //===----------------------------------------------------------------------===//
2449
2450
2451 SDValue X86TargetLowering::getReturnAddressFrameIndex(SelectionDAG &DAG) const {
2452   MachineFunction &MF = DAG.getMachineFunction();
2453   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
2454   int ReturnAddrIndex = FuncInfo->getRAIndex();
2455
2456   if (ReturnAddrIndex == 0) {
2457     // Set up a frame object for the return address.
2458     uint64_t SlotSize = TD->getPointerSize();
2459     ReturnAddrIndex = MF.getFrameInfo()->CreateFixedObject(SlotSize, -SlotSize,
2460                                                            false, false);
2461     FuncInfo->setRAIndex(ReturnAddrIndex);
2462   }
2463
2464   return DAG.getFrameIndex(ReturnAddrIndex, getPointerTy());
2465 }
2466
2467
2468 bool X86::isOffsetSuitableForCodeModel(int64_t Offset, CodeModel::Model M,
2469                                        bool hasSymbolicDisplacement) {
2470   // Offset should fit into 32 bit immediate field.
2471   if (!isInt<32>(Offset))
2472     return false;
2473
2474   // If we don't have a symbolic displacement - we don't have any extra
2475   // restrictions.
2476   if (!hasSymbolicDisplacement)
2477     return true;
2478
2479   // FIXME: Some tweaks might be needed for medium code model.
2480   if (M != CodeModel::Small && M != CodeModel::Kernel)
2481     return false;
2482
2483   // For small code model we assume that latest object is 16MB before end of 31
2484   // bits boundary. We may also accept pretty large negative constants knowing
2485   // that all objects are in the positive half of address space.
2486   if (M == CodeModel::Small && Offset < 16*1024*1024)
2487     return true;
2488
2489   // For kernel code model we know that all object resist in the negative half
2490   // of 32bits address space. We may not accept negative offsets, since they may
2491   // be just off and we may accept pretty large positive ones.
2492   if (M == CodeModel::Kernel && Offset > 0)
2493     return true;
2494
2495   return false;
2496 }
2497
2498 /// TranslateX86CC - do a one to one translation of a ISD::CondCode to the X86
2499 /// specific condition code, returning the condition code and the LHS/RHS of the
2500 /// comparison to make.
2501 static unsigned TranslateX86CC(ISD::CondCode SetCCOpcode, bool isFP,
2502                                SDValue &LHS, SDValue &RHS, SelectionDAG &DAG) {
2503   if (!isFP) {
2504     if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) {
2505       if (SetCCOpcode == ISD::SETGT && RHSC->isAllOnesValue()) {
2506         // X > -1   -> X == 0, jump !sign.
2507         RHS = DAG.getConstant(0, RHS.getValueType());
2508         return X86::COND_NS;
2509       } else if (SetCCOpcode == ISD::SETLT && RHSC->isNullValue()) {
2510         // X < 0   -> X == 0, jump on sign.
2511         return X86::COND_S;
2512       } else if (SetCCOpcode == ISD::SETLT && RHSC->getZExtValue() == 1) {
2513         // X < 1   -> X <= 0
2514         RHS = DAG.getConstant(0, RHS.getValueType());
2515         return X86::COND_LE;
2516       }
2517     }
2518
2519     switch (SetCCOpcode) {
2520     default: llvm_unreachable("Invalid integer condition!");
2521     case ISD::SETEQ:  return X86::COND_E;
2522     case ISD::SETGT:  return X86::COND_G;
2523     case ISD::SETGE:  return X86::COND_GE;
2524     case ISD::SETLT:  return X86::COND_L;
2525     case ISD::SETLE:  return X86::COND_LE;
2526     case ISD::SETNE:  return X86::COND_NE;
2527     case ISD::SETULT: return X86::COND_B;
2528     case ISD::SETUGT: return X86::COND_A;
2529     case ISD::SETULE: return X86::COND_BE;
2530     case ISD::SETUGE: return X86::COND_AE;
2531     }
2532   }
2533
2534   // First determine if it is required or is profitable to flip the operands.
2535
2536   // If LHS is a foldable load, but RHS is not, flip the condition.
2537   if ((ISD::isNON_EXTLoad(LHS.getNode()) && LHS.hasOneUse()) &&
2538       !(ISD::isNON_EXTLoad(RHS.getNode()) && RHS.hasOneUse())) {
2539     SetCCOpcode = getSetCCSwappedOperands(SetCCOpcode);
2540     std::swap(LHS, RHS);
2541   }
2542
2543   switch (SetCCOpcode) {
2544   default: break;
2545   case ISD::SETOLT:
2546   case ISD::SETOLE:
2547   case ISD::SETUGT:
2548   case ISD::SETUGE:
2549     std::swap(LHS, RHS);
2550     break;
2551   }
2552
2553   // On a floating point condition, the flags are set as follows:
2554   // ZF  PF  CF   op
2555   //  0 | 0 | 0 | X > Y
2556   //  0 | 0 | 1 | X < Y
2557   //  1 | 0 | 0 | X == Y
2558   //  1 | 1 | 1 | unordered
2559   switch (SetCCOpcode) {
2560   default: llvm_unreachable("Condcode should be pre-legalized away");
2561   case ISD::SETUEQ:
2562   case ISD::SETEQ:   return X86::COND_E;
2563   case ISD::SETOLT:              // flipped
2564   case ISD::SETOGT:
2565   case ISD::SETGT:   return X86::COND_A;
2566   case ISD::SETOLE:              // flipped
2567   case ISD::SETOGE:
2568   case ISD::SETGE:   return X86::COND_AE;
2569   case ISD::SETUGT:              // flipped
2570   case ISD::SETULT:
2571   case ISD::SETLT:   return X86::COND_B;
2572   case ISD::SETUGE:              // flipped
2573   case ISD::SETULE:
2574   case ISD::SETLE:   return X86::COND_BE;
2575   case ISD::SETONE:
2576   case ISD::SETNE:   return X86::COND_NE;
2577   case ISD::SETUO:   return X86::COND_P;
2578   case ISD::SETO:    return X86::COND_NP;
2579   case ISD::SETOEQ:
2580   case ISD::SETUNE:  return X86::COND_INVALID;
2581   }
2582 }
2583
2584 /// hasFPCMov - is there a floating point cmov for the specific X86 condition
2585 /// code. Current x86 isa includes the following FP cmov instructions:
2586 /// fcmovb, fcomvbe, fcomve, fcmovu, fcmovae, fcmova, fcmovne, fcmovnu.
2587 static bool hasFPCMov(unsigned X86CC) {
2588   switch (X86CC) {
2589   default:
2590     return false;
2591   case X86::COND_B:
2592   case X86::COND_BE:
2593   case X86::COND_E:
2594   case X86::COND_P:
2595   case X86::COND_A:
2596   case X86::COND_AE:
2597   case X86::COND_NE:
2598   case X86::COND_NP:
2599     return true;
2600   }
2601 }
2602
2603 /// isFPImmLegal - Returns true if the target can instruction select the
2604 /// specified FP immediate natively. If false, the legalizer will
2605 /// materialize the FP immediate as a load from a constant pool.
2606 bool X86TargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
2607   for (unsigned i = 0, e = LegalFPImmediates.size(); i != e; ++i) {
2608     if (Imm.bitwiseIsEqual(LegalFPImmediates[i]))
2609       return true;
2610   }
2611   return false;
2612 }
2613
2614 /// isUndefOrInRange - Return true if Val is undef or if its value falls within
2615 /// the specified range (L, H].
2616 static bool isUndefOrInRange(int Val, int Low, int Hi) {
2617   return (Val < 0) || (Val >= Low && Val < Hi);
2618 }
2619
2620 /// isUndefOrEqual - Val is either less than zero (undef) or equal to the
2621 /// specified value.
2622 static bool isUndefOrEqual(int Val, int CmpVal) {
2623   if (Val < 0 || Val == CmpVal)
2624     return true;
2625   return false;
2626 }
2627
2628 /// isPSHUFDMask - Return true if the node specifies a shuffle of elements that
2629 /// is suitable for input to PSHUFD or PSHUFW.  That is, it doesn't reference
2630 /// the second operand.
2631 static bool isPSHUFDMask(const SmallVectorImpl<int> &Mask, EVT VT) {
2632   if (VT == MVT::v4f32 || VT == MVT::v4i32 || VT == MVT::v4i16)
2633     return (Mask[0] < 4 && Mask[1] < 4 && Mask[2] < 4 && Mask[3] < 4);
2634   if (VT == MVT::v2f64 || VT == MVT::v2i64)
2635     return (Mask[0] < 2 && Mask[1] < 2);
2636   return false;
2637 }
2638
2639 bool X86::isPSHUFDMask(ShuffleVectorSDNode *N) {
2640   SmallVector<int, 8> M;
2641   N->getMask(M);
2642   return ::isPSHUFDMask(M, N->getValueType(0));
2643 }
2644
2645 /// isPSHUFHWMask - Return true if the node specifies a shuffle of elements that
2646 /// is suitable for input to PSHUFHW.
2647 static bool isPSHUFHWMask(const SmallVectorImpl<int> &Mask, EVT VT) {
2648   if (VT != MVT::v8i16)
2649     return false;
2650
2651   // Lower quadword copied in order or undef.
2652   for (int i = 0; i != 4; ++i)
2653     if (Mask[i] >= 0 && Mask[i] != i)
2654       return false;
2655
2656   // Upper quadword shuffled.
2657   for (int i = 4; i != 8; ++i)
2658     if (Mask[i] >= 0 && (Mask[i] < 4 || Mask[i] > 7))
2659       return false;
2660
2661   return true;
2662 }
2663
2664 bool X86::isPSHUFHWMask(ShuffleVectorSDNode *N) {
2665   SmallVector<int, 8> M;
2666   N->getMask(M);
2667   return ::isPSHUFHWMask(M, N->getValueType(0));
2668 }
2669
2670 /// isPSHUFLWMask - Return true if the node specifies a shuffle of elements that
2671 /// is suitable for input to PSHUFLW.
2672 static bool isPSHUFLWMask(const SmallVectorImpl<int> &Mask, EVT VT) {
2673   if (VT != MVT::v8i16)
2674     return false;
2675
2676   // Upper quadword copied in order.
2677   for (int i = 4; i != 8; ++i)
2678     if (Mask[i] >= 0 && Mask[i] != i)
2679       return false;
2680
2681   // Lower quadword shuffled.
2682   for (int i = 0; i != 4; ++i)
2683     if (Mask[i] >= 4)
2684       return false;
2685
2686   return true;
2687 }
2688
2689 bool X86::isPSHUFLWMask(ShuffleVectorSDNode *N) {
2690   SmallVector<int, 8> M;
2691   N->getMask(M);
2692   return ::isPSHUFLWMask(M, N->getValueType(0));
2693 }
2694
2695 /// isPALIGNRMask - Return true if the node specifies a shuffle of elements that
2696 /// is suitable for input to PALIGNR.
2697 static bool isPALIGNRMask(const SmallVectorImpl<int> &Mask, EVT VT,
2698                           bool hasSSSE3) {
2699   int i, e = VT.getVectorNumElements();
2700   
2701   // Do not handle v2i64 / v2f64 shuffles with palignr.
2702   if (e < 4 || !hasSSSE3)
2703     return false;
2704   
2705   for (i = 0; i != e; ++i)
2706     if (Mask[i] >= 0)
2707       break;
2708   
2709   // All undef, not a palignr.
2710   if (i == e)
2711     return false;
2712
2713   // Determine if it's ok to perform a palignr with only the LHS, since we
2714   // don't have access to the actual shuffle elements to see if RHS is undef.
2715   bool Unary = Mask[i] < (int)e;
2716   bool NeedsUnary = false;
2717
2718   int s = Mask[i] - i;
2719   
2720   // Check the rest of the elements to see if they are consecutive.
2721   for (++i; i != e; ++i) {
2722     int m = Mask[i];
2723     if (m < 0) 
2724       continue;
2725     
2726     Unary = Unary && (m < (int)e);
2727     NeedsUnary = NeedsUnary || (m < s);
2728
2729     if (NeedsUnary && !Unary)
2730       return false;
2731     if (Unary && m != ((s+i) & (e-1)))
2732       return false;
2733     if (!Unary && m != (s+i))
2734       return false;
2735   }
2736   return true;
2737 }
2738
2739 bool X86::isPALIGNRMask(ShuffleVectorSDNode *N) {
2740   SmallVector<int, 8> M;
2741   N->getMask(M);
2742   return ::isPALIGNRMask(M, N->getValueType(0), true);
2743 }
2744
2745 /// isSHUFPMask - Return true if the specified VECTOR_SHUFFLE operand
2746 /// specifies a shuffle of elements that is suitable for input to SHUFP*.
2747 static bool isSHUFPMask(const SmallVectorImpl<int> &Mask, EVT VT) {
2748   int NumElems = VT.getVectorNumElements();
2749   if (NumElems != 2 && NumElems != 4)
2750     return false;
2751
2752   int Half = NumElems / 2;
2753   for (int i = 0; i < Half; ++i)
2754     if (!isUndefOrInRange(Mask[i], 0, NumElems))
2755       return false;
2756   for (int i = Half; i < NumElems; ++i)
2757     if (!isUndefOrInRange(Mask[i], NumElems, NumElems*2))
2758       return false;
2759
2760   return true;
2761 }
2762
2763 bool X86::isSHUFPMask(ShuffleVectorSDNode *N) {
2764   SmallVector<int, 8> M;
2765   N->getMask(M);
2766   return ::isSHUFPMask(M, N->getValueType(0));
2767 }
2768
2769 /// isCommutedSHUFP - Returns true if the shuffle mask is exactly
2770 /// the reverse of what x86 shuffles want. x86 shuffles requires the lower
2771 /// half elements to come from vector 1 (which would equal the dest.) and
2772 /// the upper half to come from vector 2.
2773 static bool isCommutedSHUFPMask(const SmallVectorImpl<int> &Mask, EVT VT) {
2774   int NumElems = VT.getVectorNumElements();
2775
2776   if (NumElems != 2 && NumElems != 4)
2777     return false;
2778
2779   int Half = NumElems / 2;
2780   for (int i = 0; i < Half; ++i)
2781     if (!isUndefOrInRange(Mask[i], NumElems, NumElems*2))
2782       return false;
2783   for (int i = Half; i < NumElems; ++i)
2784     if (!isUndefOrInRange(Mask[i], 0, NumElems))
2785       return false;
2786   return true;
2787 }
2788
2789 static bool isCommutedSHUFP(ShuffleVectorSDNode *N) {
2790   SmallVector<int, 8> M;
2791   N->getMask(M);
2792   return isCommutedSHUFPMask(M, N->getValueType(0));
2793 }
2794
2795 /// isMOVHLPSMask - Return true if the specified VECTOR_SHUFFLE operand
2796 /// specifies a shuffle of elements that is suitable for input to MOVHLPS.
2797 bool X86::isMOVHLPSMask(ShuffleVectorSDNode *N) {
2798   if (N->getValueType(0).getVectorNumElements() != 4)
2799     return false;
2800
2801   // Expect bit0 == 6, bit1 == 7, bit2 == 2, bit3 == 3
2802   return isUndefOrEqual(N->getMaskElt(0), 6) &&
2803          isUndefOrEqual(N->getMaskElt(1), 7) &&
2804          isUndefOrEqual(N->getMaskElt(2), 2) &&
2805          isUndefOrEqual(N->getMaskElt(3), 3);
2806 }
2807
2808 /// isMOVHLPS_v_undef_Mask - Special case of isMOVHLPSMask for canonical form
2809 /// of vector_shuffle v, v, <2, 3, 2, 3>, i.e. vector_shuffle v, undef,
2810 /// <2, 3, 2, 3>
2811 bool X86::isMOVHLPS_v_undef_Mask(ShuffleVectorSDNode *N) {
2812   unsigned NumElems = N->getValueType(0).getVectorNumElements();
2813   
2814   if (NumElems != 4)
2815     return false;
2816   
2817   return isUndefOrEqual(N->getMaskElt(0), 2) &&
2818   isUndefOrEqual(N->getMaskElt(1), 3) &&
2819   isUndefOrEqual(N->getMaskElt(2), 2) &&
2820   isUndefOrEqual(N->getMaskElt(3), 3);
2821 }
2822
2823 /// isMOVLPMask - Return true if the specified VECTOR_SHUFFLE operand
2824 /// specifies a shuffle of elements that is suitable for input to MOVLP{S|D}.
2825 bool X86::isMOVLPMask(ShuffleVectorSDNode *N) {
2826   unsigned NumElems = N->getValueType(0).getVectorNumElements();
2827
2828   if (NumElems != 2 && NumElems != 4)
2829     return false;
2830
2831   for (unsigned i = 0; i < NumElems/2; ++i)
2832     if (!isUndefOrEqual(N->getMaskElt(i), i + NumElems))
2833       return false;
2834
2835   for (unsigned i = NumElems/2; i < NumElems; ++i)
2836     if (!isUndefOrEqual(N->getMaskElt(i), i))
2837       return false;
2838
2839   return true;
2840 }
2841
2842 /// isMOVLHPSMask - Return true if the specified VECTOR_SHUFFLE operand
2843 /// specifies a shuffle of elements that is suitable for input to MOVLHPS.
2844 bool X86::isMOVLHPSMask(ShuffleVectorSDNode *N) {
2845   unsigned NumElems = N->getValueType(0).getVectorNumElements();
2846
2847   if (NumElems != 2 && NumElems != 4)
2848     return false;
2849
2850   for (unsigned i = 0; i < NumElems/2; ++i)
2851     if (!isUndefOrEqual(N->getMaskElt(i), i))
2852       return false;
2853
2854   for (unsigned i = 0; i < NumElems/2; ++i)
2855     if (!isUndefOrEqual(N->getMaskElt(i + NumElems/2), i + NumElems))
2856       return false;
2857
2858   return true;
2859 }
2860
2861 /// isUNPCKLMask - Return true if the specified VECTOR_SHUFFLE operand
2862 /// specifies a shuffle of elements that is suitable for input to UNPCKL.
2863 static bool isUNPCKLMask(const SmallVectorImpl<int> &Mask, EVT VT,
2864                          bool V2IsSplat = false) {
2865   int NumElts = VT.getVectorNumElements();
2866   if (NumElts != 2 && NumElts != 4 && NumElts != 8 && NumElts != 16)
2867     return false;
2868
2869   for (int i = 0, j = 0; i != NumElts; i += 2, ++j) {
2870     int BitI  = Mask[i];
2871     int BitI1 = Mask[i+1];
2872     if (!isUndefOrEqual(BitI, j))
2873       return false;
2874     if (V2IsSplat) {
2875       if (!isUndefOrEqual(BitI1, NumElts))
2876         return false;
2877     } else {
2878       if (!isUndefOrEqual(BitI1, j + NumElts))
2879         return false;
2880     }
2881   }
2882   return true;
2883 }
2884
2885 bool X86::isUNPCKLMask(ShuffleVectorSDNode *N, bool V2IsSplat) {
2886   SmallVector<int, 8> M;
2887   N->getMask(M);
2888   return ::isUNPCKLMask(M, N->getValueType(0), V2IsSplat);
2889 }
2890
2891 /// isUNPCKHMask - Return true if the specified VECTOR_SHUFFLE operand
2892 /// specifies a shuffle of elements that is suitable for input to UNPCKH.
2893 static bool isUNPCKHMask(const SmallVectorImpl<int> &Mask, EVT VT,
2894                          bool V2IsSplat = false) {
2895   int NumElts = VT.getVectorNumElements();
2896   if (NumElts != 2 && NumElts != 4 && NumElts != 8 && NumElts != 16)
2897     return false;
2898
2899   for (int i = 0, j = 0; i != NumElts; i += 2, ++j) {
2900     int BitI  = Mask[i];
2901     int BitI1 = Mask[i+1];
2902     if (!isUndefOrEqual(BitI, j + NumElts/2))
2903       return false;
2904     if (V2IsSplat) {
2905       if (isUndefOrEqual(BitI1, NumElts))
2906         return false;
2907     } else {
2908       if (!isUndefOrEqual(BitI1, j + NumElts/2 + NumElts))
2909         return false;
2910     }
2911   }
2912   return true;
2913 }
2914
2915 bool X86::isUNPCKHMask(ShuffleVectorSDNode *N, bool V2IsSplat) {
2916   SmallVector<int, 8> M;
2917   N->getMask(M);
2918   return ::isUNPCKHMask(M, N->getValueType(0), V2IsSplat);
2919 }
2920
2921 /// isUNPCKL_v_undef_Mask - Special case of isUNPCKLMask for canonical form
2922 /// of vector_shuffle v, v, <0, 4, 1, 5>, i.e. vector_shuffle v, undef,
2923 /// <0, 0, 1, 1>
2924 static bool isUNPCKL_v_undef_Mask(const SmallVectorImpl<int> &Mask, EVT VT) {
2925   int NumElems = VT.getVectorNumElements();
2926   if (NumElems != 2 && NumElems != 4 && NumElems != 8 && NumElems != 16)
2927     return false;
2928
2929   for (int i = 0, j = 0; i != NumElems; i += 2, ++j) {
2930     int BitI  = Mask[i];
2931     int BitI1 = Mask[i+1];
2932     if (!isUndefOrEqual(BitI, j))
2933       return false;
2934     if (!isUndefOrEqual(BitI1, j))
2935       return false;
2936   }
2937   return true;
2938 }
2939
2940 bool X86::isUNPCKL_v_undef_Mask(ShuffleVectorSDNode *N) {
2941   SmallVector<int, 8> M;
2942   N->getMask(M);
2943   return ::isUNPCKL_v_undef_Mask(M, N->getValueType(0));
2944 }
2945
2946 /// isUNPCKH_v_undef_Mask - Special case of isUNPCKHMask for canonical form
2947 /// of vector_shuffle v, v, <2, 6, 3, 7>, i.e. vector_shuffle v, undef,
2948 /// <2, 2, 3, 3>
2949 static bool isUNPCKH_v_undef_Mask(const SmallVectorImpl<int> &Mask, EVT VT) {
2950   int NumElems = VT.getVectorNumElements();
2951   if (NumElems != 2 && NumElems != 4 && NumElems != 8 && NumElems != 16)
2952     return false;
2953
2954   for (int i = 0, j = NumElems / 2; i != NumElems; i += 2, ++j) {
2955     int BitI  = Mask[i];
2956     int BitI1 = Mask[i+1];
2957     if (!isUndefOrEqual(BitI, j))
2958       return false;
2959     if (!isUndefOrEqual(BitI1, j))
2960       return false;
2961   }
2962   return true;
2963 }
2964
2965 bool X86::isUNPCKH_v_undef_Mask(ShuffleVectorSDNode *N) {
2966   SmallVector<int, 8> M;
2967   N->getMask(M);
2968   return ::isUNPCKH_v_undef_Mask(M, N->getValueType(0));
2969 }
2970
2971 /// isMOVLMask - Return true if the specified VECTOR_SHUFFLE operand
2972 /// specifies a shuffle of elements that is suitable for input to MOVSS,
2973 /// MOVSD, and MOVD, i.e. setting the lowest element.
2974 static bool isMOVLMask(const SmallVectorImpl<int> &Mask, EVT VT) {
2975   if (VT.getVectorElementType().getSizeInBits() < 32)
2976     return false;
2977
2978   int NumElts = VT.getVectorNumElements();
2979
2980   if (!isUndefOrEqual(Mask[0], NumElts))
2981     return false;
2982
2983   for (int i = 1; i < NumElts; ++i)
2984     if (!isUndefOrEqual(Mask[i], i))
2985       return false;
2986
2987   return true;
2988 }
2989
2990 bool X86::isMOVLMask(ShuffleVectorSDNode *N) {
2991   SmallVector<int, 8> M;
2992   N->getMask(M);
2993   return ::isMOVLMask(M, N->getValueType(0));
2994 }
2995
2996 /// isCommutedMOVL - Returns true if the shuffle mask is except the reverse
2997 /// of what x86 movss want. X86 movs requires the lowest  element to be lowest
2998 /// element of vector 2 and the other elements to come from vector 1 in order.
2999 static bool isCommutedMOVLMask(const SmallVectorImpl<int> &Mask, EVT VT,
3000                                bool V2IsSplat = false, bool V2IsUndef = false) {
3001   int NumOps = VT.getVectorNumElements();
3002   if (NumOps != 2 && NumOps != 4 && NumOps != 8 && NumOps != 16)
3003     return false;
3004
3005   if (!isUndefOrEqual(Mask[0], 0))
3006     return false;
3007
3008   for (int i = 1; i < NumOps; ++i)
3009     if (!(isUndefOrEqual(Mask[i], i+NumOps) ||
3010           (V2IsUndef && isUndefOrInRange(Mask[i], NumOps, NumOps*2)) ||
3011           (V2IsSplat && isUndefOrEqual(Mask[i], NumOps))))
3012       return false;
3013
3014   return true;
3015 }
3016
3017 static bool isCommutedMOVL(ShuffleVectorSDNode *N, bool V2IsSplat = false,
3018                            bool V2IsUndef = false) {
3019   SmallVector<int, 8> M;
3020   N->getMask(M);
3021   return isCommutedMOVLMask(M, N->getValueType(0), V2IsSplat, V2IsUndef);
3022 }
3023
3024 /// isMOVSHDUPMask - Return true if the specified VECTOR_SHUFFLE operand
3025 /// specifies a shuffle of elements that is suitable for input to MOVSHDUP.
3026 bool X86::isMOVSHDUPMask(ShuffleVectorSDNode *N) {
3027   if (N->getValueType(0).getVectorNumElements() != 4)
3028     return false;
3029
3030   // Expect 1, 1, 3, 3
3031   for (unsigned i = 0; i < 2; ++i) {
3032     int Elt = N->getMaskElt(i);
3033     if (Elt >= 0 && Elt != 1)
3034       return false;
3035   }
3036
3037   bool HasHi = false;
3038   for (unsigned i = 2; i < 4; ++i) {
3039     int Elt = N->getMaskElt(i);
3040     if (Elt >= 0 && Elt != 3)
3041       return false;
3042     if (Elt == 3)
3043       HasHi = true;
3044   }
3045   // Don't use movshdup if it can be done with a shufps.
3046   // FIXME: verify that matching u, u, 3, 3 is what we want.
3047   return HasHi;
3048 }
3049
3050 /// isMOVSLDUPMask - Return true if the specified VECTOR_SHUFFLE operand
3051 /// specifies a shuffle of elements that is suitable for input to MOVSLDUP.
3052 bool X86::isMOVSLDUPMask(ShuffleVectorSDNode *N) {
3053   if (N->getValueType(0).getVectorNumElements() != 4)
3054     return false;
3055
3056   // Expect 0, 0, 2, 2
3057   for (unsigned i = 0; i < 2; ++i)
3058     if (N->getMaskElt(i) > 0)
3059       return false;
3060
3061   bool HasHi = false;
3062   for (unsigned i = 2; i < 4; ++i) {
3063     int Elt = N->getMaskElt(i);
3064     if (Elt >= 0 && Elt != 2)
3065       return false;
3066     if (Elt == 2)
3067       HasHi = true;
3068   }
3069   // Don't use movsldup if it can be done with a shufps.
3070   return HasHi;
3071 }
3072
3073 /// isMOVDDUPMask - Return true if the specified VECTOR_SHUFFLE operand
3074 /// specifies a shuffle of elements that is suitable for input to MOVDDUP.
3075 bool X86::isMOVDDUPMask(ShuffleVectorSDNode *N) {
3076   int e = N->getValueType(0).getVectorNumElements() / 2;
3077
3078   for (int i = 0; i < e; ++i)
3079     if (!isUndefOrEqual(N->getMaskElt(i), i))
3080       return false;
3081   for (int i = 0; i < e; ++i)
3082     if (!isUndefOrEqual(N->getMaskElt(e+i), i))
3083       return false;
3084   return true;
3085 }
3086
3087 /// getShuffleSHUFImmediate - Return the appropriate immediate to shuffle
3088 /// the specified VECTOR_SHUFFLE mask with PSHUF* and SHUFP* instructions.
3089 unsigned X86::getShuffleSHUFImmediate(SDNode *N) {
3090   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
3091   int NumOperands = SVOp->getValueType(0).getVectorNumElements();
3092
3093   unsigned Shift = (NumOperands == 4) ? 2 : 1;
3094   unsigned Mask = 0;
3095   for (int i = 0; i < NumOperands; ++i) {
3096     int Val = SVOp->getMaskElt(NumOperands-i-1);
3097     if (Val < 0) Val = 0;
3098     if (Val >= NumOperands) Val -= NumOperands;
3099     Mask |= Val;
3100     if (i != NumOperands - 1)
3101       Mask <<= Shift;
3102   }
3103   return Mask;
3104 }
3105
3106 /// getShufflePSHUFHWImmediate - Return the appropriate immediate to shuffle
3107 /// the specified VECTOR_SHUFFLE mask with the PSHUFHW instruction.
3108 unsigned X86::getShufflePSHUFHWImmediate(SDNode *N) {
3109   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
3110   unsigned Mask = 0;
3111   // 8 nodes, but we only care about the last 4.
3112   for (unsigned i = 7; i >= 4; --i) {
3113     int Val = SVOp->getMaskElt(i);
3114     if (Val >= 0)
3115       Mask |= (Val - 4);
3116     if (i != 4)
3117       Mask <<= 2;
3118   }
3119   return Mask;
3120 }
3121
3122 /// getShufflePSHUFLWImmediate - Return the appropriate immediate to shuffle
3123 /// the specified VECTOR_SHUFFLE mask with the PSHUFLW instruction.
3124 unsigned X86::getShufflePSHUFLWImmediate(SDNode *N) {
3125   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
3126   unsigned Mask = 0;
3127   // 8 nodes, but we only care about the first 4.
3128   for (int i = 3; i >= 0; --i) {
3129     int Val = SVOp->getMaskElt(i);
3130     if (Val >= 0)
3131       Mask |= Val;
3132     if (i != 0)
3133       Mask <<= 2;
3134   }
3135   return Mask;
3136 }
3137
3138 /// getShufflePALIGNRImmediate - Return the appropriate immediate to shuffle
3139 /// the specified VECTOR_SHUFFLE mask with the PALIGNR instruction.
3140 unsigned X86::getShufflePALIGNRImmediate(SDNode *N) {
3141   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
3142   EVT VVT = N->getValueType(0);
3143   unsigned EltSize = VVT.getVectorElementType().getSizeInBits() >> 3;
3144   int Val = 0;
3145
3146   unsigned i, e;
3147   for (i = 0, e = VVT.getVectorNumElements(); i != e; ++i) {
3148     Val = SVOp->getMaskElt(i);
3149     if (Val >= 0)
3150       break;
3151   }
3152   return (Val - i) * EltSize;
3153 }
3154
3155 /// isZeroNode - Returns true if Elt is a constant zero or a floating point
3156 /// constant +0.0.
3157 bool X86::isZeroNode(SDValue Elt) {
3158   return ((isa<ConstantSDNode>(Elt) &&
3159            cast<ConstantSDNode>(Elt)->getZExtValue() == 0) ||
3160           (isa<ConstantFPSDNode>(Elt) &&
3161            cast<ConstantFPSDNode>(Elt)->getValueAPF().isPosZero()));
3162 }
3163
3164 /// CommuteVectorShuffle - Swap vector_shuffle operands as well as values in
3165 /// their permute mask.
3166 static SDValue CommuteVectorShuffle(ShuffleVectorSDNode *SVOp,
3167                                     SelectionDAG &DAG) {
3168   EVT VT = SVOp->getValueType(0);
3169   unsigned NumElems = VT.getVectorNumElements();
3170   SmallVector<int, 8> MaskVec;
3171
3172   for (unsigned i = 0; i != NumElems; ++i) {
3173     int idx = SVOp->getMaskElt(i);
3174     if (idx < 0)
3175       MaskVec.push_back(idx);
3176     else if (idx < (int)NumElems)
3177       MaskVec.push_back(idx + NumElems);
3178     else
3179       MaskVec.push_back(idx - NumElems);
3180   }
3181   return DAG.getVectorShuffle(VT, SVOp->getDebugLoc(), SVOp->getOperand(1),
3182                               SVOp->getOperand(0), &MaskVec[0]);
3183 }
3184
3185 /// CommuteVectorShuffleMask - Change values in a shuffle permute mask assuming
3186 /// the two vector operands have swapped position.
3187 static void CommuteVectorShuffleMask(SmallVectorImpl<int> &Mask, EVT VT) {
3188   unsigned NumElems = VT.getVectorNumElements();
3189   for (unsigned i = 0; i != NumElems; ++i) {
3190     int idx = Mask[i];
3191     if (idx < 0)
3192       continue;
3193     else if (idx < (int)NumElems)
3194       Mask[i] = idx + NumElems;
3195     else
3196       Mask[i] = idx - NumElems;
3197   }
3198 }
3199
3200 /// ShouldXformToMOVHLPS - Return true if the node should be transformed to
3201 /// match movhlps. The lower half elements should come from upper half of
3202 /// V1 (and in order), and the upper half elements should come from the upper
3203 /// half of V2 (and in order).
3204 static bool ShouldXformToMOVHLPS(ShuffleVectorSDNode *Op) {
3205   if (Op->getValueType(0).getVectorNumElements() != 4)
3206     return false;
3207   for (unsigned i = 0, e = 2; i != e; ++i)
3208     if (!isUndefOrEqual(Op->getMaskElt(i), i+2))
3209       return false;
3210   for (unsigned i = 2; i != 4; ++i)
3211     if (!isUndefOrEqual(Op->getMaskElt(i), i+4))
3212       return false;
3213   return true;
3214 }
3215
3216 /// isScalarLoadToVector - Returns true if the node is a scalar load that
3217 /// is promoted to a vector. It also returns the LoadSDNode by reference if
3218 /// required.
3219 static bool isScalarLoadToVector(SDNode *N, LoadSDNode **LD = NULL) {
3220   if (N->getOpcode() != ISD::SCALAR_TO_VECTOR)
3221     return false;
3222   N = N->getOperand(0).getNode();
3223   if (!ISD::isNON_EXTLoad(N))
3224     return false;
3225   if (LD)
3226     *LD = cast<LoadSDNode>(N);
3227   return true;
3228 }
3229
3230 /// ShouldXformToMOVLP{S|D} - Return true if the node should be transformed to
3231 /// match movlp{s|d}. The lower half elements should come from lower half of
3232 /// V1 (and in order), and the upper half elements should come from the upper
3233 /// half of V2 (and in order). And since V1 will become the source of the
3234 /// MOVLP, it must be either a vector load or a scalar load to vector.
3235 static bool ShouldXformToMOVLP(SDNode *V1, SDNode *V2,
3236                                ShuffleVectorSDNode *Op) {
3237   if (!ISD::isNON_EXTLoad(V1) && !isScalarLoadToVector(V1))
3238     return false;
3239   // Is V2 is a vector load, don't do this transformation. We will try to use
3240   // load folding shufps op.
3241   if (ISD::isNON_EXTLoad(V2))
3242     return false;
3243
3244   unsigned NumElems = Op->getValueType(0).getVectorNumElements();
3245
3246   if (NumElems != 2 && NumElems != 4)
3247     return false;
3248   for (unsigned i = 0, e = NumElems/2; i != e; ++i)
3249     if (!isUndefOrEqual(Op->getMaskElt(i), i))
3250       return false;
3251   for (unsigned i = NumElems/2; i != NumElems; ++i)
3252     if (!isUndefOrEqual(Op->getMaskElt(i), i+NumElems))
3253       return false;
3254   return true;
3255 }
3256
3257 /// isSplatVector - Returns true if N is a BUILD_VECTOR node whose elements are
3258 /// all the same.
3259 static bool isSplatVector(SDNode *N) {
3260   if (N->getOpcode() != ISD::BUILD_VECTOR)
3261     return false;
3262
3263   SDValue SplatValue = N->getOperand(0);
3264   for (unsigned i = 1, e = N->getNumOperands(); i != e; ++i)
3265     if (N->getOperand(i) != SplatValue)
3266       return false;
3267   return true;
3268 }
3269
3270 /// isZeroShuffle - Returns true if N is a VECTOR_SHUFFLE that can be resolved
3271 /// to an zero vector.
3272 /// FIXME: move to dag combiner / method on ShuffleVectorSDNode
3273 static bool isZeroShuffle(ShuffleVectorSDNode *N) {
3274   SDValue V1 = N->getOperand(0);
3275   SDValue V2 = N->getOperand(1);
3276   unsigned NumElems = N->getValueType(0).getVectorNumElements();
3277   for (unsigned i = 0; i != NumElems; ++i) {
3278     int Idx = N->getMaskElt(i);
3279     if (Idx >= (int)NumElems) {
3280       unsigned Opc = V2.getOpcode();
3281       if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V2.getNode()))
3282         continue;
3283       if (Opc != ISD::BUILD_VECTOR ||
3284           !X86::isZeroNode(V2.getOperand(Idx-NumElems)))
3285         return false;
3286     } else if (Idx >= 0) {
3287       unsigned Opc = V1.getOpcode();
3288       if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V1.getNode()))
3289         continue;
3290       if (Opc != ISD::BUILD_VECTOR ||
3291           !X86::isZeroNode(V1.getOperand(Idx)))
3292         return false;
3293     }
3294   }
3295   return true;
3296 }
3297
3298 /// getZeroVector - Returns a vector of specified type with all zero elements.
3299 ///
3300 static SDValue getZeroVector(EVT VT, bool HasSSE2, SelectionDAG &DAG,
3301                              DebugLoc dl) {
3302   assert(VT.isVector() && "Expected a vector type");
3303
3304   // Always build zero vectors as <4 x i32> or <2 x i32> bitcasted to their dest
3305   // type.  This ensures they get CSE'd.
3306   SDValue Vec;
3307   if (VT.getSizeInBits() == 64) { // MMX
3308     SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
3309     Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v2i32, Cst, Cst);
3310   } else if (HasSSE2) {  // SSE2
3311     SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
3312     Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
3313   } else { // SSE1
3314     SDValue Cst = DAG.getTargetConstantFP(+0.0, MVT::f32);
3315     Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4f32, Cst, Cst, Cst, Cst);
3316   }
3317   return DAG.getNode(ISD::BIT_CONVERT, dl, VT, Vec);
3318 }
3319
3320 /// getOnesVector - Returns a vector of specified type with all bits set.
3321 ///
3322 static SDValue getOnesVector(EVT VT, SelectionDAG &DAG, DebugLoc dl) {
3323   assert(VT.isVector() && "Expected a vector type");
3324
3325   // Always build ones vectors as <4 x i32> or <2 x i32> bitcasted to their dest
3326   // type.  This ensures they get CSE'd.
3327   SDValue Cst = DAG.getTargetConstant(~0U, MVT::i32);
3328   SDValue Vec;
3329   if (VT.getSizeInBits() == 64)  // MMX
3330     Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v2i32, Cst, Cst);
3331   else                                              // SSE
3332     Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
3333   return DAG.getNode(ISD::BIT_CONVERT, dl, VT, Vec);
3334 }
3335
3336
3337 /// NormalizeMask - V2 is a splat, modify the mask (if needed) so all elements
3338 /// that point to V2 points to its first element.
3339 static SDValue NormalizeMask(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
3340   EVT VT = SVOp->getValueType(0);
3341   unsigned NumElems = VT.getVectorNumElements();
3342
3343   bool Changed = false;
3344   SmallVector<int, 8> MaskVec;
3345   SVOp->getMask(MaskVec);
3346
3347   for (unsigned i = 0; i != NumElems; ++i) {
3348     if (MaskVec[i] > (int)NumElems) {
3349       MaskVec[i] = NumElems;
3350       Changed = true;
3351     }
3352   }
3353   if (Changed)
3354     return DAG.getVectorShuffle(VT, SVOp->getDebugLoc(), SVOp->getOperand(0),
3355                                 SVOp->getOperand(1), &MaskVec[0]);
3356   return SDValue(SVOp, 0);
3357 }
3358
3359 /// getMOVLMask - Returns a vector_shuffle mask for an movs{s|d}, movd
3360 /// operation of specified width.
3361 static SDValue getMOVL(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
3362                        SDValue V2) {
3363   unsigned NumElems = VT.getVectorNumElements();
3364   SmallVector<int, 8> Mask;
3365   Mask.push_back(NumElems);
3366   for (unsigned i = 1; i != NumElems; ++i)
3367     Mask.push_back(i);
3368   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
3369 }
3370
3371 /// getUnpackl - Returns a vector_shuffle node for an unpackl operation.
3372 static SDValue getUnpackl(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
3373                           SDValue V2) {
3374   unsigned NumElems = VT.getVectorNumElements();
3375   SmallVector<int, 8> Mask;
3376   for (unsigned i = 0, e = NumElems/2; i != e; ++i) {
3377     Mask.push_back(i);
3378     Mask.push_back(i + NumElems);
3379   }
3380   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
3381 }
3382
3383 /// getUnpackhMask - Returns a vector_shuffle node for an unpackh operation.
3384 static SDValue getUnpackh(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
3385                           SDValue V2) {
3386   unsigned NumElems = VT.getVectorNumElements();
3387   unsigned Half = NumElems/2;
3388   SmallVector<int, 8> Mask;
3389   for (unsigned i = 0; i != Half; ++i) {
3390     Mask.push_back(i + Half);
3391     Mask.push_back(i + NumElems + Half);
3392   }
3393   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
3394 }
3395
3396 /// PromoteSplat - Promote a splat of v4f32, v8i16 or v16i8 to v4i32.
3397 static SDValue PromoteSplat(ShuffleVectorSDNode *SV, SelectionDAG &DAG,
3398                             bool HasSSE2) {
3399   if (SV->getValueType(0).getVectorNumElements() <= 4)
3400     return SDValue(SV, 0);
3401
3402   EVT PVT = MVT::v4f32;
3403   EVT VT = SV->getValueType(0);
3404   DebugLoc dl = SV->getDebugLoc();
3405   SDValue V1 = SV->getOperand(0);
3406   int NumElems = VT.getVectorNumElements();
3407   int EltNo = SV->getSplatIndex();
3408
3409   // unpack elements to the correct location
3410   while (NumElems > 4) {
3411     if (EltNo < NumElems/2) {
3412       V1 = getUnpackl(DAG, dl, VT, V1, V1);
3413     } else {
3414       V1 = getUnpackh(DAG, dl, VT, V1, V1);
3415       EltNo -= NumElems/2;
3416     }
3417     NumElems >>= 1;
3418   }
3419
3420   // Perform the splat.
3421   int SplatMask[4] = { EltNo, EltNo, EltNo, EltNo };
3422   V1 = DAG.getNode(ISD::BIT_CONVERT, dl, PVT, V1);
3423   V1 = DAG.getVectorShuffle(PVT, dl, V1, DAG.getUNDEF(PVT), &SplatMask[0]);
3424   return DAG.getNode(ISD::BIT_CONVERT, dl, VT, V1);
3425 }
3426
3427 /// getShuffleVectorZeroOrUndef - Return a vector_shuffle of the specified
3428 /// vector of zero or undef vector.  This produces a shuffle where the low
3429 /// element of V2 is swizzled into the zero/undef vector, landing at element
3430 /// Idx.  This produces a shuffle mask like 4,1,2,3 (idx=0) or  0,1,2,4 (idx=3).
3431 static SDValue getShuffleVectorZeroOrUndef(SDValue V2, unsigned Idx,
3432                                              bool isZero, bool HasSSE2,
3433                                              SelectionDAG &DAG) {
3434   EVT VT = V2.getValueType();
3435   SDValue V1 = isZero
3436     ? getZeroVector(VT, HasSSE2, DAG, V2.getDebugLoc()) : DAG.getUNDEF(VT);
3437   unsigned NumElems = VT.getVectorNumElements();
3438   SmallVector<int, 16> MaskVec;
3439   for (unsigned i = 0; i != NumElems; ++i)
3440     // If this is the insertion idx, put the low elt of V2 here.
3441     MaskVec.push_back(i == Idx ? NumElems : i);
3442   return DAG.getVectorShuffle(VT, V2.getDebugLoc(), V1, V2, &MaskVec[0]);
3443 }
3444
3445 /// getNumOfConsecutiveZeros - Return the number of elements in a result of
3446 /// a shuffle that is zero.
3447 static
3448 unsigned getNumOfConsecutiveZeros(ShuffleVectorSDNode *SVOp, int NumElems,
3449                                   bool Low, SelectionDAG &DAG) {
3450   unsigned NumZeros = 0;
3451   for (int i = 0; i < NumElems; ++i) {
3452     unsigned Index = Low ? i : NumElems-i-1;
3453     int Idx = SVOp->getMaskElt(Index);
3454     if (Idx < 0) {
3455       ++NumZeros;
3456       continue;
3457     }
3458     SDValue Elt = DAG.getShuffleScalarElt(SVOp, Index);
3459     if (Elt.getNode() && X86::isZeroNode(Elt))
3460       ++NumZeros;
3461     else
3462       break;
3463   }
3464   return NumZeros;
3465 }
3466
3467 /// isVectorShift - Returns true if the shuffle can be implemented as a
3468 /// logical left or right shift of a vector.
3469 /// FIXME: split into pslldqi, psrldqi, palignr variants.
3470 static bool isVectorShift(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
3471                           bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
3472   unsigned NumElems = SVOp->getValueType(0).getVectorNumElements();
3473
3474   isLeft = true;
3475   unsigned NumZeros = getNumOfConsecutiveZeros(SVOp, NumElems, true, DAG);
3476   if (!NumZeros) {
3477     isLeft = false;
3478     NumZeros = getNumOfConsecutiveZeros(SVOp, NumElems, false, DAG);
3479     if (!NumZeros)
3480       return false;
3481   }
3482   bool SeenV1 = false;
3483   bool SeenV2 = false;
3484   for (unsigned i = NumZeros; i < NumElems; ++i) {
3485     unsigned Val = isLeft ? (i - NumZeros) : i;
3486     int Idx_ = SVOp->getMaskElt(isLeft ? i : (i - NumZeros));
3487     if (Idx_ < 0)
3488       continue;
3489     unsigned Idx = (unsigned) Idx_;
3490     if (Idx < NumElems)
3491       SeenV1 = true;
3492     else {
3493       Idx -= NumElems;
3494       SeenV2 = true;
3495     }
3496     if (Idx != Val)
3497       return false;
3498   }
3499   if (SeenV1 && SeenV2)
3500     return false;
3501
3502   ShVal = SeenV1 ? SVOp->getOperand(0) : SVOp->getOperand(1);
3503   ShAmt = NumZeros;
3504   return true;
3505 }
3506
3507
3508 /// LowerBuildVectorv16i8 - Custom lower build_vector of v16i8.
3509 ///
3510 static SDValue LowerBuildVectorv16i8(SDValue Op, unsigned NonZeros,
3511                                        unsigned NumNonZero, unsigned NumZero,
3512                                        SelectionDAG &DAG,
3513                                        const TargetLowering &TLI) {
3514   if (NumNonZero > 8)
3515     return SDValue();
3516
3517   DebugLoc dl = Op.getDebugLoc();
3518   SDValue V(0, 0);
3519   bool First = true;
3520   for (unsigned i = 0; i < 16; ++i) {
3521     bool ThisIsNonZero = (NonZeros & (1 << i)) != 0;
3522     if (ThisIsNonZero && First) {
3523       if (NumZero)
3524         V = getZeroVector(MVT::v8i16, true, DAG, dl);
3525       else
3526         V = DAG.getUNDEF(MVT::v8i16);
3527       First = false;
3528     }
3529
3530     if ((i & 1) != 0) {
3531       SDValue ThisElt(0, 0), LastElt(0, 0);
3532       bool LastIsNonZero = (NonZeros & (1 << (i-1))) != 0;
3533       if (LastIsNonZero) {
3534         LastElt = DAG.getNode(ISD::ZERO_EXTEND, dl,
3535                               MVT::i16, Op.getOperand(i-1));
3536       }
3537       if (ThisIsNonZero) {
3538         ThisElt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i16, Op.getOperand(i));
3539         ThisElt = DAG.getNode(ISD::SHL, dl, MVT::i16,
3540                               ThisElt, DAG.getConstant(8, MVT::i8));
3541         if (LastIsNonZero)
3542           ThisElt = DAG.getNode(ISD::OR, dl, MVT::i16, ThisElt, LastElt);
3543       } else
3544         ThisElt = LastElt;
3545
3546       if (ThisElt.getNode())
3547         V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, V, ThisElt,
3548                         DAG.getIntPtrConstant(i/2));
3549     }
3550   }
3551
3552   return DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v16i8, V);
3553 }
3554
3555 /// LowerBuildVectorv8i16 - Custom lower build_vector of v8i16.
3556 ///
3557 static SDValue LowerBuildVectorv8i16(SDValue Op, unsigned NonZeros,
3558                                      unsigned NumNonZero, unsigned NumZero,
3559                                      SelectionDAG &DAG,
3560                                      const TargetLowering &TLI) {
3561   if (NumNonZero > 4)
3562     return SDValue();
3563
3564   DebugLoc dl = Op.getDebugLoc();
3565   SDValue V(0, 0);
3566   bool First = true;
3567   for (unsigned i = 0; i < 8; ++i) {
3568     bool isNonZero = (NonZeros & (1 << i)) != 0;
3569     if (isNonZero) {
3570       if (First) {
3571         if (NumZero)
3572           V = getZeroVector(MVT::v8i16, true, DAG, dl);
3573         else
3574           V = DAG.getUNDEF(MVT::v8i16);
3575         First = false;
3576       }
3577       V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl,
3578                       MVT::v8i16, V, Op.getOperand(i),
3579                       DAG.getIntPtrConstant(i));
3580     }
3581   }
3582
3583   return V;
3584 }
3585
3586 /// getVShift - Return a vector logical shift node.
3587 ///
3588 static SDValue getVShift(bool isLeft, EVT VT, SDValue SrcOp,
3589                          unsigned NumBits, SelectionDAG &DAG,
3590                          const TargetLowering &TLI, DebugLoc dl) {
3591   bool isMMX = VT.getSizeInBits() == 64;
3592   EVT ShVT = isMMX ? MVT::v1i64 : MVT::v2i64;
3593   unsigned Opc = isLeft ? X86ISD::VSHL : X86ISD::VSRL;
3594   SrcOp = DAG.getNode(ISD::BIT_CONVERT, dl, ShVT, SrcOp);
3595   return DAG.getNode(ISD::BIT_CONVERT, dl, VT,
3596                      DAG.getNode(Opc, dl, ShVT, SrcOp,
3597                              DAG.getConstant(NumBits, TLI.getShiftAmountTy())));
3598 }
3599
3600 SDValue
3601 X86TargetLowering::LowerAsSplatVectorLoad(SDValue SrcOp, EVT VT, DebugLoc dl,
3602                                           SelectionDAG &DAG) const {
3603   
3604   // Check if the scalar load can be widened into a vector load. And if
3605   // the address is "base + cst" see if the cst can be "absorbed" into
3606   // the shuffle mask.
3607   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(SrcOp)) {
3608     SDValue Ptr = LD->getBasePtr();
3609     if (!ISD::isNormalLoad(LD) || LD->isVolatile())
3610       return SDValue();
3611     EVT PVT = LD->getValueType(0);
3612     if (PVT != MVT::i32 && PVT != MVT::f32)
3613       return SDValue();
3614
3615     int FI = -1;
3616     int64_t Offset = 0;
3617     if (FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr)) {
3618       FI = FINode->getIndex();
3619       Offset = 0;
3620     } else if (Ptr.getOpcode() == ISD::ADD &&
3621                isa<ConstantSDNode>(Ptr.getOperand(1)) &&
3622                isa<FrameIndexSDNode>(Ptr.getOperand(0))) {
3623       FI = cast<FrameIndexSDNode>(Ptr.getOperand(0))->getIndex();
3624       Offset = Ptr.getConstantOperandVal(1);
3625       Ptr = Ptr.getOperand(0);
3626     } else {
3627       return SDValue();
3628     }
3629
3630     SDValue Chain = LD->getChain();
3631     // Make sure the stack object alignment is at least 16.
3632     MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
3633     if (DAG.InferPtrAlignment(Ptr) < 16) {
3634       if (MFI->isFixedObjectIndex(FI)) {
3635         // Can't change the alignment. FIXME: It's possible to compute
3636         // the exact stack offset and reference FI + adjust offset instead.
3637         // If someone *really* cares about this. That's the way to implement it.
3638         return SDValue();
3639       } else {
3640         MFI->setObjectAlignment(FI, 16);
3641       }
3642     }
3643
3644     // (Offset % 16) must be multiple of 4. Then address is then
3645     // Ptr + (Offset & ~15).
3646     if (Offset < 0)
3647       return SDValue();
3648     if ((Offset % 16) & 3)
3649       return SDValue();
3650     int64_t StartOffset = Offset & ~15;
3651     if (StartOffset)
3652       Ptr = DAG.getNode(ISD::ADD, Ptr.getDebugLoc(), Ptr.getValueType(),
3653                         Ptr,DAG.getConstant(StartOffset, Ptr.getValueType()));
3654
3655     int EltNo = (Offset - StartOffset) >> 2;
3656     int Mask[4] = { EltNo, EltNo, EltNo, EltNo };
3657     EVT VT = (PVT == MVT::i32) ? MVT::v4i32 : MVT::v4f32;
3658     SDValue V1 = DAG.getLoad(VT, dl, Chain, Ptr,LD->getSrcValue(),0,
3659                              false, false, 0);
3660     // Canonicalize it to a v4i32 shuffle.
3661     V1 = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v4i32, V1);
3662     return DAG.getNode(ISD::BIT_CONVERT, dl, VT,
3663                        DAG.getVectorShuffle(MVT::v4i32, dl, V1,
3664                                             DAG.getUNDEF(MVT::v4i32), &Mask[0]));
3665   }
3666
3667   return SDValue();
3668 }
3669
3670 /// EltsFromConsecutiveLoads - Given the initializing elements 'Elts' of a 
3671 /// vector of type 'VT', see if the elements can be replaced by a single large 
3672 /// load which has the same value as a build_vector whose operands are 'elts'.
3673 ///
3674 /// Example: <load i32 *a, load i32 *a+4, undef, undef> -> zextload a
3675 /// 
3676 /// FIXME: we'd also like to handle the case where the last elements are zero
3677 /// rather than undef via VZEXT_LOAD, but we do not detect that case today.
3678 /// There's even a handy isZeroNode for that purpose.
3679 static SDValue EltsFromConsecutiveLoads(EVT VT, SmallVectorImpl<SDValue> &Elts,
3680                                         DebugLoc &dl, SelectionDAG &DAG) {
3681   EVT EltVT = VT.getVectorElementType();
3682   unsigned NumElems = Elts.size();
3683   
3684   LoadSDNode *LDBase = NULL;
3685   unsigned LastLoadedElt = -1U;
3686   
3687   // For each element in the initializer, see if we've found a load or an undef.
3688   // If we don't find an initial load element, or later load elements are 
3689   // non-consecutive, bail out.
3690   for (unsigned i = 0; i < NumElems; ++i) {
3691     SDValue Elt = Elts[i];
3692     
3693     if (!Elt.getNode() ||
3694         (Elt.getOpcode() != ISD::UNDEF && !ISD::isNON_EXTLoad(Elt.getNode())))
3695       return SDValue();
3696     if (!LDBase) {
3697       if (Elt.getNode()->getOpcode() == ISD::UNDEF)
3698         return SDValue();
3699       LDBase = cast<LoadSDNode>(Elt.getNode());
3700       LastLoadedElt = i;
3701       continue;
3702     }
3703     if (Elt.getOpcode() == ISD::UNDEF)
3704       continue;
3705
3706     LoadSDNode *LD = cast<LoadSDNode>(Elt);
3707     if (!DAG.isConsecutiveLoad(LD, LDBase, EltVT.getSizeInBits()/8, i))
3708       return SDValue();
3709     LastLoadedElt = i;
3710   }
3711
3712   // If we have found an entire vector of loads and undefs, then return a large
3713   // load of the entire vector width starting at the base pointer.  If we found
3714   // consecutive loads for the low half, generate a vzext_load node.
3715   if (LastLoadedElt == NumElems - 1) {
3716     if (DAG.InferPtrAlignment(LDBase->getBasePtr()) >= 16)
3717       return DAG.getLoad(VT, dl, LDBase->getChain(), LDBase->getBasePtr(),
3718                          LDBase->getSrcValue(), LDBase->getSrcValueOffset(),
3719                          LDBase->isVolatile(), LDBase->isNonTemporal(), 0);
3720     return DAG.getLoad(VT, dl, LDBase->getChain(), LDBase->getBasePtr(),
3721                        LDBase->getSrcValue(), LDBase->getSrcValueOffset(),
3722                        LDBase->isVolatile(), LDBase->isNonTemporal(),
3723                        LDBase->getAlignment());
3724   } else if (NumElems == 4 && LastLoadedElt == 1) {
3725     SDVTList Tys = DAG.getVTList(MVT::v2i64, MVT::Other);
3726     SDValue Ops[] = { LDBase->getChain(), LDBase->getBasePtr() };
3727     SDValue ResNode = DAG.getNode(X86ISD::VZEXT_LOAD, dl, Tys, Ops, 2);
3728     return DAG.getNode(ISD::BIT_CONVERT, dl, VT, ResNode);
3729   }
3730   return SDValue();
3731 }
3732
3733 SDValue
3734 X86TargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG) const {
3735   DebugLoc dl = Op.getDebugLoc();
3736   // All zero's are handled with pxor, all one's are handled with pcmpeqd.
3737   if (ISD::isBuildVectorAllZeros(Op.getNode())
3738       || ISD::isBuildVectorAllOnes(Op.getNode())) {
3739     // Canonicalize this to either <4 x i32> or <2 x i32> (SSE vs MMX) to
3740     // 1) ensure the zero vectors are CSE'd, and 2) ensure that i64 scalars are
3741     // eliminated on x86-32 hosts.
3742     if (Op.getValueType() == MVT::v4i32 || Op.getValueType() == MVT::v2i32)
3743       return Op;
3744
3745     if (ISD::isBuildVectorAllOnes(Op.getNode()))
3746       return getOnesVector(Op.getValueType(), DAG, dl);
3747     return getZeroVector(Op.getValueType(), Subtarget->hasSSE2(), DAG, dl);
3748   }
3749
3750   EVT VT = Op.getValueType();
3751   EVT ExtVT = VT.getVectorElementType();
3752   unsigned EVTBits = ExtVT.getSizeInBits();
3753
3754   unsigned NumElems = Op.getNumOperands();
3755   unsigned NumZero  = 0;
3756   unsigned NumNonZero = 0;
3757   unsigned NonZeros = 0;
3758   bool IsAllConstants = true;
3759   SmallSet<SDValue, 8> Values;
3760   for (unsigned i = 0; i < NumElems; ++i) {
3761     SDValue Elt = Op.getOperand(i);
3762     if (Elt.getOpcode() == ISD::UNDEF)
3763       continue;
3764     Values.insert(Elt);
3765     if (Elt.getOpcode() != ISD::Constant &&
3766         Elt.getOpcode() != ISD::ConstantFP)
3767       IsAllConstants = false;
3768     if (X86::isZeroNode(Elt))
3769       NumZero++;
3770     else {
3771       NonZeros |= (1 << i);
3772       NumNonZero++;
3773     }
3774   }
3775
3776   if (NumNonZero == 0) {
3777     // All undef vector. Return an UNDEF.  All zero vectors were handled above.
3778     return DAG.getUNDEF(VT);
3779   }
3780
3781   // Special case for single non-zero, non-undef, element.
3782   if (NumNonZero == 1) {
3783     unsigned Idx = CountTrailingZeros_32(NonZeros);
3784     SDValue Item = Op.getOperand(Idx);
3785
3786     // If this is an insertion of an i64 value on x86-32, and if the top bits of
3787     // the value are obviously zero, truncate the value to i32 and do the
3788     // insertion that way.  Only do this if the value is non-constant or if the
3789     // value is a constant being inserted into element 0.  It is cheaper to do
3790     // a constant pool load than it is to do a movd + shuffle.
3791     if (ExtVT == MVT::i64 && !Subtarget->is64Bit() &&
3792         (!IsAllConstants || Idx == 0)) {
3793       if (DAG.MaskedValueIsZero(Item, APInt::getBitsSet(64, 32, 64))) {
3794         // Handle MMX and SSE both.
3795         EVT VecVT = VT == MVT::v2i64 ? MVT::v4i32 : MVT::v2i32;
3796         unsigned VecElts = VT == MVT::v2i64 ? 4 : 2;
3797
3798         // Truncate the value (which may itself be a constant) to i32, and
3799         // convert it to a vector with movd (S2V+shuffle to zero extend).
3800         Item = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Item);
3801         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VecVT, Item);
3802         Item = getShuffleVectorZeroOrUndef(Item, 0, true,
3803                                            Subtarget->hasSSE2(), DAG);
3804
3805         // Now we have our 32-bit value zero extended in the low element of
3806         // a vector.  If Idx != 0, swizzle it into place.
3807         if (Idx != 0) {
3808           SmallVector<int, 4> Mask;
3809           Mask.push_back(Idx);
3810           for (unsigned i = 1; i != VecElts; ++i)
3811             Mask.push_back(i);
3812           Item = DAG.getVectorShuffle(VecVT, dl, Item,
3813                                       DAG.getUNDEF(Item.getValueType()),
3814                                       &Mask[0]);
3815         }
3816         return DAG.getNode(ISD::BIT_CONVERT, dl, Op.getValueType(), Item);
3817       }
3818     }
3819
3820     // If we have a constant or non-constant insertion into the low element of
3821     // a vector, we can do this with SCALAR_TO_VECTOR + shuffle of zero into
3822     // the rest of the elements.  This will be matched as movd/movq/movss/movsd
3823     // depending on what the source datatype is.
3824     if (Idx == 0) {
3825       if (NumZero == 0) {
3826         return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
3827       } else if (ExtVT == MVT::i32 || ExtVT == MVT::f32 || ExtVT == MVT::f64 ||
3828           (ExtVT == MVT::i64 && Subtarget->is64Bit())) {
3829         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
3830         // Turn it into a MOVL (i.e. movss, movsd, or movd) to a zero vector.
3831         return getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget->hasSSE2(),
3832                                            DAG);
3833       } else if (ExtVT == MVT::i16 || ExtVT == MVT::i8) {
3834         Item = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, Item);
3835         EVT MiddleVT = VT.getSizeInBits() == 64 ? MVT::v2i32 : MVT::v4i32;
3836         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MiddleVT, Item);
3837         Item = getShuffleVectorZeroOrUndef(Item, 0, true,
3838                                            Subtarget->hasSSE2(), DAG);
3839         return DAG.getNode(ISD::BIT_CONVERT, dl, VT, Item);
3840       }
3841     }
3842
3843     // Is it a vector logical left shift?
3844     if (NumElems == 2 && Idx == 1 &&
3845         X86::isZeroNode(Op.getOperand(0)) &&
3846         !X86::isZeroNode(Op.getOperand(1))) {
3847       unsigned NumBits = VT.getSizeInBits();
3848       return getVShift(true, VT,
3849                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
3850                                    VT, Op.getOperand(1)),
3851                        NumBits/2, DAG, *this, dl);
3852     }
3853
3854     if (IsAllConstants) // Otherwise, it's better to do a constpool load.
3855       return SDValue();
3856
3857     // Otherwise, if this is a vector with i32 or f32 elements, and the element
3858     // is a non-constant being inserted into an element other than the low one,
3859     // we can't use a constant pool load.  Instead, use SCALAR_TO_VECTOR (aka
3860     // movd/movss) to move this into the low element, then shuffle it into
3861     // place.
3862     if (EVTBits == 32) {
3863       Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
3864
3865       // Turn it into a shuffle of zero and zero-extended scalar to vector.
3866       Item = getShuffleVectorZeroOrUndef(Item, 0, NumZero > 0,
3867                                          Subtarget->hasSSE2(), DAG);
3868       SmallVector<int, 8> MaskVec;
3869       for (unsigned i = 0; i < NumElems; i++)
3870         MaskVec.push_back(i == Idx ? 0 : 1);
3871       return DAG.getVectorShuffle(VT, dl, Item, DAG.getUNDEF(VT), &MaskVec[0]);
3872     }
3873   }
3874
3875   // Splat is obviously ok. Let legalizer expand it to a shuffle.
3876   if (Values.size() == 1) {
3877     if (EVTBits == 32) {
3878       // Instead of a shuffle like this:
3879       // shuffle (scalar_to_vector (load (ptr + 4))), undef, <0, 0, 0, 0>
3880       // Check if it's possible to issue this instead.
3881       // shuffle (vload ptr)), undef, <1, 1, 1, 1>
3882       unsigned Idx = CountTrailingZeros_32(NonZeros);
3883       SDValue Item = Op.getOperand(Idx);
3884       if (Op.getNode()->isOnlyUserOf(Item.getNode()))
3885         return LowerAsSplatVectorLoad(Item, VT, dl, DAG);
3886     }
3887     return SDValue();
3888   }
3889
3890   // A vector full of immediates; various special cases are already
3891   // handled, so this is best done with a single constant-pool load.
3892   if (IsAllConstants)
3893     return SDValue();
3894
3895   // Let legalizer expand 2-wide build_vectors.
3896   if (EVTBits == 64) {
3897     if (NumNonZero == 1) {
3898       // One half is zero or undef.
3899       unsigned Idx = CountTrailingZeros_32(NonZeros);
3900       SDValue V2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT,
3901                                  Op.getOperand(Idx));
3902       return getShuffleVectorZeroOrUndef(V2, Idx, true,
3903                                          Subtarget->hasSSE2(), DAG);
3904     }
3905     return SDValue();
3906   }
3907
3908   // If element VT is < 32 bits, convert it to inserts into a zero vector.
3909   if (EVTBits == 8 && NumElems == 16) {
3910     SDValue V = LowerBuildVectorv16i8(Op, NonZeros,NumNonZero,NumZero, DAG,
3911                                         *this);
3912     if (V.getNode()) return V;
3913   }
3914
3915   if (EVTBits == 16 && NumElems == 8) {
3916     SDValue V = LowerBuildVectorv8i16(Op, NonZeros,NumNonZero,NumZero, DAG,
3917                                         *this);
3918     if (V.getNode()) return V;
3919   }
3920
3921   // If element VT is == 32 bits, turn it into a number of shuffles.
3922   SmallVector<SDValue, 8> V;
3923   V.resize(NumElems);
3924   if (NumElems == 4 && NumZero > 0) {
3925     for (unsigned i = 0; i < 4; ++i) {
3926       bool isZero = !(NonZeros & (1 << i));
3927       if (isZero)
3928         V[i] = getZeroVector(VT, Subtarget->hasSSE2(), DAG, dl);
3929       else
3930         V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
3931     }
3932
3933     for (unsigned i = 0; i < 2; ++i) {
3934       switch ((NonZeros & (0x3 << i*2)) >> (i*2)) {
3935         default: break;
3936         case 0:
3937           V[i] = V[i*2];  // Must be a zero vector.
3938           break;
3939         case 1:
3940           V[i] = getMOVL(DAG, dl, VT, V[i*2+1], V[i*2]);
3941           break;
3942         case 2:
3943           V[i] = getMOVL(DAG, dl, VT, V[i*2], V[i*2+1]);
3944           break;
3945         case 3:
3946           V[i] = getUnpackl(DAG, dl, VT, V[i*2], V[i*2+1]);
3947           break;
3948       }
3949     }
3950
3951     SmallVector<int, 8> MaskVec;
3952     bool Reverse = (NonZeros & 0x3) == 2;
3953     for (unsigned i = 0; i < 2; ++i)
3954       MaskVec.push_back(Reverse ? 1-i : i);
3955     Reverse = ((NonZeros & (0x3 << 2)) >> 2) == 2;
3956     for (unsigned i = 0; i < 2; ++i)
3957       MaskVec.push_back(Reverse ? 1-i+NumElems : i+NumElems);
3958     return DAG.getVectorShuffle(VT, dl, V[0], V[1], &MaskVec[0]);
3959   }
3960
3961   if (Values.size() > 1 && VT.getSizeInBits() == 128) {
3962     // Check for a build vector of consecutive loads.
3963     for (unsigned i = 0; i < NumElems; ++i)
3964       V[i] = Op.getOperand(i);
3965     
3966     // Check for elements which are consecutive loads.
3967     SDValue LD = EltsFromConsecutiveLoads(VT, V, dl, DAG);
3968     if (LD.getNode())
3969       return LD;
3970     
3971     // For SSE 4.1, use inserts into undef.  
3972     if (getSubtarget()->hasSSE41()) {
3973       V[0] = DAG.getUNDEF(VT);
3974       for (unsigned i = 0; i < NumElems; ++i)
3975         if (Op.getOperand(i).getOpcode() != ISD::UNDEF)
3976           V[0] = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, V[0],
3977                              Op.getOperand(i), DAG.getIntPtrConstant(i));
3978       return V[0];
3979     }
3980     
3981     // Otherwise, expand into a number of unpckl*
3982     // e.g. for v4f32
3983     //   Step 1: unpcklps 0, 2 ==> X: <?, ?, 2, 0>
3984     //         : unpcklps 1, 3 ==> Y: <?, ?, 3, 1>
3985     //   Step 2: unpcklps X, Y ==>    <3, 2, 1, 0>
3986     for (unsigned i = 0; i < NumElems; ++i)
3987       V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
3988     NumElems >>= 1;
3989     while (NumElems != 0) {
3990       for (unsigned i = 0; i < NumElems; ++i)
3991         V[i] = getUnpackl(DAG, dl, VT, V[i], V[i + NumElems]);
3992       NumElems >>= 1;
3993     }
3994     return V[0];
3995   }
3996   return SDValue();
3997 }
3998
3999 SDValue
4000 X86TargetLowering::LowerCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) const {
4001   // We support concatenate two MMX registers and place them in a MMX
4002   // register.  This is better than doing a stack convert.
4003   DebugLoc dl = Op.getDebugLoc();
4004   EVT ResVT = Op.getValueType();
4005   assert(Op.getNumOperands() == 2);
4006   assert(ResVT == MVT::v2i64 || ResVT == MVT::v4i32 ||
4007          ResVT == MVT::v8i16 || ResVT == MVT::v16i8);
4008   int Mask[2];
4009   SDValue InVec = DAG.getNode(ISD::BIT_CONVERT,dl, MVT::v1i64, Op.getOperand(0));
4010   SDValue VecOp = DAG.getNode(X86ISD::MOVQ2DQ, dl, MVT::v2i64, InVec);
4011   InVec = Op.getOperand(1);
4012   if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR) {
4013     unsigned NumElts = ResVT.getVectorNumElements();
4014     VecOp = DAG.getNode(ISD::BIT_CONVERT, dl, ResVT, VecOp);
4015     VecOp = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, ResVT, VecOp,
4016                        InVec.getOperand(0), DAG.getIntPtrConstant(NumElts/2+1));
4017   } else {
4018     InVec = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v1i64, InVec);
4019     SDValue VecOp2 = DAG.getNode(X86ISD::MOVQ2DQ, dl, MVT::v2i64, InVec);
4020     Mask[0] = 0; Mask[1] = 2;
4021     VecOp = DAG.getVectorShuffle(MVT::v2i64, dl, VecOp, VecOp2, Mask);
4022   }
4023   return DAG.getNode(ISD::BIT_CONVERT, dl, ResVT, VecOp);
4024 }
4025
4026 // v8i16 shuffles - Prefer shuffles in the following order:
4027 // 1. [all]   pshuflw, pshufhw, optional move
4028 // 2. [ssse3] 1 x pshufb
4029 // 3. [ssse3] 2 x pshufb + 1 x por
4030 // 4. [all]   mov + pshuflw + pshufhw + N x (pextrw + pinsrw)
4031 static
4032 SDValue LowerVECTOR_SHUFFLEv8i16(ShuffleVectorSDNode *SVOp,
4033                                  SelectionDAG &DAG,
4034                                  const X86TargetLowering &TLI) {
4035   SDValue V1 = SVOp->getOperand(0);
4036   SDValue V2 = SVOp->getOperand(1);
4037   DebugLoc dl = SVOp->getDebugLoc();
4038   SmallVector<int, 8> MaskVals;
4039
4040   // Determine if more than 1 of the words in each of the low and high quadwords
4041   // of the result come from the same quadword of one of the two inputs.  Undef
4042   // mask values count as coming from any quadword, for better codegen.
4043   SmallVector<unsigned, 4> LoQuad(4);
4044   SmallVector<unsigned, 4> HiQuad(4);
4045   BitVector InputQuads(4);
4046   for (unsigned i = 0; i < 8; ++i) {
4047     SmallVectorImpl<unsigned> &Quad = i < 4 ? LoQuad : HiQuad;
4048     int EltIdx = SVOp->getMaskElt(i);
4049     MaskVals.push_back(EltIdx);
4050     if (EltIdx < 0) {
4051       ++Quad[0];
4052       ++Quad[1];
4053       ++Quad[2];
4054       ++Quad[3];
4055       continue;
4056     }
4057     ++Quad[EltIdx / 4];
4058     InputQuads.set(EltIdx / 4);
4059   }
4060
4061   int BestLoQuad = -1;
4062   unsigned MaxQuad = 1;
4063   for (unsigned i = 0; i < 4; ++i) {
4064     if (LoQuad[i] > MaxQuad) {
4065       BestLoQuad = i;
4066       MaxQuad = LoQuad[i];
4067     }
4068   }
4069
4070   int BestHiQuad = -1;
4071   MaxQuad = 1;
4072   for (unsigned i = 0; i < 4; ++i) {
4073     if (HiQuad[i] > MaxQuad) {
4074       BestHiQuad = i;
4075       MaxQuad = HiQuad[i];
4076     }
4077   }
4078
4079   // For SSSE3, If all 8 words of the result come from only 1 quadword of each
4080   // of the two input vectors, shuffle them into one input vector so only a
4081   // single pshufb instruction is necessary. If There are more than 2 input
4082   // quads, disable the next transformation since it does not help SSSE3.
4083   bool V1Used = InputQuads[0] || InputQuads[1];
4084   bool V2Used = InputQuads[2] || InputQuads[3];
4085   if (TLI.getSubtarget()->hasSSSE3()) {
4086     if (InputQuads.count() == 2 && V1Used && V2Used) {
4087       BestLoQuad = InputQuads.find_first();
4088       BestHiQuad = InputQuads.find_next(BestLoQuad);
4089     }
4090     if (InputQuads.count() > 2) {
4091       BestLoQuad = -1;
4092       BestHiQuad = -1;
4093     }
4094   }
4095
4096   // If BestLoQuad or BestHiQuad are set, shuffle the quads together and update
4097   // the shuffle mask.  If a quad is scored as -1, that means that it contains
4098   // words from all 4 input quadwords.
4099   SDValue NewV;
4100   if (BestLoQuad >= 0 || BestHiQuad >= 0) {
4101     SmallVector<int, 8> MaskV;
4102     MaskV.push_back(BestLoQuad < 0 ? 0 : BestLoQuad);
4103     MaskV.push_back(BestHiQuad < 0 ? 1 : BestHiQuad);
4104     NewV = DAG.getVectorShuffle(MVT::v2i64, dl,
4105                   DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v2i64, V1),
4106                   DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v2i64, V2), &MaskV[0]);
4107     NewV = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v8i16, NewV);
4108
4109     // Rewrite the MaskVals and assign NewV to V1 if NewV now contains all the
4110     // source words for the shuffle, to aid later transformations.
4111     bool AllWordsInNewV = true;
4112     bool InOrder[2] = { true, true };
4113     for (unsigned i = 0; i != 8; ++i) {
4114       int idx = MaskVals[i];
4115       if (idx != (int)i)
4116         InOrder[i/4] = false;
4117       if (idx < 0 || (idx/4) == BestLoQuad || (idx/4) == BestHiQuad)
4118         continue;
4119       AllWordsInNewV = false;
4120       break;
4121     }
4122
4123     bool pshuflw = AllWordsInNewV, pshufhw = AllWordsInNewV;
4124     if (AllWordsInNewV) {
4125       for (int i = 0; i != 8; ++i) {
4126         int idx = MaskVals[i];
4127         if (idx < 0)
4128           continue;
4129         idx = MaskVals[i] = (idx / 4) == BestLoQuad ? (idx & 3) : (idx & 3) + 4;
4130         if ((idx != i) && idx < 4)
4131           pshufhw = false;
4132         if ((idx != i) && idx > 3)
4133           pshuflw = false;
4134       }
4135       V1 = NewV;
4136       V2Used = false;
4137       BestLoQuad = 0;
4138       BestHiQuad = 1;
4139     }
4140
4141     // If we've eliminated the use of V2, and the new mask is a pshuflw or
4142     // pshufhw, that's as cheap as it gets.  Return the new shuffle.
4143     if ((pshufhw && InOrder[0]) || (pshuflw && InOrder[1])) {
4144       return DAG.getVectorShuffle(MVT::v8i16, dl, NewV,
4145                                   DAG.getUNDEF(MVT::v8i16), &MaskVals[0]);
4146     }
4147   }
4148
4149   // If we have SSSE3, and all words of the result are from 1 input vector,
4150   // case 2 is generated, otherwise case 3 is generated.  If no SSSE3
4151   // is present, fall back to case 4.
4152   if (TLI.getSubtarget()->hasSSSE3()) {
4153     SmallVector<SDValue,16> pshufbMask;
4154
4155     // If we have elements from both input vectors, set the high bit of the
4156     // shuffle mask element to zero out elements that come from V2 in the V1
4157     // mask, and elements that come from V1 in the V2 mask, so that the two
4158     // results can be OR'd together.
4159     bool TwoInputs = V1Used && V2Used;
4160     for (unsigned i = 0; i != 8; ++i) {
4161       int EltIdx = MaskVals[i] * 2;
4162       if (TwoInputs && (EltIdx >= 16)) {
4163         pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
4164         pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
4165         continue;
4166       }
4167       pshufbMask.push_back(DAG.getConstant(EltIdx,   MVT::i8));
4168       pshufbMask.push_back(DAG.getConstant(EltIdx+1, MVT::i8));
4169     }
4170     V1 = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v16i8, V1);
4171     V1 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V1,
4172                      DAG.getNode(ISD::BUILD_VECTOR, dl,
4173                                  MVT::v16i8, &pshufbMask[0], 16));
4174     if (!TwoInputs)
4175       return DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v8i16, V1);
4176
4177     // Calculate the shuffle mask for the second input, shuffle it, and
4178     // OR it with the first shuffled input.
4179     pshufbMask.clear();
4180     for (unsigned i = 0; i != 8; ++i) {
4181       int EltIdx = MaskVals[i] * 2;
4182       if (EltIdx < 16) {
4183         pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
4184         pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
4185         continue;
4186       }
4187       pshufbMask.push_back(DAG.getConstant(EltIdx - 16, MVT::i8));
4188       pshufbMask.push_back(DAG.getConstant(EltIdx - 15, MVT::i8));
4189     }
4190     V2 = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v16i8, V2);
4191     V2 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V2,
4192                      DAG.getNode(ISD::BUILD_VECTOR, dl,
4193                                  MVT::v16i8, &pshufbMask[0], 16));
4194     V1 = DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2);
4195     return DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v8i16, V1);
4196   }
4197
4198   // If BestLoQuad >= 0, generate a pshuflw to put the low elements in order,
4199   // and update MaskVals with new element order.
4200   BitVector InOrder(8);
4201   if (BestLoQuad >= 0) {
4202     SmallVector<int, 8> MaskV;
4203     for (int i = 0; i != 4; ++i) {
4204       int idx = MaskVals[i];
4205       if (idx < 0) {
4206         MaskV.push_back(-1);
4207         InOrder.set(i);
4208       } else if ((idx / 4) == BestLoQuad) {
4209         MaskV.push_back(idx & 3);
4210         InOrder.set(i);
4211       } else {
4212         MaskV.push_back(-1);
4213       }
4214     }
4215     for (unsigned i = 4; i != 8; ++i)
4216       MaskV.push_back(i);
4217     NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::v8i16),
4218                                 &MaskV[0]);
4219   }
4220
4221   // If BestHi >= 0, generate a pshufhw to put the high elements in order,
4222   // and update MaskVals with the new element order.
4223   if (BestHiQuad >= 0) {
4224     SmallVector<int, 8> MaskV;
4225     for (unsigned i = 0; i != 4; ++i)
4226       MaskV.push_back(i);
4227     for (unsigned i = 4; i != 8; ++i) {
4228       int idx = MaskVals[i];
4229       if (idx < 0) {
4230         MaskV.push_back(-1);
4231         InOrder.set(i);
4232       } else if ((idx / 4) == BestHiQuad) {
4233         MaskV.push_back((idx & 3) + 4);
4234         InOrder.set(i);
4235       } else {
4236         MaskV.push_back(-1);
4237       }
4238     }
4239     NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::v8i16),
4240                                 &MaskV[0]);
4241   }
4242
4243   // In case BestHi & BestLo were both -1, which means each quadword has a word
4244   // from each of the four input quadwords, calculate the InOrder bitvector now
4245   // before falling through to the insert/extract cleanup.
4246   if (BestLoQuad == -1 && BestHiQuad == -1) {
4247     NewV = V1;
4248     for (int i = 0; i != 8; ++i)
4249       if (MaskVals[i] < 0 || MaskVals[i] == i)
4250         InOrder.set(i);
4251   }
4252
4253   // The other elements are put in the right place using pextrw and pinsrw.
4254   for (unsigned i = 0; i != 8; ++i) {
4255     if (InOrder[i])
4256       continue;
4257     int EltIdx = MaskVals[i];
4258     if (EltIdx < 0)
4259       continue;
4260     SDValue ExtOp = (EltIdx < 8)
4261     ? DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V1,
4262                   DAG.getIntPtrConstant(EltIdx))
4263     : DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V2,
4264                   DAG.getIntPtrConstant(EltIdx - 8));
4265     NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, ExtOp,
4266                        DAG.getIntPtrConstant(i));
4267   }
4268   return NewV;
4269 }
4270
4271 // v16i8 shuffles - Prefer shuffles in the following order:
4272 // 1. [ssse3] 1 x pshufb
4273 // 2. [ssse3] 2 x pshufb + 1 x por
4274 // 3. [all]   v8i16 shuffle + N x pextrw + rotate + pinsrw
4275 static
4276 SDValue LowerVECTOR_SHUFFLEv16i8(ShuffleVectorSDNode *SVOp,
4277                                  SelectionDAG &DAG,
4278                                  const X86TargetLowering &TLI) {
4279   SDValue V1 = SVOp->getOperand(0);
4280   SDValue V2 = SVOp->getOperand(1);
4281   DebugLoc dl = SVOp->getDebugLoc();
4282   SmallVector<int, 16> MaskVals;
4283   SVOp->getMask(MaskVals);
4284
4285   // If we have SSSE3, case 1 is generated when all result bytes come from
4286   // one of  the inputs.  Otherwise, case 2 is generated.  If no SSSE3 is
4287   // present, fall back to case 3.
4288   // FIXME: kill V2Only once shuffles are canonizalized by getNode.
4289   bool V1Only = true;
4290   bool V2Only = true;
4291   for (unsigned i = 0; i < 16; ++i) {
4292     int EltIdx = MaskVals[i];
4293     if (EltIdx < 0)
4294       continue;
4295     if (EltIdx < 16)
4296       V2Only = false;
4297     else
4298       V1Only = false;
4299   }
4300
4301   // If SSSE3, use 1 pshufb instruction per vector with elements in the result.
4302   if (TLI.getSubtarget()->hasSSSE3()) {
4303     SmallVector<SDValue,16> pshufbMask;
4304
4305     // If all result elements are from one input vector, then only translate
4306     // undef mask values to 0x80 (zero out result) in the pshufb mask.
4307     //
4308     // Otherwise, we have elements from both input vectors, and must zero out
4309     // elements that come from V2 in the first mask, and V1 in the second mask
4310     // so that we can OR them together.
4311     bool TwoInputs = !(V1Only || V2Only);
4312     for (unsigned i = 0; i != 16; ++i) {
4313       int EltIdx = MaskVals[i];
4314       if (EltIdx < 0 || (TwoInputs && EltIdx >= 16)) {
4315         pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
4316         continue;
4317       }
4318       pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8));
4319     }
4320     // If all the elements are from V2, assign it to V1 and return after
4321     // building the first pshufb.
4322     if (V2Only)
4323       V1 = V2;
4324     V1 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V1,
4325                      DAG.getNode(ISD::BUILD_VECTOR, dl,
4326                                  MVT::v16i8, &pshufbMask[0], 16));
4327     if (!TwoInputs)
4328       return V1;
4329
4330     // Calculate the shuffle mask for the second input, shuffle it, and
4331     // OR it with the first shuffled input.
4332     pshufbMask.clear();
4333     for (unsigned i = 0; i != 16; ++i) {
4334       int EltIdx = MaskVals[i];
4335       if (EltIdx < 16) {
4336         pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
4337         continue;
4338       }
4339       pshufbMask.push_back(DAG.getConstant(EltIdx - 16, MVT::i8));
4340     }
4341     V2 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V2,
4342                      DAG.getNode(ISD::BUILD_VECTOR, dl,
4343                                  MVT::v16i8, &pshufbMask[0], 16));
4344     return DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2);
4345   }
4346
4347   // No SSSE3 - Calculate in place words and then fix all out of place words
4348   // With 0-16 extracts & inserts.  Worst case is 16 bytes out of order from
4349   // the 16 different words that comprise the two doublequadword input vectors.
4350   V1 = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v8i16, V1);
4351   V2 = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v8i16, V2);
4352   SDValue NewV = V2Only ? V2 : V1;
4353   for (int i = 0; i != 8; ++i) {
4354     int Elt0 = MaskVals[i*2];
4355     int Elt1 = MaskVals[i*2+1];
4356
4357     // This word of the result is all undef, skip it.
4358     if (Elt0 < 0 && Elt1 < 0)
4359       continue;
4360
4361     // This word of the result is already in the correct place, skip it.
4362     if (V1Only && (Elt0 == i*2) && (Elt1 == i*2+1))
4363       continue;
4364     if (V2Only && (Elt0 == i*2+16) && (Elt1 == i*2+17))
4365       continue;
4366
4367     SDValue Elt0Src = Elt0 < 16 ? V1 : V2;
4368     SDValue Elt1Src = Elt1 < 16 ? V1 : V2;
4369     SDValue InsElt;
4370
4371     // If Elt0 and Elt1 are defined, are consecutive, and can be load
4372     // using a single extract together, load it and store it.
4373     if ((Elt0 >= 0) && ((Elt0 + 1) == Elt1) && ((Elt0 & 1) == 0)) {
4374       InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src,
4375                            DAG.getIntPtrConstant(Elt1 / 2));
4376       NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt,
4377                         DAG.getIntPtrConstant(i));
4378       continue;
4379     }
4380
4381     // If Elt1 is defined, extract it from the appropriate source.  If the
4382     // source byte is not also odd, shift the extracted word left 8 bits
4383     // otherwise clear the bottom 8 bits if we need to do an or.
4384     if (Elt1 >= 0) {
4385       InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src,
4386                            DAG.getIntPtrConstant(Elt1 / 2));
4387       if ((Elt1 & 1) == 0)
4388         InsElt = DAG.getNode(ISD::SHL, dl, MVT::i16, InsElt,
4389                              DAG.getConstant(8, TLI.getShiftAmountTy()));
4390       else if (Elt0 >= 0)
4391         InsElt = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt,
4392                              DAG.getConstant(0xFF00, MVT::i16));
4393     }
4394     // If Elt0 is defined, extract it from the appropriate source.  If the
4395     // source byte is not also even, shift the extracted word right 8 bits. If
4396     // Elt1 was also defined, OR the extracted values together before
4397     // inserting them in the result.
4398     if (Elt0 >= 0) {
4399       SDValue InsElt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16,
4400                                     Elt0Src, DAG.getIntPtrConstant(Elt0 / 2));
4401       if ((Elt0 & 1) != 0)
4402         InsElt0 = DAG.getNode(ISD::SRL, dl, MVT::i16, InsElt0,
4403                               DAG.getConstant(8, TLI.getShiftAmountTy()));
4404       else if (Elt1 >= 0)
4405         InsElt0 = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt0,
4406                              DAG.getConstant(0x00FF, MVT::i16));
4407       InsElt = Elt1 >= 0 ? DAG.getNode(ISD::OR, dl, MVT::i16, InsElt, InsElt0)
4408                          : InsElt0;
4409     }
4410     NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt,
4411                        DAG.getIntPtrConstant(i));
4412   }
4413   return DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v16i8, NewV);
4414 }
4415
4416 /// RewriteAsNarrowerShuffle - Try rewriting v8i16 and v16i8 shuffles as 4 wide
4417 /// ones, or rewriting v4i32 / v2f32 as 2 wide ones if possible. This can be
4418 /// done when every pair / quad of shuffle mask elements point to elements in
4419 /// the right sequence. e.g.
4420 /// vector_shuffle <>, <>, < 3, 4, | 10, 11, | 0, 1, | 14, 15>
4421 static
4422 SDValue RewriteAsNarrowerShuffle(ShuffleVectorSDNode *SVOp,
4423                                  SelectionDAG &DAG,
4424                                  const TargetLowering &TLI, DebugLoc dl) {
4425   EVT VT = SVOp->getValueType(0);
4426   SDValue V1 = SVOp->getOperand(0);
4427   SDValue V2 = SVOp->getOperand(1);
4428   unsigned NumElems = VT.getVectorNumElements();
4429   unsigned NewWidth = (NumElems == 4) ? 2 : 4;
4430   EVT MaskVT = MVT::getIntVectorWithNumElements(NewWidth);
4431   EVT MaskEltVT = MaskVT.getVectorElementType();
4432   EVT NewVT = MaskVT;
4433   switch (VT.getSimpleVT().SimpleTy) {
4434   default: assert(false && "Unexpected!");
4435   case MVT::v4f32: NewVT = MVT::v2f64; break;
4436   case MVT::v4i32: NewVT = MVT::v2i64; break;
4437   case MVT::v8i16: NewVT = MVT::v4i32; break;
4438   case MVT::v16i8: NewVT = MVT::v4i32; break;
4439   }
4440
4441   if (NewWidth == 2) {
4442     if (VT.isInteger())
4443       NewVT = MVT::v2i64;
4444     else
4445       NewVT = MVT::v2f64;
4446   }
4447   int Scale = NumElems / NewWidth;
4448   SmallVector<int, 8> MaskVec;
4449   for (unsigned i = 0; i < NumElems; i += Scale) {
4450     int StartIdx = -1;
4451     for (int j = 0; j < Scale; ++j) {
4452       int EltIdx = SVOp->getMaskElt(i+j);
4453       if (EltIdx < 0)
4454         continue;
4455       if (StartIdx == -1)
4456         StartIdx = EltIdx - (EltIdx % Scale);
4457       if (EltIdx != StartIdx + j)
4458         return SDValue();
4459     }
4460     if (StartIdx == -1)
4461       MaskVec.push_back(-1);
4462     else
4463       MaskVec.push_back(StartIdx / Scale);
4464   }
4465
4466   V1 = DAG.getNode(ISD::BIT_CONVERT, dl, NewVT, V1);
4467   V2 = DAG.getNode(ISD::BIT_CONVERT, dl, NewVT, V2);
4468   return DAG.getVectorShuffle(NewVT, dl, V1, V2, &MaskVec[0]);
4469 }
4470
4471 /// getVZextMovL - Return a zero-extending vector move low node.
4472 ///
4473 static SDValue getVZextMovL(EVT VT, EVT OpVT,
4474                             SDValue SrcOp, SelectionDAG &DAG,
4475                             const X86Subtarget *Subtarget, DebugLoc dl) {
4476   if (VT == MVT::v2f64 || VT == MVT::v4f32) {
4477     LoadSDNode *LD = NULL;
4478     if (!isScalarLoadToVector(SrcOp.getNode(), &LD))
4479       LD = dyn_cast<LoadSDNode>(SrcOp);
4480     if (!LD) {
4481       // movssrr and movsdrr do not clear top bits. Try to use movd, movq
4482       // instead.
4483       MVT ExtVT = (OpVT == MVT::v2f64) ? MVT::i64 : MVT::i32;
4484       if ((ExtVT.SimpleTy != MVT::i64 || Subtarget->is64Bit()) &&
4485           SrcOp.getOpcode() == ISD::SCALAR_TO_VECTOR &&
4486           SrcOp.getOperand(0).getOpcode() == ISD::BIT_CONVERT &&
4487           SrcOp.getOperand(0).getOperand(0).getValueType() == ExtVT) {
4488         // PR2108
4489         OpVT = (OpVT == MVT::v2f64) ? MVT::v2i64 : MVT::v4i32;
4490         return DAG.getNode(ISD::BIT_CONVERT, dl, VT,
4491                            DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT,
4492                                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
4493                                                    OpVT,
4494                                                    SrcOp.getOperand(0)
4495                                                           .getOperand(0))));
4496       }
4497     }
4498   }
4499
4500   return DAG.getNode(ISD::BIT_CONVERT, dl, VT,
4501                      DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT,
4502                                  DAG.getNode(ISD::BIT_CONVERT, dl,
4503                                              OpVT, SrcOp)));
4504 }
4505
4506 /// LowerVECTOR_SHUFFLE_4wide - Handle all 4 wide cases with a number of
4507 /// shuffles.
4508 static SDValue
4509 LowerVECTOR_SHUFFLE_4wide(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
4510   SDValue V1 = SVOp->getOperand(0);
4511   SDValue V2 = SVOp->getOperand(1);
4512   DebugLoc dl = SVOp->getDebugLoc();
4513   EVT VT = SVOp->getValueType(0);
4514
4515   SmallVector<std::pair<int, int>, 8> Locs;
4516   Locs.resize(4);
4517   SmallVector<int, 8> Mask1(4U, -1);
4518   SmallVector<int, 8> PermMask;
4519   SVOp->getMask(PermMask);
4520
4521   unsigned NumHi = 0;
4522   unsigned NumLo = 0;
4523   for (unsigned i = 0; i != 4; ++i) {
4524     int Idx = PermMask[i];
4525     if (Idx < 0) {
4526       Locs[i] = std::make_pair(-1, -1);
4527     } else {
4528       assert(Idx < 8 && "Invalid VECTOR_SHUFFLE index!");
4529       if (Idx < 4) {
4530         Locs[i] = std::make_pair(0, NumLo);
4531         Mask1[NumLo] = Idx;
4532         NumLo++;
4533       } else {
4534         Locs[i] = std::make_pair(1, NumHi);
4535         if (2+NumHi < 4)
4536           Mask1[2+NumHi] = Idx;
4537         NumHi++;
4538       }
4539     }
4540   }
4541
4542   if (NumLo <= 2 && NumHi <= 2) {
4543     // If no more than two elements come from either vector. This can be
4544     // implemented with two shuffles. First shuffle gather the elements.
4545     // The second shuffle, which takes the first shuffle as both of its
4546     // vector operands, put the elements into the right order.
4547     V1 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
4548
4549     SmallVector<int, 8> Mask2(4U, -1);
4550
4551     for (unsigned i = 0; i != 4; ++i) {
4552       if (Locs[i].first == -1)
4553         continue;
4554       else {
4555         unsigned Idx = (i < 2) ? 0 : 4;
4556         Idx += Locs[i].first * 2 + Locs[i].second;
4557         Mask2[i] = Idx;
4558       }
4559     }
4560
4561     return DAG.getVectorShuffle(VT, dl, V1, V1, &Mask2[0]);
4562   } else if (NumLo == 3 || NumHi == 3) {
4563     // Otherwise, we must have three elements from one vector, call it X, and
4564     // one element from the other, call it Y.  First, use a shufps to build an
4565     // intermediate vector with the one element from Y and the element from X
4566     // that will be in the same half in the final destination (the indexes don't
4567     // matter). Then, use a shufps to build the final vector, taking the half
4568     // containing the element from Y from the intermediate, and the other half
4569     // from X.
4570     if (NumHi == 3) {
4571       // Normalize it so the 3 elements come from V1.
4572       CommuteVectorShuffleMask(PermMask, VT);
4573       std::swap(V1, V2);
4574     }
4575
4576     // Find the element from V2.
4577     unsigned HiIndex;
4578     for (HiIndex = 0; HiIndex < 3; ++HiIndex) {
4579       int Val = PermMask[HiIndex];
4580       if (Val < 0)
4581         continue;
4582       if (Val >= 4)
4583         break;
4584     }
4585
4586     Mask1[0] = PermMask[HiIndex];
4587     Mask1[1] = -1;
4588     Mask1[2] = PermMask[HiIndex^1];
4589     Mask1[3] = -1;
4590     V2 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
4591
4592     if (HiIndex >= 2) {
4593       Mask1[0] = PermMask[0];
4594       Mask1[1] = PermMask[1];
4595       Mask1[2] = HiIndex & 1 ? 6 : 4;
4596       Mask1[3] = HiIndex & 1 ? 4 : 6;
4597       return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
4598     } else {
4599       Mask1[0] = HiIndex & 1 ? 2 : 0;
4600       Mask1[1] = HiIndex & 1 ? 0 : 2;
4601       Mask1[2] = PermMask[2];
4602       Mask1[3] = PermMask[3];
4603       if (Mask1[2] >= 0)
4604         Mask1[2] += 4;
4605       if (Mask1[3] >= 0)
4606         Mask1[3] += 4;
4607       return DAG.getVectorShuffle(VT, dl, V2, V1, &Mask1[0]);
4608     }
4609   }
4610
4611   // Break it into (shuffle shuffle_hi, shuffle_lo).
4612   Locs.clear();
4613   SmallVector<int,8> LoMask(4U, -1);
4614   SmallVector<int,8> HiMask(4U, -1);
4615
4616   SmallVector<int,8> *MaskPtr = &LoMask;
4617   unsigned MaskIdx = 0;
4618   unsigned LoIdx = 0;
4619   unsigned HiIdx = 2;
4620   for (unsigned i = 0; i != 4; ++i) {
4621     if (i == 2) {
4622       MaskPtr = &HiMask;
4623       MaskIdx = 1;
4624       LoIdx = 0;
4625       HiIdx = 2;
4626     }
4627     int Idx = PermMask[i];
4628     if (Idx < 0) {
4629       Locs[i] = std::make_pair(-1, -1);
4630     } else if (Idx < 4) {
4631       Locs[i] = std::make_pair(MaskIdx, LoIdx);
4632       (*MaskPtr)[LoIdx] = Idx;
4633       LoIdx++;
4634     } else {
4635       Locs[i] = std::make_pair(MaskIdx, HiIdx);
4636       (*MaskPtr)[HiIdx] = Idx;
4637       HiIdx++;
4638     }
4639   }
4640
4641   SDValue LoShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &LoMask[0]);
4642   SDValue HiShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &HiMask[0]);
4643   SmallVector<int, 8> MaskOps;
4644   for (unsigned i = 0; i != 4; ++i) {
4645     if (Locs[i].first == -1) {
4646       MaskOps.push_back(-1);
4647     } else {
4648       unsigned Idx = Locs[i].first * 4 + Locs[i].second;
4649       MaskOps.push_back(Idx);
4650     }
4651   }
4652   return DAG.getVectorShuffle(VT, dl, LoShuffle, HiShuffle, &MaskOps[0]);
4653 }
4654
4655 SDValue
4656 X86TargetLowering::LowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG) const {
4657   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
4658   SDValue V1 = Op.getOperand(0);
4659   SDValue V2 = Op.getOperand(1);
4660   EVT VT = Op.getValueType();
4661   DebugLoc dl = Op.getDebugLoc();
4662   unsigned NumElems = VT.getVectorNumElements();
4663   bool isMMX = VT.getSizeInBits() == 64;
4664   bool V1IsUndef = V1.getOpcode() == ISD::UNDEF;
4665   bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
4666   bool V1IsSplat = false;
4667   bool V2IsSplat = false;
4668
4669   if (isZeroShuffle(SVOp))
4670     return getZeroVector(VT, Subtarget->hasSSE2(), DAG, dl);
4671
4672   // Promote splats to v4f32.
4673   if (SVOp->isSplat()) {
4674     if (isMMX || NumElems < 4)
4675       return Op;
4676     return PromoteSplat(SVOp, DAG, Subtarget->hasSSE2());
4677   }
4678
4679   // If the shuffle can be profitably rewritten as a narrower shuffle, then
4680   // do it!
4681   if (VT == MVT::v8i16 || VT == MVT::v16i8) {
4682     SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG, *this, dl);
4683     if (NewOp.getNode())
4684       return DAG.getNode(ISD::BIT_CONVERT, dl, VT,
4685                          LowerVECTOR_SHUFFLE(NewOp, DAG));
4686   } else if ((VT == MVT::v4i32 || (VT == MVT::v4f32 && Subtarget->hasSSE2()))) {
4687     // FIXME: Figure out a cleaner way to do this.
4688     // Try to make use of movq to zero out the top part.
4689     if (ISD::isBuildVectorAllZeros(V2.getNode())) {
4690       SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG, *this, dl);
4691       if (NewOp.getNode()) {
4692         if (isCommutedMOVL(cast<ShuffleVectorSDNode>(NewOp), true, false))
4693           return getVZextMovL(VT, NewOp.getValueType(), NewOp.getOperand(0),
4694                               DAG, Subtarget, dl);
4695       }
4696     } else if (ISD::isBuildVectorAllZeros(V1.getNode())) {
4697       SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG, *this, dl);
4698       if (NewOp.getNode() && X86::isMOVLMask(cast<ShuffleVectorSDNode>(NewOp)))
4699         return getVZextMovL(VT, NewOp.getValueType(), NewOp.getOperand(1),
4700                             DAG, Subtarget, dl);
4701     }
4702   }
4703
4704   if (X86::isPSHUFDMask(SVOp))
4705     return Op;
4706
4707   // Check if this can be converted into a logical shift.
4708   bool isLeft = false;
4709   unsigned ShAmt = 0;
4710   SDValue ShVal;
4711   bool isShift = getSubtarget()->hasSSE2() &&
4712     isVectorShift(SVOp, DAG, isLeft, ShVal, ShAmt);
4713   if (isShift && ShVal.hasOneUse()) {
4714     // If the shifted value has multiple uses, it may be cheaper to use
4715     // v_set0 + movlhps or movhlps, etc.
4716     EVT EltVT = VT.getVectorElementType();
4717     ShAmt *= EltVT.getSizeInBits();
4718     return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
4719   }
4720
4721   if (X86::isMOVLMask(SVOp)) {
4722     if (V1IsUndef)
4723       return V2;
4724     if (ISD::isBuildVectorAllZeros(V1.getNode()))
4725       return getVZextMovL(VT, VT, V2, DAG, Subtarget, dl);
4726     if (!isMMX)
4727       return Op;
4728   }
4729
4730   // FIXME: fold these into legal mask.
4731   if (!isMMX && (X86::isMOVSHDUPMask(SVOp) ||
4732                  X86::isMOVSLDUPMask(SVOp) ||
4733                  X86::isMOVHLPSMask(SVOp) ||
4734                  X86::isMOVLHPSMask(SVOp) ||
4735                  X86::isMOVLPMask(SVOp)))
4736     return Op;
4737
4738   if (ShouldXformToMOVHLPS(SVOp) ||
4739       ShouldXformToMOVLP(V1.getNode(), V2.getNode(), SVOp))
4740     return CommuteVectorShuffle(SVOp, DAG);
4741
4742   if (isShift) {
4743     // No better options. Use a vshl / vsrl.
4744     EVT EltVT = VT.getVectorElementType();
4745     ShAmt *= EltVT.getSizeInBits();
4746     return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
4747   }
4748
4749   bool Commuted = false;
4750   // FIXME: This should also accept a bitcast of a splat?  Be careful, not
4751   // 1,1,1,1 -> v8i16 though.
4752   V1IsSplat = isSplatVector(V1.getNode());
4753   V2IsSplat = isSplatVector(V2.getNode());
4754
4755   // Canonicalize the splat or undef, if present, to be on the RHS.
4756   if ((V1IsSplat || V1IsUndef) && !(V2IsSplat || V2IsUndef)) {
4757     Op = CommuteVectorShuffle(SVOp, DAG);
4758     SVOp = cast<ShuffleVectorSDNode>(Op);
4759     V1 = SVOp->getOperand(0);
4760     V2 = SVOp->getOperand(1);
4761     std::swap(V1IsSplat, V2IsSplat);
4762     std::swap(V1IsUndef, V2IsUndef);
4763     Commuted = true;
4764   }
4765
4766   if (isCommutedMOVL(SVOp, V2IsSplat, V2IsUndef)) {
4767     // Shuffling low element of v1 into undef, just return v1.
4768     if (V2IsUndef)
4769       return V1;
4770     // If V2 is a splat, the mask may be malformed such as <4,3,3,3>, which
4771     // the instruction selector will not match, so get a canonical MOVL with
4772     // swapped operands to undo the commute.
4773     return getMOVL(DAG, dl, VT, V2, V1);
4774   }
4775
4776   if (X86::isUNPCKL_v_undef_Mask(SVOp) ||
4777       X86::isUNPCKH_v_undef_Mask(SVOp) ||
4778       X86::isUNPCKLMask(SVOp) ||
4779       X86::isUNPCKHMask(SVOp))
4780     return Op;
4781
4782   if (V2IsSplat) {
4783     // Normalize mask so all entries that point to V2 points to its first
4784     // element then try to match unpck{h|l} again. If match, return a
4785     // new vector_shuffle with the corrected mask.
4786     SDValue NewMask = NormalizeMask(SVOp, DAG);
4787     ShuffleVectorSDNode *NSVOp = cast<ShuffleVectorSDNode>(NewMask);
4788     if (NSVOp != SVOp) {
4789       if (X86::isUNPCKLMask(NSVOp, true)) {
4790         return NewMask;
4791       } else if (X86::isUNPCKHMask(NSVOp, true)) {
4792         return NewMask;
4793       }
4794     }
4795   }
4796
4797   if (Commuted) {
4798     // Commute is back and try unpck* again.
4799     // FIXME: this seems wrong.
4800     SDValue NewOp = CommuteVectorShuffle(SVOp, DAG);
4801     ShuffleVectorSDNode *NewSVOp = cast<ShuffleVectorSDNode>(NewOp);
4802     if (X86::isUNPCKL_v_undef_Mask(NewSVOp) ||
4803         X86::isUNPCKH_v_undef_Mask(NewSVOp) ||
4804         X86::isUNPCKLMask(NewSVOp) ||
4805         X86::isUNPCKHMask(NewSVOp))
4806       return NewOp;
4807   }
4808
4809   // FIXME: for mmx, bitcast v2i32 to v4i16 for shuffle.
4810
4811   // Normalize the node to match x86 shuffle ops if needed
4812   if (!isMMX && V2.getOpcode() != ISD::UNDEF && isCommutedSHUFP(SVOp))
4813     return CommuteVectorShuffle(SVOp, DAG);
4814
4815   // Check for legal shuffle and return?
4816   SmallVector<int, 16> PermMask;
4817   SVOp->getMask(PermMask);
4818   if (isShuffleMaskLegal(PermMask, VT))
4819     return Op;
4820
4821   // Handle v8i16 specifically since SSE can do byte extraction and insertion.
4822   if (VT == MVT::v8i16) {
4823     SDValue NewOp = LowerVECTOR_SHUFFLEv8i16(SVOp, DAG, *this);
4824     if (NewOp.getNode())
4825       return NewOp;
4826   }
4827
4828   if (VT == MVT::v16i8) {
4829     SDValue NewOp = LowerVECTOR_SHUFFLEv16i8(SVOp, DAG, *this);
4830     if (NewOp.getNode())
4831       return NewOp;
4832   }
4833
4834   // Handle all 4 wide cases with a number of shuffles except for MMX.
4835   if (NumElems == 4 && !isMMX)
4836     return LowerVECTOR_SHUFFLE_4wide(SVOp, DAG);
4837
4838   return SDValue();
4839 }
4840
4841 SDValue
4842 X86TargetLowering::LowerEXTRACT_VECTOR_ELT_SSE4(SDValue Op,
4843                                                 SelectionDAG &DAG) const {
4844   EVT VT = Op.getValueType();
4845   DebugLoc dl = Op.getDebugLoc();
4846   if (VT.getSizeInBits() == 8) {
4847     SDValue Extract = DAG.getNode(X86ISD::PEXTRB, dl, MVT::i32,
4848                                     Op.getOperand(0), Op.getOperand(1));
4849     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
4850                                     DAG.getValueType(VT));
4851     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
4852   } else if (VT.getSizeInBits() == 16) {
4853     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
4854     // If Idx is 0, it's cheaper to do a move instead of a pextrw.
4855     if (Idx == 0)
4856       return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
4857                          DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
4858                                      DAG.getNode(ISD::BIT_CONVERT, dl,
4859                                                  MVT::v4i32,
4860                                                  Op.getOperand(0)),
4861                                      Op.getOperand(1)));
4862     SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, MVT::i32,
4863                                     Op.getOperand(0), Op.getOperand(1));
4864     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
4865                                     DAG.getValueType(VT));
4866     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
4867   } else if (VT == MVT::f32) {
4868     // EXTRACTPS outputs to a GPR32 register which will require a movd to copy
4869     // the result back to FR32 register. It's only worth matching if the
4870     // result has a single use which is a store or a bitcast to i32.  And in
4871     // the case of a store, it's not worth it if the index is a constant 0,
4872     // because a MOVSSmr can be used instead, which is smaller and faster.
4873     if (!Op.hasOneUse())
4874       return SDValue();
4875     SDNode *User = *Op.getNode()->use_begin();
4876     if ((User->getOpcode() != ISD::STORE ||
4877          (isa<ConstantSDNode>(Op.getOperand(1)) &&
4878           cast<ConstantSDNode>(Op.getOperand(1))->isNullValue())) &&
4879         (User->getOpcode() != ISD::BIT_CONVERT ||
4880          User->getValueType(0) != MVT::i32))
4881       return SDValue();
4882     SDValue Extract = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
4883                                   DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v4i32,
4884                                               Op.getOperand(0)),
4885                                               Op.getOperand(1));
4886     return DAG.getNode(ISD::BIT_CONVERT, dl, MVT::f32, Extract);
4887   } else if (VT == MVT::i32) {
4888     // ExtractPS works with constant index.
4889     if (isa<ConstantSDNode>(Op.getOperand(1)))
4890       return Op;
4891   }
4892   return SDValue();
4893 }
4894
4895
4896 SDValue
4897 X86TargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op,
4898                                            SelectionDAG &DAG) const {
4899   if (!isa<ConstantSDNode>(Op.getOperand(1)))
4900     return SDValue();
4901
4902   if (Subtarget->hasSSE41()) {
4903     SDValue Res = LowerEXTRACT_VECTOR_ELT_SSE4(Op, DAG);
4904     if (Res.getNode())
4905       return Res;
4906   }
4907
4908   EVT VT = Op.getValueType();
4909   DebugLoc dl = Op.getDebugLoc();
4910   // TODO: handle v16i8.
4911   if (VT.getSizeInBits() == 16) {
4912     SDValue Vec = Op.getOperand(0);
4913     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
4914     if (Idx == 0)
4915       return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
4916                          DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
4917                                      DAG.getNode(ISD::BIT_CONVERT, dl,
4918                                                  MVT::v4i32, Vec),
4919                                      Op.getOperand(1)));
4920     // Transform it so it match pextrw which produces a 32-bit result.
4921     EVT EltVT = MVT::i32;
4922     SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, EltVT,
4923                                     Op.getOperand(0), Op.getOperand(1));
4924     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, EltVT, Extract,
4925                                     DAG.getValueType(VT));
4926     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
4927   } else if (VT.getSizeInBits() == 32) {
4928     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
4929     if (Idx == 0)
4930       return Op;
4931
4932     // SHUFPS the element to the lowest double word, then movss.
4933     int Mask[4] = { Idx, -1, -1, -1 };
4934     EVT VVT = Op.getOperand(0).getValueType();
4935     SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
4936                                        DAG.getUNDEF(VVT), Mask);
4937     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
4938                        DAG.getIntPtrConstant(0));
4939   } else if (VT.getSizeInBits() == 64) {
4940     // FIXME: .td only matches this for <2 x f64>, not <2 x i64> on 32b
4941     // FIXME: seems like this should be unnecessary if mov{h,l}pd were taught
4942     //        to match extract_elt for f64.
4943     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
4944     if (Idx == 0)
4945       return Op;
4946
4947     // UNPCKHPD the element to the lowest double word, then movsd.
4948     // Note if the lower 64 bits of the result of the UNPCKHPD is then stored
4949     // to a f64mem, the whole operation is folded into a single MOVHPDmr.
4950     int Mask[2] = { 1, -1 };
4951     EVT VVT = Op.getOperand(0).getValueType();
4952     SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
4953                                        DAG.getUNDEF(VVT), Mask);
4954     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
4955                        DAG.getIntPtrConstant(0));
4956   }
4957
4958   return SDValue();
4959 }
4960
4961 SDValue
4962 X86TargetLowering::LowerINSERT_VECTOR_ELT_SSE4(SDValue Op,
4963                                                SelectionDAG &DAG) const {
4964   EVT VT = Op.getValueType();
4965   EVT EltVT = VT.getVectorElementType();
4966   DebugLoc dl = Op.getDebugLoc();
4967
4968   SDValue N0 = Op.getOperand(0);
4969   SDValue N1 = Op.getOperand(1);
4970   SDValue N2 = Op.getOperand(2);
4971
4972   if ((EltVT.getSizeInBits() == 8 || EltVT.getSizeInBits() == 16) &&
4973       isa<ConstantSDNode>(N2)) {
4974     unsigned Opc;
4975     if (VT == MVT::v8i16)
4976       Opc = X86ISD::PINSRW;
4977     else if (VT == MVT::v4i16)
4978       Opc = X86ISD::MMX_PINSRW;
4979     else if (VT == MVT::v16i8)
4980       Opc = X86ISD::PINSRB;
4981     else
4982       Opc = X86ISD::PINSRB;
4983
4984     // Transform it so it match pinsr{b,w} which expects a GR32 as its second
4985     // argument.
4986     if (N1.getValueType() != MVT::i32)
4987       N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
4988     if (N2.getValueType() != MVT::i32)
4989       N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue());
4990     return DAG.getNode(Opc, dl, VT, N0, N1, N2);
4991   } else if (EltVT == MVT::f32 && isa<ConstantSDNode>(N2)) {
4992     // Bits [7:6] of the constant are the source select.  This will always be
4993     //  zero here.  The DAG Combiner may combine an extract_elt index into these
4994     //  bits.  For example (insert (extract, 3), 2) could be matched by putting
4995     //  the '3' into bits [7:6] of X86ISD::INSERTPS.
4996     // Bits [5:4] of the constant are the destination select.  This is the
4997     //  value of the incoming immediate.
4998     // Bits [3:0] of the constant are the zero mask.  The DAG Combiner may
4999     //   combine either bitwise AND or insert of float 0.0 to set these bits.
5000     N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue() << 4);
5001     // Create this as a scalar to vector..
5002     N1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4f32, N1);
5003     return DAG.getNode(X86ISD::INSERTPS, dl, VT, N0, N1, N2);
5004   } else if (EltVT == MVT::i32 && isa<ConstantSDNode>(N2)) {
5005     // PINSR* works with constant index.
5006     return Op;
5007   }
5008   return SDValue();
5009 }
5010
5011 SDValue
5012 X86TargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) const {
5013   EVT VT = Op.getValueType();
5014   EVT EltVT = VT.getVectorElementType();
5015
5016   if (Subtarget->hasSSE41())
5017     return LowerINSERT_VECTOR_ELT_SSE4(Op, DAG);
5018
5019   if (EltVT == MVT::i8)
5020     return SDValue();
5021
5022   DebugLoc dl = Op.getDebugLoc();
5023   SDValue N0 = Op.getOperand(0);
5024   SDValue N1 = Op.getOperand(1);
5025   SDValue N2 = Op.getOperand(2);
5026
5027   if (EltVT.getSizeInBits() == 16 && isa<ConstantSDNode>(N2)) {
5028     // Transform it so it match pinsrw which expects a 16-bit value in a GR32
5029     // as its second argument.
5030     if (N1.getValueType() != MVT::i32)
5031       N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
5032     if (N2.getValueType() != MVT::i32)
5033       N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue());
5034     return DAG.getNode(VT == MVT::v8i16 ? X86ISD::PINSRW : X86ISD::MMX_PINSRW,
5035                        dl, VT, N0, N1, N2);
5036   }
5037   return SDValue();
5038 }
5039
5040 SDValue
5041 X86TargetLowering::LowerSCALAR_TO_VECTOR(SDValue Op, SelectionDAG &DAG) const {
5042   DebugLoc dl = Op.getDebugLoc();
5043   if (Op.getValueType() == MVT::v2f32)
5044     return DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v2f32,
5045                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i32,
5046                                    DAG.getNode(ISD::BIT_CONVERT, dl, MVT::i32,
5047                                                Op.getOperand(0))));
5048
5049   if (Op.getValueType() == MVT::v1i64 && Op.getOperand(0).getValueType() == MVT::i64)
5050     return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v1i64, Op.getOperand(0));
5051
5052   SDValue AnyExt = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, Op.getOperand(0));
5053   EVT VT = MVT::v2i32;
5054   switch (Op.getValueType().getSimpleVT().SimpleTy) {
5055   default: break;
5056   case MVT::v16i8:
5057   case MVT::v8i16:
5058     VT = MVT::v4i32;
5059     break;
5060   }
5061   return DAG.getNode(ISD::BIT_CONVERT, dl, Op.getValueType(),
5062                      DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, AnyExt));
5063 }
5064
5065 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
5066 // their target countpart wrapped in the X86ISD::Wrapper node. Suppose N is
5067 // one of the above mentioned nodes. It has to be wrapped because otherwise
5068 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
5069 // be used to form addressing mode. These wrapped nodes will be selected
5070 // into MOV32ri.
5071 SDValue
5072 X86TargetLowering::LowerConstantPool(SDValue Op, SelectionDAG &DAG) const {
5073   ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
5074
5075   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
5076   // global base reg.
5077   unsigned char OpFlag = 0;
5078   unsigned WrapperKind = X86ISD::Wrapper;
5079   CodeModel::Model M = getTargetMachine().getCodeModel();
5080
5081   if (Subtarget->isPICStyleRIPRel() &&
5082       (M == CodeModel::Small || M == CodeModel::Kernel))
5083     WrapperKind = X86ISD::WrapperRIP;
5084   else if (Subtarget->isPICStyleGOT())
5085     OpFlag = X86II::MO_GOTOFF;
5086   else if (Subtarget->isPICStyleStubPIC())
5087     OpFlag = X86II::MO_PIC_BASE_OFFSET;
5088
5089   SDValue Result = DAG.getTargetConstantPool(CP->getConstVal(), getPointerTy(),
5090                                              CP->getAlignment(),
5091                                              CP->getOffset(), OpFlag);
5092   DebugLoc DL = CP->getDebugLoc();
5093   Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
5094   // With PIC, the address is actually $g + Offset.
5095   if (OpFlag) {
5096     Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
5097                          DAG.getNode(X86ISD::GlobalBaseReg,
5098                                      DebugLoc(), getPointerTy()),
5099                          Result);
5100   }
5101
5102   return Result;
5103 }
5104
5105 SDValue X86TargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) const {
5106   JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
5107
5108   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
5109   // global base reg.
5110   unsigned char OpFlag = 0;
5111   unsigned WrapperKind = X86ISD::Wrapper;
5112   CodeModel::Model M = getTargetMachine().getCodeModel();
5113
5114   if (Subtarget->isPICStyleRIPRel() &&
5115       (M == CodeModel::Small || M == CodeModel::Kernel))
5116     WrapperKind = X86ISD::WrapperRIP;
5117   else if (Subtarget->isPICStyleGOT())
5118     OpFlag = X86II::MO_GOTOFF;
5119   else if (Subtarget->isPICStyleStubPIC())
5120     OpFlag = X86II::MO_PIC_BASE_OFFSET;
5121
5122   SDValue Result = DAG.getTargetJumpTable(JT->getIndex(), getPointerTy(),
5123                                           OpFlag);
5124   DebugLoc DL = JT->getDebugLoc();
5125   Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
5126
5127   // With PIC, the address is actually $g + Offset.
5128   if (OpFlag) {
5129     Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
5130                          DAG.getNode(X86ISD::GlobalBaseReg,
5131                                      DebugLoc(), getPointerTy()),
5132                          Result);
5133   }
5134
5135   return Result;
5136 }
5137
5138 SDValue
5139 X86TargetLowering::LowerExternalSymbol(SDValue Op, SelectionDAG &DAG) const {
5140   const char *Sym = cast<ExternalSymbolSDNode>(Op)->getSymbol();
5141
5142   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
5143   // global base reg.
5144   unsigned char OpFlag = 0;
5145   unsigned WrapperKind = X86ISD::Wrapper;
5146   CodeModel::Model M = getTargetMachine().getCodeModel();
5147
5148   if (Subtarget->isPICStyleRIPRel() &&
5149       (M == CodeModel::Small || M == CodeModel::Kernel))
5150     WrapperKind = X86ISD::WrapperRIP;
5151   else if (Subtarget->isPICStyleGOT())
5152     OpFlag = X86II::MO_GOTOFF;
5153   else if (Subtarget->isPICStyleStubPIC())
5154     OpFlag = X86II::MO_PIC_BASE_OFFSET;
5155
5156   SDValue Result = DAG.getTargetExternalSymbol(Sym, getPointerTy(), OpFlag);
5157
5158   DebugLoc DL = Op.getDebugLoc();
5159   Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
5160
5161
5162   // With PIC, the address is actually $g + Offset.
5163   if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
5164       !Subtarget->is64Bit()) {
5165     Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
5166                          DAG.getNode(X86ISD::GlobalBaseReg,
5167                                      DebugLoc(), getPointerTy()),
5168                          Result);
5169   }
5170
5171   return Result;
5172 }
5173
5174 SDValue
5175 X86TargetLowering::LowerBlockAddress(SDValue Op, SelectionDAG &DAG) const {
5176   // Create the TargetBlockAddressAddress node.
5177   unsigned char OpFlags =
5178     Subtarget->ClassifyBlockAddressReference();
5179   CodeModel::Model M = getTargetMachine().getCodeModel();
5180   const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
5181   DebugLoc dl = Op.getDebugLoc();
5182   SDValue Result = DAG.getBlockAddress(BA, getPointerTy(),
5183                                        /*isTarget=*/true, OpFlags);
5184
5185   if (Subtarget->isPICStyleRIPRel() &&
5186       (M == CodeModel::Small || M == CodeModel::Kernel))
5187     Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
5188   else
5189     Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
5190
5191   // With PIC, the address is actually $g + Offset.
5192   if (isGlobalRelativeToPICBase(OpFlags)) {
5193     Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
5194                          DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
5195                          Result);
5196   }
5197
5198   return Result;
5199 }
5200
5201 SDValue
5202 X86TargetLowering::LowerGlobalAddress(const GlobalValue *GV, DebugLoc dl,
5203                                       int64_t Offset,
5204                                       SelectionDAG &DAG) const {
5205   // Create the TargetGlobalAddress node, folding in the constant
5206   // offset if it is legal.
5207   unsigned char OpFlags =
5208     Subtarget->ClassifyGlobalReference(GV, getTargetMachine());
5209   CodeModel::Model M = getTargetMachine().getCodeModel();
5210   SDValue Result;
5211   if (OpFlags == X86II::MO_NO_FLAG &&
5212       X86::isOffsetSuitableForCodeModel(Offset, M)) {
5213     // A direct static reference to a global.
5214     Result = DAG.getTargetGlobalAddress(GV, getPointerTy(), Offset);
5215     Offset = 0;
5216   } else {
5217     Result = DAG.getTargetGlobalAddress(GV, getPointerTy(), 0, OpFlags);
5218   }
5219
5220   if (Subtarget->isPICStyleRIPRel() &&
5221       (M == CodeModel::Small || M == CodeModel::Kernel))
5222     Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
5223   else
5224     Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
5225
5226   // With PIC, the address is actually $g + Offset.
5227   if (isGlobalRelativeToPICBase(OpFlags)) {
5228     Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
5229                          DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
5230                          Result);
5231   }
5232
5233   // For globals that require a load from a stub to get the address, emit the
5234   // load.
5235   if (isGlobalStubReference(OpFlags))
5236     Result = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Result,
5237                          PseudoSourceValue::getGOT(), 0, false, false, 0);
5238
5239   // If there was a non-zero offset that we didn't fold, create an explicit
5240   // addition for it.
5241   if (Offset != 0)
5242     Result = DAG.getNode(ISD::ADD, dl, getPointerTy(), Result,
5243                          DAG.getConstant(Offset, getPointerTy()));
5244
5245   return Result;
5246 }
5247
5248 SDValue
5249 X86TargetLowering::LowerGlobalAddress(SDValue Op, SelectionDAG &DAG) const {
5250   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
5251   int64_t Offset = cast<GlobalAddressSDNode>(Op)->getOffset();
5252   return LowerGlobalAddress(GV, Op.getDebugLoc(), Offset, DAG);
5253 }
5254
5255 static SDValue
5256 GetTLSADDR(SelectionDAG &DAG, SDValue Chain, GlobalAddressSDNode *GA,
5257            SDValue *InFlag, const EVT PtrVT, unsigned ReturnReg,
5258            unsigned char OperandFlags) {
5259   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
5260   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Flag);
5261   DebugLoc dl = GA->getDebugLoc();
5262   SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(),
5263                                            GA->getValueType(0),
5264                                            GA->getOffset(),
5265                                            OperandFlags);
5266   if (InFlag) {
5267     SDValue Ops[] = { Chain,  TGA, *InFlag };
5268     Chain = DAG.getNode(X86ISD::TLSADDR, dl, NodeTys, Ops, 3);
5269   } else {
5270     SDValue Ops[]  = { Chain, TGA };
5271     Chain = DAG.getNode(X86ISD::TLSADDR, dl, NodeTys, Ops, 2);
5272   }
5273
5274   // TLSADDR will be codegen'ed as call. Inform MFI that function has calls.
5275   MFI->setHasCalls(true);
5276
5277   SDValue Flag = Chain.getValue(1);
5278   return DAG.getCopyFromReg(Chain, dl, ReturnReg, PtrVT, Flag);
5279 }
5280
5281 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 32 bit
5282 static SDValue
5283 LowerToTLSGeneralDynamicModel32(GlobalAddressSDNode *GA, SelectionDAG &DAG,
5284                                 const EVT PtrVT) {
5285   SDValue InFlag;
5286   DebugLoc dl = GA->getDebugLoc();  // ? function entry point might be better
5287   SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
5288                                      DAG.getNode(X86ISD::GlobalBaseReg,
5289                                                  DebugLoc(), PtrVT), InFlag);
5290   InFlag = Chain.getValue(1);
5291
5292   return GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX, X86II::MO_TLSGD);
5293 }
5294
5295 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 64 bit
5296 static SDValue
5297 LowerToTLSGeneralDynamicModel64(GlobalAddressSDNode *GA, SelectionDAG &DAG,
5298                                 const EVT PtrVT) {
5299   return GetTLSADDR(DAG, DAG.getEntryNode(), GA, NULL, PtrVT,
5300                     X86::RAX, X86II::MO_TLSGD);
5301 }
5302
5303 // Lower ISD::GlobalTLSAddress using the "initial exec" (for no-pic) or
5304 // "local exec" model.
5305 static SDValue LowerToTLSExecModel(GlobalAddressSDNode *GA, SelectionDAG &DAG,
5306                                    const EVT PtrVT, TLSModel::Model model,
5307                                    bool is64Bit) {
5308   DebugLoc dl = GA->getDebugLoc();
5309   // Get the Thread Pointer
5310   SDValue Base = DAG.getNode(X86ISD::SegmentBaseAddress,
5311                              DebugLoc(), PtrVT,
5312                              DAG.getRegister(is64Bit? X86::FS : X86::GS,
5313                                              MVT::i32));
5314
5315   SDValue ThreadPointer = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Base,
5316                                       NULL, 0, false, false, 0);
5317
5318   unsigned char OperandFlags = 0;
5319   // Most TLS accesses are not RIP relative, even on x86-64.  One exception is
5320   // initialexec.
5321   unsigned WrapperKind = X86ISD::Wrapper;
5322   if (model == TLSModel::LocalExec) {
5323     OperandFlags = is64Bit ? X86II::MO_TPOFF : X86II::MO_NTPOFF;
5324   } else if (is64Bit) {
5325     assert(model == TLSModel::InitialExec);
5326     OperandFlags = X86II::MO_GOTTPOFF;
5327     WrapperKind = X86ISD::WrapperRIP;
5328   } else {
5329     assert(model == TLSModel::InitialExec);
5330     OperandFlags = X86II::MO_INDNTPOFF;
5331   }
5332
5333   // emit "addl x@ntpoff,%eax" (local exec) or "addl x@indntpoff,%eax" (initial
5334   // exec)
5335   SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), GA->getValueType(0),
5336                                            GA->getOffset(), OperandFlags);
5337   SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
5338
5339   if (model == TLSModel::InitialExec)
5340     Offset = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Offset,
5341                          PseudoSourceValue::getGOT(), 0, false, false, 0);
5342
5343   // The address of the thread local variable is the add of the thread
5344   // pointer with the offset of the variable.
5345   return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
5346 }
5347
5348 SDValue
5349 X86TargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const {
5350   // TODO: implement the "local dynamic" model
5351   // TODO: implement the "initial exec"model for pic executables
5352   assert(Subtarget->isTargetELF() &&
5353          "TLS not implemented for non-ELF targets");
5354   GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
5355   const GlobalValue *GV = GA->getGlobal();
5356
5357   // If GV is an alias then use the aliasee for determining
5358   // thread-localness.
5359   if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(GV))
5360     GV = GA->resolveAliasedGlobal(false);
5361
5362   TLSModel::Model model = getTLSModel(GV,
5363                                       getTargetMachine().getRelocationModel());
5364
5365   switch (model) {
5366   case TLSModel::GeneralDynamic:
5367   case TLSModel::LocalDynamic: // not implemented
5368     if (Subtarget->is64Bit())
5369       return LowerToTLSGeneralDynamicModel64(GA, DAG, getPointerTy());
5370     return LowerToTLSGeneralDynamicModel32(GA, DAG, getPointerTy());
5371
5372   case TLSModel::InitialExec:
5373   case TLSModel::LocalExec:
5374     return LowerToTLSExecModel(GA, DAG, getPointerTy(), model,
5375                                Subtarget->is64Bit());
5376   }
5377
5378   llvm_unreachable("Unreachable");
5379   return SDValue();
5380 }
5381
5382
5383 /// LowerShift - Lower SRA_PARTS and friends, which return two i32 values and
5384 /// take a 2 x i32 value to shift plus a shift amount.
5385 SDValue X86TargetLowering::LowerShift(SDValue Op, SelectionDAG &DAG) const {
5386   assert(Op.getNumOperands() == 3 && "Not a double-shift!");
5387   EVT VT = Op.getValueType();
5388   unsigned VTBits = VT.getSizeInBits();
5389   DebugLoc dl = Op.getDebugLoc();
5390   bool isSRA = Op.getOpcode() == ISD::SRA_PARTS;
5391   SDValue ShOpLo = Op.getOperand(0);
5392   SDValue ShOpHi = Op.getOperand(1);
5393   SDValue ShAmt  = Op.getOperand(2);
5394   SDValue Tmp1 = isSRA ? DAG.getNode(ISD::SRA, dl, VT, ShOpHi,
5395                                      DAG.getConstant(VTBits - 1, MVT::i8))
5396                        : DAG.getConstant(0, VT);
5397
5398   SDValue Tmp2, Tmp3;
5399   if (Op.getOpcode() == ISD::SHL_PARTS) {
5400     Tmp2 = DAG.getNode(X86ISD::SHLD, dl, VT, ShOpHi, ShOpLo, ShAmt);
5401     Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ShAmt);
5402   } else {
5403     Tmp2 = DAG.getNode(X86ISD::SHRD, dl, VT, ShOpLo, ShOpHi, ShAmt);
5404     Tmp3 = DAG.getNode(isSRA ? ISD::SRA : ISD::SRL, dl, VT, ShOpHi, ShAmt);
5405   }
5406
5407   SDValue AndNode = DAG.getNode(ISD::AND, dl, MVT::i8, ShAmt,
5408                                 DAG.getConstant(VTBits, MVT::i8));
5409   SDValue Cond = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
5410                              AndNode, DAG.getConstant(0, MVT::i8));
5411
5412   SDValue Hi, Lo;
5413   SDValue CC = DAG.getConstant(X86::COND_NE, MVT::i8);
5414   SDValue Ops0[4] = { Tmp2, Tmp3, CC, Cond };
5415   SDValue Ops1[4] = { Tmp3, Tmp1, CC, Cond };
5416
5417   if (Op.getOpcode() == ISD::SHL_PARTS) {
5418     Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0, 4);
5419     Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1, 4);
5420   } else {
5421     Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0, 4);
5422     Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1, 4);
5423   }
5424
5425   SDValue Ops[2] = { Lo, Hi };
5426   return DAG.getMergeValues(Ops, 2, dl);
5427 }
5428
5429 SDValue X86TargetLowering::LowerSINT_TO_FP(SDValue Op,
5430                                            SelectionDAG &DAG) const {
5431   EVT SrcVT = Op.getOperand(0).getValueType();
5432
5433   if (SrcVT.isVector()) {
5434     if (SrcVT == MVT::v2i32 && Op.getValueType() == MVT::v2f64) {
5435       return Op;
5436     }
5437     return SDValue();
5438   }
5439
5440   assert(SrcVT.getSimpleVT() <= MVT::i64 && SrcVT.getSimpleVT() >= MVT::i16 &&
5441          "Unknown SINT_TO_FP to lower!");
5442
5443   // These are really Legal; return the operand so the caller accepts it as
5444   // Legal.
5445   if (SrcVT == MVT::i32 && isScalarFPTypeInSSEReg(Op.getValueType()))
5446     return Op;
5447   if (SrcVT == MVT::i64 && isScalarFPTypeInSSEReg(Op.getValueType()) &&
5448       Subtarget->is64Bit()) {
5449     return Op;
5450   }
5451
5452   DebugLoc dl = Op.getDebugLoc();
5453   unsigned Size = SrcVT.getSizeInBits()/8;
5454   MachineFunction &MF = DAG.getMachineFunction();
5455   int SSFI = MF.getFrameInfo()->CreateStackObject(Size, Size, false);
5456   SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
5457   SDValue Chain = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
5458                                StackSlot,
5459                                PseudoSourceValue::getFixedStack(SSFI), 0,
5460                                false, false, 0);
5461   return BuildFILD(Op, SrcVT, Chain, StackSlot, DAG);
5462 }
5463
5464 SDValue X86TargetLowering::BuildFILD(SDValue Op, EVT SrcVT, SDValue Chain,
5465                                      SDValue StackSlot,
5466                                      SelectionDAG &DAG) const {
5467   // Build the FILD
5468   DebugLoc dl = Op.getDebugLoc();
5469   SDVTList Tys;
5470   bool useSSE = isScalarFPTypeInSSEReg(Op.getValueType());
5471   if (useSSE)
5472     Tys = DAG.getVTList(MVT::f64, MVT::Other, MVT::Flag);
5473   else
5474     Tys = DAG.getVTList(Op.getValueType(), MVT::Other);
5475   SDValue Ops[] = { Chain, StackSlot, DAG.getValueType(SrcVT) };
5476   SDValue Result = DAG.getNode(useSSE ? X86ISD::FILD_FLAG : X86ISD::FILD, dl,
5477                                Tys, Ops, array_lengthof(Ops));
5478
5479   if (useSSE) {
5480     Chain = Result.getValue(1);
5481     SDValue InFlag = Result.getValue(2);
5482
5483     // FIXME: Currently the FST is flagged to the FILD_FLAG. This
5484     // shouldn't be necessary except that RFP cannot be live across
5485     // multiple blocks. When stackifier is fixed, they can be uncoupled.
5486     MachineFunction &MF = DAG.getMachineFunction();
5487     int SSFI = MF.getFrameInfo()->CreateStackObject(8, 8, false);
5488     SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
5489     Tys = DAG.getVTList(MVT::Other);
5490     SDValue Ops[] = {
5491       Chain, Result, StackSlot, DAG.getValueType(Op.getValueType()), InFlag
5492     };
5493     Chain = DAG.getNode(X86ISD::FST, dl, Tys, Ops, array_lengthof(Ops));
5494     Result = DAG.getLoad(Op.getValueType(), dl, Chain, StackSlot,
5495                          PseudoSourceValue::getFixedStack(SSFI), 0,
5496                          false, false, 0);
5497   }
5498
5499   return Result;
5500 }
5501
5502 // LowerUINT_TO_FP_i64 - 64-bit unsigned integer to double expansion.
5503 SDValue X86TargetLowering::LowerUINT_TO_FP_i64(SDValue Op,
5504                                                SelectionDAG &DAG) const {
5505   // This algorithm is not obvious. Here it is in C code, more or less:
5506   /*
5507     double uint64_to_double( uint32_t hi, uint32_t lo ) {
5508       static const __m128i exp = { 0x4330000045300000ULL, 0 };
5509       static const __m128d bias = { 0x1.0p84, 0x1.0p52 };
5510
5511       // Copy ints to xmm registers.
5512       __m128i xh = _mm_cvtsi32_si128( hi );
5513       __m128i xl = _mm_cvtsi32_si128( lo );
5514
5515       // Combine into low half of a single xmm register.
5516       __m128i x = _mm_unpacklo_epi32( xh, xl );
5517       __m128d d;
5518       double sd;
5519
5520       // Merge in appropriate exponents to give the integer bits the right
5521       // magnitude.
5522       x = _mm_unpacklo_epi32( x, exp );
5523
5524       // Subtract away the biases to deal with the IEEE-754 double precision
5525       // implicit 1.
5526       d = _mm_sub_pd( (__m128d) x, bias );
5527
5528       // All conversions up to here are exact. The correctly rounded result is
5529       // calculated using the current rounding mode using the following
5530       // horizontal add.
5531       d = _mm_add_sd( d, _mm_unpackhi_pd( d, d ) );
5532       _mm_store_sd( &sd, d );   // Because we are returning doubles in XMM, this
5533                                 // store doesn't really need to be here (except
5534                                 // maybe to zero the other double)
5535       return sd;
5536     }
5537   */
5538
5539   DebugLoc dl = Op.getDebugLoc();
5540   LLVMContext *Context = DAG.getContext();
5541
5542   // Build some magic constants.
5543   std::vector<Constant*> CV0;
5544   CV0.push_back(ConstantInt::get(*Context, APInt(32, 0x45300000)));
5545   CV0.push_back(ConstantInt::get(*Context, APInt(32, 0x43300000)));
5546   CV0.push_back(ConstantInt::get(*Context, APInt(32, 0)));
5547   CV0.push_back(ConstantInt::get(*Context, APInt(32, 0)));
5548   Constant *C0 = ConstantVector::get(CV0);
5549   SDValue CPIdx0 = DAG.getConstantPool(C0, getPointerTy(), 16);
5550
5551   std::vector<Constant*> CV1;
5552   CV1.push_back(
5553     ConstantFP::get(*Context, APFloat(APInt(64, 0x4530000000000000ULL))));
5554   CV1.push_back(
5555     ConstantFP::get(*Context, APFloat(APInt(64, 0x4330000000000000ULL))));
5556   Constant *C1 = ConstantVector::get(CV1);
5557   SDValue CPIdx1 = DAG.getConstantPool(C1, getPointerTy(), 16);
5558
5559   SDValue XR1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
5560                             DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
5561                                         Op.getOperand(0),
5562                                         DAG.getIntPtrConstant(1)));
5563   SDValue XR2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
5564                             DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
5565                                         Op.getOperand(0),
5566                                         DAG.getIntPtrConstant(0)));
5567   SDValue Unpck1 = getUnpackl(DAG, dl, MVT::v4i32, XR1, XR2);
5568   SDValue CLod0 = DAG.getLoad(MVT::v4i32, dl, DAG.getEntryNode(), CPIdx0,
5569                               PseudoSourceValue::getConstantPool(), 0,
5570                               false, false, 16);
5571   SDValue Unpck2 = getUnpackl(DAG, dl, MVT::v4i32, Unpck1, CLod0);
5572   SDValue XR2F = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v2f64, Unpck2);
5573   SDValue CLod1 = DAG.getLoad(MVT::v2f64, dl, CLod0.getValue(1), CPIdx1,
5574                               PseudoSourceValue::getConstantPool(), 0,
5575                               false, false, 16);
5576   SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, XR2F, CLod1);
5577
5578   // Add the halves; easiest way is to swap them into another reg first.
5579   int ShufMask[2] = { 1, -1 };
5580   SDValue Shuf = DAG.getVectorShuffle(MVT::v2f64, dl, Sub,
5581                                       DAG.getUNDEF(MVT::v2f64), ShufMask);
5582   SDValue Add = DAG.getNode(ISD::FADD, dl, MVT::v2f64, Shuf, Sub);
5583   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Add,
5584                      DAG.getIntPtrConstant(0));
5585 }
5586
5587 // LowerUINT_TO_FP_i32 - 32-bit unsigned integer to float expansion.
5588 SDValue X86TargetLowering::LowerUINT_TO_FP_i32(SDValue Op,
5589                                                SelectionDAG &DAG) const {
5590   DebugLoc dl = Op.getDebugLoc();
5591   // FP constant to bias correct the final result.
5592   SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL),
5593                                    MVT::f64);
5594
5595   // Load the 32-bit value into an XMM register.
5596   SDValue Load = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
5597                              DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
5598                                          Op.getOperand(0),
5599                                          DAG.getIntPtrConstant(0)));
5600
5601   Load = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
5602                      DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v2f64, Load),
5603                      DAG.getIntPtrConstant(0));
5604
5605   // Or the load with the bias.
5606   SDValue Or = DAG.getNode(ISD::OR, dl, MVT::v2i64,
5607                            DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v2i64,
5608                                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
5609                                                    MVT::v2f64, Load)),
5610                            DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v2i64,
5611                                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
5612                                                    MVT::v2f64, Bias)));
5613   Or = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
5614                    DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v2f64, Or),
5615                    DAG.getIntPtrConstant(0));
5616
5617   // Subtract the bias.
5618   SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::f64, Or, Bias);
5619
5620   // Handle final rounding.
5621   EVT DestVT = Op.getValueType();
5622
5623   if (DestVT.bitsLT(MVT::f64)) {
5624     return DAG.getNode(ISD::FP_ROUND, dl, DestVT, Sub,
5625                        DAG.getIntPtrConstant(0));
5626   } else if (DestVT.bitsGT(MVT::f64)) {
5627     return DAG.getNode(ISD::FP_EXTEND, dl, DestVT, Sub);
5628   }
5629
5630   // Handle final rounding.
5631   return Sub;
5632 }
5633
5634 SDValue X86TargetLowering::LowerUINT_TO_FP(SDValue Op,
5635                                            SelectionDAG &DAG) const {
5636   SDValue N0 = Op.getOperand(0);
5637   DebugLoc dl = Op.getDebugLoc();
5638
5639   // Now not UINT_TO_FP is legal (it's marked custom), dag combiner won't
5640   // optimize it to a SINT_TO_FP when the sign bit is known zero. Perform
5641   // the optimization here.
5642   if (DAG.SignBitIsZero(N0))
5643     return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(), N0);
5644
5645   EVT SrcVT = N0.getValueType();
5646   if (SrcVT == MVT::i64) {
5647     // We only handle SSE2 f64 target here; caller can expand the rest.
5648     if (Op.getValueType() != MVT::f64 || !X86ScalarSSEf64)
5649       return SDValue();
5650
5651     return LowerUINT_TO_FP_i64(Op, DAG);
5652   } else if (SrcVT == MVT::i32 && X86ScalarSSEf64) {
5653     return LowerUINT_TO_FP_i32(Op, DAG);
5654   }
5655
5656   assert(SrcVT == MVT::i32 && "Unknown UINT_TO_FP to lower!");
5657
5658   // Make a 64-bit buffer, and use it to build an FILD.
5659   SDValue StackSlot = DAG.CreateStackTemporary(MVT::i64);
5660   SDValue WordOff = DAG.getConstant(4, getPointerTy());
5661   SDValue OffsetSlot = DAG.getNode(ISD::ADD, dl,
5662                                    getPointerTy(), StackSlot, WordOff);
5663   SDValue Store1 = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
5664                                 StackSlot, NULL, 0, false, false, 0);
5665   SDValue Store2 = DAG.getStore(Store1, dl, DAG.getConstant(0, MVT::i32),
5666                                 OffsetSlot, NULL, 0, false, false, 0);
5667   return BuildFILD(Op, MVT::i64, Store2, StackSlot, DAG);
5668 }
5669
5670 std::pair<SDValue,SDValue> X86TargetLowering::
5671 FP_TO_INTHelper(SDValue Op, SelectionDAG &DAG, bool IsSigned) const {
5672   DebugLoc dl = Op.getDebugLoc();
5673
5674   EVT DstTy = Op.getValueType();
5675
5676   if (!IsSigned) {
5677     assert(DstTy == MVT::i32 && "Unexpected FP_TO_UINT");
5678     DstTy = MVT::i64;
5679   }
5680
5681   assert(DstTy.getSimpleVT() <= MVT::i64 &&
5682          DstTy.getSimpleVT() >= MVT::i16 &&
5683          "Unknown FP_TO_SINT to lower!");
5684
5685   // These are really Legal.
5686   if (DstTy == MVT::i32 &&
5687       isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
5688     return std::make_pair(SDValue(), SDValue());
5689   if (Subtarget->is64Bit() &&
5690       DstTy == MVT::i64 &&
5691       isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
5692     return std::make_pair(SDValue(), SDValue());
5693
5694   // We lower FP->sint64 into FISTP64, followed by a load, all to a temporary
5695   // stack slot.
5696   MachineFunction &MF = DAG.getMachineFunction();
5697   unsigned MemSize = DstTy.getSizeInBits()/8;
5698   int SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
5699   SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
5700
5701   unsigned Opc;
5702   switch (DstTy.getSimpleVT().SimpleTy) {
5703   default: llvm_unreachable("Invalid FP_TO_SINT to lower!");
5704   case MVT::i16: Opc = X86ISD::FP_TO_INT16_IN_MEM; break;
5705   case MVT::i32: Opc = X86ISD::FP_TO_INT32_IN_MEM; break;
5706   case MVT::i64: Opc = X86ISD::FP_TO_INT64_IN_MEM; break;
5707   }
5708
5709   SDValue Chain = DAG.getEntryNode();
5710   SDValue Value = Op.getOperand(0);
5711   if (isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType())) {
5712     assert(DstTy == MVT::i64 && "Invalid FP_TO_SINT to lower!");
5713     Chain = DAG.getStore(Chain, dl, Value, StackSlot,
5714                          PseudoSourceValue::getFixedStack(SSFI), 0,
5715                          false, false, 0);
5716     SDVTList Tys = DAG.getVTList(Op.getOperand(0).getValueType(), MVT::Other);
5717     SDValue Ops[] = {
5718       Chain, StackSlot, DAG.getValueType(Op.getOperand(0).getValueType())
5719     };
5720     Value = DAG.getNode(X86ISD::FLD, dl, Tys, Ops, 3);
5721     Chain = Value.getValue(1);
5722     SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
5723     StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
5724   }
5725
5726   // Build the FP_TO_INT*_IN_MEM
5727   SDValue Ops[] = { Chain, Value, StackSlot };
5728   SDValue FIST = DAG.getNode(Opc, dl, MVT::Other, Ops, 3);
5729
5730   return std::make_pair(FIST, StackSlot);
5731 }
5732
5733 SDValue X86TargetLowering::LowerFP_TO_SINT(SDValue Op,
5734                                            SelectionDAG &DAG) const {
5735   if (Op.getValueType().isVector()) {
5736     if (Op.getValueType() == MVT::v2i32 &&
5737         Op.getOperand(0).getValueType() == MVT::v2f64) {
5738       return Op;
5739     }
5740     return SDValue();
5741   }
5742
5743   std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG, true);
5744   SDValue FIST = Vals.first, StackSlot = Vals.second;
5745   // If FP_TO_INTHelper failed, the node is actually supposed to be Legal.
5746   if (FIST.getNode() == 0) return Op;
5747
5748   // Load the result.
5749   return DAG.getLoad(Op.getValueType(), Op.getDebugLoc(),
5750                      FIST, StackSlot, NULL, 0, false, false, 0);
5751 }
5752
5753 SDValue X86TargetLowering::LowerFP_TO_UINT(SDValue Op,
5754                                            SelectionDAG &DAG) const {
5755   std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG, false);
5756   SDValue FIST = Vals.first, StackSlot = Vals.second;
5757   assert(FIST.getNode() && "Unexpected failure");
5758
5759   // Load the result.
5760   return DAG.getLoad(Op.getValueType(), Op.getDebugLoc(),
5761                      FIST, StackSlot, NULL, 0, false, false, 0);
5762 }
5763
5764 SDValue X86TargetLowering::LowerFABS(SDValue Op,
5765                                      SelectionDAG &DAG) const {
5766   LLVMContext *Context = DAG.getContext();
5767   DebugLoc dl = Op.getDebugLoc();
5768   EVT VT = Op.getValueType();
5769   EVT EltVT = VT;
5770   if (VT.isVector())
5771     EltVT = VT.getVectorElementType();
5772   std::vector<Constant*> CV;
5773   if (EltVT == MVT::f64) {
5774     Constant *C = ConstantFP::get(*Context, APFloat(APInt(64, ~(1ULL << 63))));
5775     CV.push_back(C);
5776     CV.push_back(C);
5777   } else {
5778     Constant *C = ConstantFP::get(*Context, APFloat(APInt(32, ~(1U << 31))));
5779     CV.push_back(C);
5780     CV.push_back(C);
5781     CV.push_back(C);
5782     CV.push_back(C);
5783   }
5784   Constant *C = ConstantVector::get(CV);
5785   SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
5786   SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
5787                              PseudoSourceValue::getConstantPool(), 0,
5788                              false, false, 16);
5789   return DAG.getNode(X86ISD::FAND, dl, VT, Op.getOperand(0), Mask);
5790 }
5791
5792 SDValue X86TargetLowering::LowerFNEG(SDValue Op, SelectionDAG &DAG) const {
5793   LLVMContext *Context = DAG.getContext();
5794   DebugLoc dl = Op.getDebugLoc();
5795   EVT VT = Op.getValueType();
5796   EVT EltVT = VT;
5797   if (VT.isVector())
5798     EltVT = VT.getVectorElementType();
5799   std::vector<Constant*> CV;
5800   if (EltVT == MVT::f64) {
5801     Constant *C = ConstantFP::get(*Context, APFloat(APInt(64, 1ULL << 63)));
5802     CV.push_back(C);
5803     CV.push_back(C);
5804   } else {
5805     Constant *C = ConstantFP::get(*Context, APFloat(APInt(32, 1U << 31)));
5806     CV.push_back(C);
5807     CV.push_back(C);
5808     CV.push_back(C);
5809     CV.push_back(C);
5810   }
5811   Constant *C = ConstantVector::get(CV);
5812   SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
5813   SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
5814                              PseudoSourceValue::getConstantPool(), 0,
5815                              false, false, 16);
5816   if (VT.isVector()) {
5817     return DAG.getNode(ISD::BIT_CONVERT, dl, VT,
5818                        DAG.getNode(ISD::XOR, dl, MVT::v2i64,
5819                     DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v2i64,
5820                                 Op.getOperand(0)),
5821                     DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v2i64, Mask)));
5822   } else {
5823     return DAG.getNode(X86ISD::FXOR, dl, VT, Op.getOperand(0), Mask);
5824   }
5825 }
5826
5827 SDValue X86TargetLowering::LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) const {
5828   LLVMContext *Context = DAG.getContext();
5829   SDValue Op0 = Op.getOperand(0);
5830   SDValue Op1 = Op.getOperand(1);
5831   DebugLoc dl = Op.getDebugLoc();
5832   EVT VT = Op.getValueType();
5833   EVT SrcVT = Op1.getValueType();
5834
5835   // If second operand is smaller, extend it first.
5836   if (SrcVT.bitsLT(VT)) {
5837     Op1 = DAG.getNode(ISD::FP_EXTEND, dl, VT, Op1);
5838     SrcVT = VT;
5839   }
5840   // And if it is bigger, shrink it first.
5841   if (SrcVT.bitsGT(VT)) {
5842     Op1 = DAG.getNode(ISD::FP_ROUND, dl, VT, Op1, DAG.getIntPtrConstant(1));
5843     SrcVT = VT;
5844   }
5845
5846   // At this point the operands and the result should have the same
5847   // type, and that won't be f80 since that is not custom lowered.
5848
5849   // First get the sign bit of second operand.
5850   std::vector<Constant*> CV;
5851   if (SrcVT == MVT::f64) {
5852     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, 1ULL << 63))));
5853     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, 0))));
5854   } else {
5855     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 1U << 31))));
5856     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
5857     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
5858     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
5859   }
5860   Constant *C = ConstantVector::get(CV);
5861   SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
5862   SDValue Mask1 = DAG.getLoad(SrcVT, dl, DAG.getEntryNode(), CPIdx,
5863                               PseudoSourceValue::getConstantPool(), 0,
5864                               false, false, 16);
5865   SDValue SignBit = DAG.getNode(X86ISD::FAND, dl, SrcVT, Op1, Mask1);
5866
5867   // Shift sign bit right or left if the two operands have different types.
5868   if (SrcVT.bitsGT(VT)) {
5869     // Op0 is MVT::f32, Op1 is MVT::f64.
5870     SignBit = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f64, SignBit);
5871     SignBit = DAG.getNode(X86ISD::FSRL, dl, MVT::v2f64, SignBit,
5872                           DAG.getConstant(32, MVT::i32));
5873     SignBit = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v4f32, SignBit);
5874     SignBit = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f32, SignBit,
5875                           DAG.getIntPtrConstant(0));
5876   }
5877
5878   // Clear first operand sign bit.
5879   CV.clear();
5880   if (VT == MVT::f64) {
5881     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, ~(1ULL << 63)))));
5882     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, 0))));
5883   } else {
5884     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, ~(1U << 31)))));
5885     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
5886     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
5887     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
5888   }
5889   C = ConstantVector::get(CV);
5890   CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
5891   SDValue Mask2 = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
5892                               PseudoSourceValue::getConstantPool(), 0,
5893                               false, false, 16);
5894   SDValue Val = DAG.getNode(X86ISD::FAND, dl, VT, Op0, Mask2);
5895
5896   // Or the value with the sign bit.
5897   return DAG.getNode(X86ISD::FOR, dl, VT, Val, SignBit);
5898 }
5899
5900 /// Emit nodes that will be selected as "test Op0,Op0", or something
5901 /// equivalent.
5902 SDValue X86TargetLowering::EmitTest(SDValue Op, unsigned X86CC,
5903                                     SelectionDAG &DAG) const {
5904   DebugLoc dl = Op.getDebugLoc();
5905
5906   // CF and OF aren't always set the way we want. Determine which
5907   // of these we need.
5908   bool NeedCF = false;
5909   bool NeedOF = false;
5910   switch (X86CC) {
5911   case X86::COND_A: case X86::COND_AE:
5912   case X86::COND_B: case X86::COND_BE:
5913     NeedCF = true;
5914     break;
5915   case X86::COND_G: case X86::COND_GE:
5916   case X86::COND_L: case X86::COND_LE:
5917   case X86::COND_O: case X86::COND_NO:
5918     NeedOF = true;
5919     break;
5920   default: break;
5921   }
5922
5923   // See if we can use the EFLAGS value from the operand instead of
5924   // doing a separate TEST. TEST always sets OF and CF to 0, so unless
5925   // we prove that the arithmetic won't overflow, we can't use OF or CF.
5926   if (Op.getResNo() == 0 && !NeedOF && !NeedCF) {
5927     unsigned Opcode = 0;
5928     unsigned NumOperands = 0;
5929     switch (Op.getNode()->getOpcode()) {
5930     case ISD::ADD:
5931       // Due to an isel shortcoming, be conservative if this add is
5932       // likely to be selected as part of a load-modify-store
5933       // instruction. When the root node in a match is a store, isel
5934       // doesn't know how to remap non-chain non-flag uses of other
5935       // nodes in the match, such as the ADD in this case. This leads
5936       // to the ADD being left around and reselected, with the result
5937       // being two adds in the output.  Alas, even if none our users
5938       // are stores, that doesn't prove we're O.K.  Ergo, if we have
5939       // any parents that aren't CopyToReg or SETCC, eschew INC/DEC.
5940       // A better fix seems to require climbing the DAG back to the
5941       // root, and it doesn't seem to be worth the effort.
5942       for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
5943              UE = Op.getNode()->use_end(); UI != UE; ++UI)
5944         if (UI->getOpcode() != ISD::CopyToReg && UI->getOpcode() != ISD::SETCC)
5945           goto default_case;
5946       if (ConstantSDNode *C =
5947             dyn_cast<ConstantSDNode>(Op.getNode()->getOperand(1))) {
5948         // An add of one will be selected as an INC.
5949         if (C->getAPIntValue() == 1) {
5950           Opcode = X86ISD::INC;
5951           NumOperands = 1;
5952           break;
5953         }
5954         // An add of negative one (subtract of one) will be selected as a DEC.
5955         if (C->getAPIntValue().isAllOnesValue()) {
5956           Opcode = X86ISD::DEC;
5957           NumOperands = 1;
5958           break;
5959         }
5960       }
5961       // Otherwise use a regular EFLAGS-setting add.
5962       Opcode = X86ISD::ADD;
5963       NumOperands = 2;
5964       break;
5965     case ISD::AND: {
5966       // If the primary and result isn't used, don't bother using X86ISD::AND,
5967       // because a TEST instruction will be better.
5968       bool NonFlagUse = false;
5969       for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
5970              UE = Op.getNode()->use_end(); UI != UE; ++UI) {
5971         SDNode *User = *UI;
5972         unsigned UOpNo = UI.getOperandNo();
5973         if (User->getOpcode() == ISD::TRUNCATE && User->hasOneUse()) {
5974           // Look pass truncate.
5975           UOpNo = User->use_begin().getOperandNo();
5976           User = *User->use_begin();
5977         }
5978         if (User->getOpcode() != ISD::BRCOND &&
5979             User->getOpcode() != ISD::SETCC &&
5980             (User->getOpcode() != ISD::SELECT || UOpNo != 0)) {
5981           NonFlagUse = true;
5982           break;
5983         }
5984       }
5985       if (!NonFlagUse)
5986         break;
5987     }
5988     // FALL THROUGH
5989     case ISD::SUB:
5990     case ISD::OR:
5991     case ISD::XOR:
5992       // Due to the ISEL shortcoming noted above, be conservative if this op is
5993       // likely to be selected as part of a load-modify-store instruction.
5994       for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
5995            UE = Op.getNode()->use_end(); UI != UE; ++UI)
5996         if (UI->getOpcode() == ISD::STORE)
5997           goto default_case;
5998       // Otherwise use a regular EFLAGS-setting instruction.
5999       switch (Op.getNode()->getOpcode()) {
6000       case ISD::SUB: Opcode = X86ISD::SUB; break;
6001       case ISD::OR:  Opcode = X86ISD::OR;  break;
6002       case ISD::XOR: Opcode = X86ISD::XOR; break;
6003       case ISD::AND: Opcode = X86ISD::AND; break;
6004       default: llvm_unreachable("unexpected operator!");
6005       }
6006       NumOperands = 2;
6007       break;
6008     case X86ISD::ADD:
6009     case X86ISD::SUB:
6010     case X86ISD::INC:
6011     case X86ISD::DEC:
6012     case X86ISD::OR:
6013     case X86ISD::XOR:
6014     case X86ISD::AND:
6015       return SDValue(Op.getNode(), 1);
6016     default:
6017     default_case:
6018       break;
6019     }
6020     if (Opcode != 0) {
6021       SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
6022       SmallVector<SDValue, 4> Ops;
6023       for (unsigned i = 0; i != NumOperands; ++i)
6024         Ops.push_back(Op.getOperand(i));
6025       SDValue New = DAG.getNode(Opcode, dl, VTs, &Ops[0], NumOperands);
6026       DAG.ReplaceAllUsesWith(Op, New);
6027       return SDValue(New.getNode(), 1);
6028     }
6029   }
6030
6031   // Otherwise just emit a CMP with 0, which is the TEST pattern.
6032   return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
6033                      DAG.getConstant(0, Op.getValueType()));
6034 }
6035
6036 /// Emit nodes that will be selected as "cmp Op0,Op1", or something
6037 /// equivalent.
6038 SDValue X86TargetLowering::EmitCmp(SDValue Op0, SDValue Op1, unsigned X86CC,
6039                                    SelectionDAG &DAG) const {
6040   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op1))
6041     if (C->getAPIntValue() == 0)
6042       return EmitTest(Op0, X86CC, DAG);
6043
6044   DebugLoc dl = Op0.getDebugLoc();
6045   return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op0, Op1);
6046 }
6047
6048 /// LowerToBT - Result of 'and' is compared against zero. Turn it into a BT node
6049 /// if it's possible.
6050 SDValue X86TargetLowering::LowerToBT(SDValue And, ISD::CondCode CC,
6051                                      DebugLoc dl, SelectionDAG &DAG) const {
6052   SDValue Op0 = And.getOperand(0);
6053   SDValue Op1 = And.getOperand(1);
6054   if (Op0.getOpcode() == ISD::TRUNCATE)
6055     Op0 = Op0.getOperand(0);
6056   if (Op1.getOpcode() == ISD::TRUNCATE)
6057     Op1 = Op1.getOperand(0);
6058
6059   SDValue LHS, RHS;
6060   if (Op1.getOpcode() == ISD::SHL) {
6061     if (ConstantSDNode *And10C = dyn_cast<ConstantSDNode>(Op1.getOperand(0)))
6062       if (And10C->getZExtValue() == 1) {
6063         LHS = Op0;
6064         RHS = Op1.getOperand(1);
6065       }
6066   } else if (Op0.getOpcode() == ISD::SHL) {
6067     if (ConstantSDNode *And00C = dyn_cast<ConstantSDNode>(Op0.getOperand(0)))
6068       if (And00C->getZExtValue() == 1) {
6069         LHS = Op1;
6070         RHS = Op0.getOperand(1);
6071       }
6072   } else if (Op1.getOpcode() == ISD::Constant) {
6073     ConstantSDNode *AndRHS = cast<ConstantSDNode>(Op1);
6074     SDValue AndLHS = Op0;
6075     if (AndRHS->getZExtValue() == 1 && AndLHS.getOpcode() == ISD::SRL) {
6076       LHS = AndLHS.getOperand(0);
6077       RHS = AndLHS.getOperand(1);
6078     }
6079   }
6080
6081   if (LHS.getNode()) {
6082     // If LHS is i8, promote it to i32 with any_extend.  There is no i8 BT
6083     // instruction.  Since the shift amount is in-range-or-undefined, we know
6084     // that doing a bittest on the i32 value is ok.  We extend to i32 because
6085     // the encoding for the i16 version is larger than the i32 version.
6086     // Also promote i16 to i32 for performance / code size reason.
6087     if (LHS.getValueType() == MVT::i8 ||
6088         LHS.getValueType() == MVT::i16)
6089       LHS = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, LHS);
6090
6091     // If the operand types disagree, extend the shift amount to match.  Since
6092     // BT ignores high bits (like shifts) we can use anyextend.
6093     if (LHS.getValueType() != RHS.getValueType())
6094       RHS = DAG.getNode(ISD::ANY_EXTEND, dl, LHS.getValueType(), RHS);
6095
6096     SDValue BT = DAG.getNode(X86ISD::BT, dl, MVT::i32, LHS, RHS);
6097     unsigned Cond = CC == ISD::SETEQ ? X86::COND_AE : X86::COND_B;
6098     return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
6099                        DAG.getConstant(Cond, MVT::i8), BT);
6100   }
6101
6102   return SDValue();
6103 }
6104
6105 SDValue X86TargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
6106   assert(Op.getValueType() == MVT::i8 && "SetCC type must be 8-bit integer");
6107   SDValue Op0 = Op.getOperand(0);
6108   SDValue Op1 = Op.getOperand(1);
6109   DebugLoc dl = Op.getDebugLoc();
6110   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
6111
6112   // Optimize to BT if possible.
6113   // Lower (X & (1 << N)) == 0 to BT(X, N).
6114   // Lower ((X >>u N) & 1) != 0 to BT(X, N).
6115   // Lower ((X >>s N) & 1) != 0 to BT(X, N).
6116   if (Op0.getOpcode() == ISD::AND &&
6117       Op0.hasOneUse() &&
6118       Op1.getOpcode() == ISD::Constant &&
6119       cast<ConstantSDNode>(Op1)->getZExtValue() == 0 &&
6120       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
6121     SDValue NewSetCC = LowerToBT(Op0, CC, dl, DAG);
6122     if (NewSetCC.getNode())
6123       return NewSetCC;
6124   }
6125
6126   // Look for "(setcc) == / != 1" to avoid unncessary setcc.
6127   if (Op0.getOpcode() == X86ISD::SETCC &&
6128       Op1.getOpcode() == ISD::Constant &&
6129       (cast<ConstantSDNode>(Op1)->getZExtValue() == 1 ||
6130        cast<ConstantSDNode>(Op1)->isNullValue()) &&
6131       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
6132     X86::CondCode CCode = (X86::CondCode)Op0.getConstantOperandVal(0);
6133     bool Invert = (CC == ISD::SETNE) ^
6134       cast<ConstantSDNode>(Op1)->isNullValue();
6135     if (Invert)
6136       CCode = X86::GetOppositeBranchCondition(CCode);
6137     return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
6138                        DAG.getConstant(CCode, MVT::i8), Op0.getOperand(1));
6139   }
6140
6141   bool isFP = Op1.getValueType().isFloatingPoint();
6142   unsigned X86CC = TranslateX86CC(CC, isFP, Op0, Op1, DAG);
6143   if (X86CC == X86::COND_INVALID)
6144     return SDValue();
6145
6146   SDValue Cond = EmitCmp(Op0, Op1, X86CC, DAG);
6147
6148   // Use sbb x, x to materialize carry bit into a GPR.
6149   if (X86CC == X86::COND_B)
6150     return DAG.getNode(ISD::AND, dl, MVT::i8,
6151                        DAG.getNode(X86ISD::SETCC_CARRY, dl, MVT::i8,
6152                                    DAG.getConstant(X86CC, MVT::i8), Cond),
6153                        DAG.getConstant(1, MVT::i8));
6154
6155   return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
6156                      DAG.getConstant(X86CC, MVT::i8), Cond);
6157 }
6158
6159 SDValue X86TargetLowering::LowerVSETCC(SDValue Op, SelectionDAG &DAG) const {
6160   SDValue Cond;
6161   SDValue Op0 = Op.getOperand(0);
6162   SDValue Op1 = Op.getOperand(1);
6163   SDValue CC = Op.getOperand(2);
6164   EVT VT = Op.getValueType();
6165   ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
6166   bool isFP = Op.getOperand(1).getValueType().isFloatingPoint();
6167   DebugLoc dl = Op.getDebugLoc();
6168
6169   if (isFP) {
6170     unsigned SSECC = 8;
6171     EVT VT0 = Op0.getValueType();
6172     assert(VT0 == MVT::v4f32 || VT0 == MVT::v2f64);
6173     unsigned Opc = VT0 == MVT::v4f32 ? X86ISD::CMPPS : X86ISD::CMPPD;
6174     bool Swap = false;
6175
6176     switch (SetCCOpcode) {
6177     default: break;
6178     case ISD::SETOEQ:
6179     case ISD::SETEQ:  SSECC = 0; break;
6180     case ISD::SETOGT:
6181     case ISD::SETGT: Swap = true; // Fallthrough
6182     case ISD::SETLT:
6183     case ISD::SETOLT: SSECC = 1; break;
6184     case ISD::SETOGE:
6185     case ISD::SETGE: Swap = true; // Fallthrough
6186     case ISD::SETLE:
6187     case ISD::SETOLE: SSECC = 2; break;
6188     case ISD::SETUO:  SSECC = 3; break;
6189     case ISD::SETUNE:
6190     case ISD::SETNE:  SSECC = 4; break;
6191     case ISD::SETULE: Swap = true;
6192     case ISD::SETUGE: SSECC = 5; break;
6193     case ISD::SETULT: Swap = true;
6194     case ISD::SETUGT: SSECC = 6; break;
6195     case ISD::SETO:   SSECC = 7; break;
6196     }
6197     if (Swap)
6198       std::swap(Op0, Op1);
6199
6200     // In the two special cases we can't handle, emit two comparisons.
6201     if (SSECC == 8) {
6202       if (SetCCOpcode == ISD::SETUEQ) {
6203         SDValue UNORD, EQ;
6204         UNORD = DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(3, MVT::i8));
6205         EQ = DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(0, MVT::i8));
6206         return DAG.getNode(ISD::OR, dl, VT, UNORD, EQ);
6207       }
6208       else if (SetCCOpcode == ISD::SETONE) {
6209         SDValue ORD, NEQ;
6210         ORD = DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(7, MVT::i8));
6211         NEQ = DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(4, MVT::i8));
6212         return DAG.getNode(ISD::AND, dl, VT, ORD, NEQ);
6213       }
6214       llvm_unreachable("Illegal FP comparison");
6215     }
6216     // Handle all other FP comparisons here.
6217     return DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(SSECC, MVT::i8));
6218   }
6219
6220   // We are handling one of the integer comparisons here.  Since SSE only has
6221   // GT and EQ comparisons for integer, swapping operands and multiple
6222   // operations may be required for some comparisons.
6223   unsigned Opc = 0, EQOpc = 0, GTOpc = 0;
6224   bool Swap = false, Invert = false, FlipSigns = false;
6225
6226   switch (VT.getSimpleVT().SimpleTy) {
6227   default: break;
6228   case MVT::v8i8:
6229   case MVT::v16i8: EQOpc = X86ISD::PCMPEQB; GTOpc = X86ISD::PCMPGTB; break;
6230   case MVT::v4i16:
6231   case MVT::v8i16: EQOpc = X86ISD::PCMPEQW; GTOpc = X86ISD::PCMPGTW; break;
6232   case MVT::v2i32:
6233   case MVT::v4i32: EQOpc = X86ISD::PCMPEQD; GTOpc = X86ISD::PCMPGTD; break;
6234   case MVT::v2i64: EQOpc = X86ISD::PCMPEQQ; GTOpc = X86ISD::PCMPGTQ; break;
6235   }
6236
6237   switch (SetCCOpcode) {
6238   default: break;
6239   case ISD::SETNE:  Invert = true;
6240   case ISD::SETEQ:  Opc = EQOpc; break;
6241   case ISD::SETLT:  Swap = true;
6242   case ISD::SETGT:  Opc = GTOpc; break;
6243   case ISD::SETGE:  Swap = true;
6244   case ISD::SETLE:  Opc = GTOpc; Invert = true; break;
6245   case ISD::SETULT: Swap = true;
6246   case ISD::SETUGT: Opc = GTOpc; FlipSigns = true; break;
6247   case ISD::SETUGE: Swap = true;
6248   case ISD::SETULE: Opc = GTOpc; FlipSigns = true; Invert = true; break;
6249   }
6250   if (Swap)
6251     std::swap(Op0, Op1);
6252
6253   // Since SSE has no unsigned integer comparisons, we need to flip  the sign
6254   // bits of the inputs before performing those operations.
6255   if (FlipSigns) {
6256     EVT EltVT = VT.getVectorElementType();
6257     SDValue SignBit = DAG.getConstant(APInt::getSignBit(EltVT.getSizeInBits()),
6258                                       EltVT);
6259     std::vector<SDValue> SignBits(VT.getVectorNumElements(), SignBit);
6260     SDValue SignVec = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &SignBits[0],
6261                                     SignBits.size());
6262     Op0 = DAG.getNode(ISD::XOR, dl, VT, Op0, SignVec);
6263     Op1 = DAG.getNode(ISD::XOR, dl, VT, Op1, SignVec);
6264   }
6265
6266   SDValue Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
6267
6268   // If the logical-not of the result is required, perform that now.
6269   if (Invert)
6270     Result = DAG.getNOT(dl, Result, VT);
6271
6272   return Result;
6273 }
6274
6275 // isX86LogicalCmp - Return true if opcode is a X86 logical comparison.
6276 static bool isX86LogicalCmp(SDValue Op) {
6277   unsigned Opc = Op.getNode()->getOpcode();
6278   if (Opc == X86ISD::CMP || Opc == X86ISD::COMI || Opc == X86ISD::UCOMI)
6279     return true;
6280   if (Op.getResNo() == 1 &&
6281       (Opc == X86ISD::ADD ||
6282        Opc == X86ISD::SUB ||
6283        Opc == X86ISD::SMUL ||
6284        Opc == X86ISD::UMUL ||
6285        Opc == X86ISD::INC ||
6286        Opc == X86ISD::DEC ||
6287        Opc == X86ISD::OR ||
6288        Opc == X86ISD::XOR ||
6289        Opc == X86ISD::AND))
6290     return true;
6291
6292   return false;
6293 }
6294
6295 SDValue X86TargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
6296   bool addTest = true;
6297   SDValue Cond  = Op.getOperand(0);
6298   DebugLoc dl = Op.getDebugLoc();
6299   SDValue CC;
6300
6301   if (Cond.getOpcode() == ISD::SETCC) {
6302     SDValue NewCond = LowerSETCC(Cond, DAG);
6303     if (NewCond.getNode())
6304       Cond = NewCond;
6305   }
6306
6307   // (select (x == 0), -1, 0) -> (sign_bit (x - 1))
6308   SDValue Op1 = Op.getOperand(1);
6309   SDValue Op2 = Op.getOperand(2);
6310   if (Cond.getOpcode() == X86ISD::SETCC &&
6311       cast<ConstantSDNode>(Cond.getOperand(0))->getZExtValue() == X86::COND_E) {
6312     SDValue Cmp = Cond.getOperand(1);
6313     if (Cmp.getOpcode() == X86ISD::CMP) {
6314       ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(Op1);
6315       ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(Op2);
6316       ConstantSDNode *RHSC =
6317         dyn_cast<ConstantSDNode>(Cmp.getOperand(1).getNode());
6318       if (N1C && N1C->isAllOnesValue() &&
6319           N2C && N2C->isNullValue() &&
6320           RHSC && RHSC->isNullValue()) {
6321         SDValue CmpOp0 = Cmp.getOperand(0);
6322         Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
6323                           CmpOp0, DAG.getConstant(1, CmpOp0.getValueType()));
6324         return DAG.getNode(X86ISD::SETCC_CARRY, dl, Op.getValueType(),
6325                            DAG.getConstant(X86::COND_B, MVT::i8), Cmp);
6326       }
6327     }
6328   }
6329
6330   // Look pass (and (setcc_carry (cmp ...)), 1).
6331   if (Cond.getOpcode() == ISD::AND &&
6332       Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
6333     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
6334     if (C && C->getAPIntValue() == 1) 
6335       Cond = Cond.getOperand(0);
6336   }
6337
6338   // If condition flag is set by a X86ISD::CMP, then use it as the condition
6339   // setting operand in place of the X86ISD::SETCC.
6340   if (Cond.getOpcode() == X86ISD::SETCC ||
6341       Cond.getOpcode() == X86ISD::SETCC_CARRY) {
6342     CC = Cond.getOperand(0);
6343
6344     SDValue Cmp = Cond.getOperand(1);
6345     unsigned Opc = Cmp.getOpcode();
6346     EVT VT = Op.getValueType();
6347
6348     bool IllegalFPCMov = false;
6349     if (VT.isFloatingPoint() && !VT.isVector() &&
6350         !isScalarFPTypeInSSEReg(VT))  // FPStack?
6351       IllegalFPCMov = !hasFPCMov(cast<ConstantSDNode>(CC)->getSExtValue());
6352
6353     if ((isX86LogicalCmp(Cmp) && !IllegalFPCMov) ||
6354         Opc == X86ISD::BT) { // FIXME
6355       Cond = Cmp;
6356       addTest = false;
6357     }
6358   }
6359
6360   if (addTest) {
6361     // Look pass the truncate.
6362     if (Cond.getOpcode() == ISD::TRUNCATE)
6363       Cond = Cond.getOperand(0);
6364
6365     // We know the result of AND is compared against zero. Try to match
6366     // it to BT.
6367     if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) { 
6368       SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, dl, DAG);
6369       if (NewSetCC.getNode()) {
6370         CC = NewSetCC.getOperand(0);
6371         Cond = NewSetCC.getOperand(1);
6372         addTest = false;
6373       }
6374     }
6375   }
6376
6377   if (addTest) {
6378     CC = DAG.getConstant(X86::COND_NE, MVT::i8);
6379     Cond = EmitTest(Cond, X86::COND_NE, DAG);
6380   }
6381
6382   // X86ISD::CMOV means set the result (which is operand 1) to the RHS if
6383   // condition is true.
6384   SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::Flag);
6385   SDValue Ops[] = { Op2, Op1, CC, Cond };
6386   return DAG.getNode(X86ISD::CMOV, dl, VTs, Ops, array_lengthof(Ops));
6387 }
6388
6389 // isAndOrOfSingleUseSetCCs - Return true if node is an ISD::AND or
6390 // ISD::OR of two X86ISD::SETCC nodes each of which has no other use apart
6391 // from the AND / OR.
6392 static bool isAndOrOfSetCCs(SDValue Op, unsigned &Opc) {
6393   Opc = Op.getOpcode();
6394   if (Opc != ISD::OR && Opc != ISD::AND)
6395     return false;
6396   return (Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
6397           Op.getOperand(0).hasOneUse() &&
6398           Op.getOperand(1).getOpcode() == X86ISD::SETCC &&
6399           Op.getOperand(1).hasOneUse());
6400 }
6401
6402 // isXor1OfSetCC - Return true if node is an ISD::XOR of a X86ISD::SETCC and
6403 // 1 and that the SETCC node has a single use.
6404 static bool isXor1OfSetCC(SDValue Op) {
6405   if (Op.getOpcode() != ISD::XOR)
6406     return false;
6407   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
6408   if (N1C && N1C->getAPIntValue() == 1) {
6409     return Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
6410       Op.getOperand(0).hasOneUse();
6411   }
6412   return false;
6413 }
6414
6415 SDValue X86TargetLowering::LowerBRCOND(SDValue Op, SelectionDAG &DAG) const {
6416   bool addTest = true;
6417   SDValue Chain = Op.getOperand(0);
6418   SDValue Cond  = Op.getOperand(1);
6419   SDValue Dest  = Op.getOperand(2);
6420   DebugLoc dl = Op.getDebugLoc();
6421   SDValue CC;
6422
6423   if (Cond.getOpcode() == ISD::SETCC) {
6424     SDValue NewCond = LowerSETCC(Cond, DAG);
6425     if (NewCond.getNode())
6426       Cond = NewCond;
6427   }
6428 #if 0
6429   // FIXME: LowerXALUO doesn't handle these!!
6430   else if (Cond.getOpcode() == X86ISD::ADD  ||
6431            Cond.getOpcode() == X86ISD::SUB  ||
6432            Cond.getOpcode() == X86ISD::SMUL ||
6433            Cond.getOpcode() == X86ISD::UMUL)
6434     Cond = LowerXALUO(Cond, DAG);
6435 #endif
6436
6437   // Look pass (and (setcc_carry (cmp ...)), 1).
6438   if (Cond.getOpcode() == ISD::AND &&
6439       Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
6440     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
6441     if (C && C->getAPIntValue() == 1) 
6442       Cond = Cond.getOperand(0);
6443   }
6444
6445   // If condition flag is set by a X86ISD::CMP, then use it as the condition
6446   // setting operand in place of the X86ISD::SETCC.
6447   if (Cond.getOpcode() == X86ISD::SETCC ||
6448       Cond.getOpcode() == X86ISD::SETCC_CARRY) {
6449     CC = Cond.getOperand(0);
6450
6451     SDValue Cmp = Cond.getOperand(1);
6452     unsigned Opc = Cmp.getOpcode();
6453     // FIXME: WHY THE SPECIAL CASING OF LogicalCmp??
6454     if (isX86LogicalCmp(Cmp) || Opc == X86ISD::BT) {
6455       Cond = Cmp;
6456       addTest = false;
6457     } else {
6458       switch (cast<ConstantSDNode>(CC)->getZExtValue()) {
6459       default: break;
6460       case X86::COND_O:
6461       case X86::COND_B:
6462         // These can only come from an arithmetic instruction with overflow,
6463         // e.g. SADDO, UADDO.
6464         Cond = Cond.getNode()->getOperand(1);
6465         addTest = false;
6466         break;
6467       }
6468     }
6469   } else {
6470     unsigned CondOpc;
6471     if (Cond.hasOneUse() && isAndOrOfSetCCs(Cond, CondOpc)) {
6472       SDValue Cmp = Cond.getOperand(0).getOperand(1);
6473       if (CondOpc == ISD::OR) {
6474         // Also, recognize the pattern generated by an FCMP_UNE. We can emit
6475         // two branches instead of an explicit OR instruction with a
6476         // separate test.
6477         if (Cmp == Cond.getOperand(1).getOperand(1) &&
6478             isX86LogicalCmp(Cmp)) {
6479           CC = Cond.getOperand(0).getOperand(0);
6480           Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
6481                               Chain, Dest, CC, Cmp);
6482           CC = Cond.getOperand(1).getOperand(0);
6483           Cond = Cmp;
6484           addTest = false;
6485         }
6486       } else { // ISD::AND
6487         // Also, recognize the pattern generated by an FCMP_OEQ. We can emit
6488         // two branches instead of an explicit AND instruction with a
6489         // separate test. However, we only do this if this block doesn't
6490         // have a fall-through edge, because this requires an explicit
6491         // jmp when the condition is false.
6492         if (Cmp == Cond.getOperand(1).getOperand(1) &&
6493             isX86LogicalCmp(Cmp) &&
6494             Op.getNode()->hasOneUse()) {
6495           X86::CondCode CCode =
6496             (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
6497           CCode = X86::GetOppositeBranchCondition(CCode);
6498           CC = DAG.getConstant(CCode, MVT::i8);
6499           SDValue User = SDValue(*Op.getNode()->use_begin(), 0);
6500           // Look for an unconditional branch following this conditional branch.
6501           // We need this because we need to reverse the successors in order
6502           // to implement FCMP_OEQ.
6503           if (User.getOpcode() == ISD::BR) {
6504             SDValue FalseBB = User.getOperand(1);
6505             SDValue NewBR =
6506               DAG.UpdateNodeOperands(User, User.getOperand(0), Dest);
6507             assert(NewBR == User);
6508             Dest = FalseBB;
6509
6510             Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
6511                                 Chain, Dest, CC, Cmp);
6512             X86::CondCode CCode =
6513               (X86::CondCode)Cond.getOperand(1).getConstantOperandVal(0);
6514             CCode = X86::GetOppositeBranchCondition(CCode);
6515             CC = DAG.getConstant(CCode, MVT::i8);
6516             Cond = Cmp;
6517             addTest = false;
6518           }
6519         }
6520       }
6521     } else if (Cond.hasOneUse() && isXor1OfSetCC(Cond)) {
6522       // Recognize for xorb (setcc), 1 patterns. The xor inverts the condition.
6523       // It should be transformed during dag combiner except when the condition
6524       // is set by a arithmetics with overflow node.
6525       X86::CondCode CCode =
6526         (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
6527       CCode = X86::GetOppositeBranchCondition(CCode);
6528       CC = DAG.getConstant(CCode, MVT::i8);
6529       Cond = Cond.getOperand(0).getOperand(1);
6530       addTest = false;
6531     }
6532   }
6533
6534   if (addTest) {
6535     // Look pass the truncate.
6536     if (Cond.getOpcode() == ISD::TRUNCATE)
6537       Cond = Cond.getOperand(0);
6538
6539     // We know the result of AND is compared against zero. Try to match
6540     // it to BT.
6541     if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) { 
6542       SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, dl, DAG);
6543       if (NewSetCC.getNode()) {
6544         CC = NewSetCC.getOperand(0);
6545         Cond = NewSetCC.getOperand(1);
6546         addTest = false;
6547       }
6548     }
6549   }
6550
6551   if (addTest) {
6552     CC = DAG.getConstant(X86::COND_NE, MVT::i8);
6553     Cond = EmitTest(Cond, X86::COND_NE, DAG);
6554   }
6555   return DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
6556                      Chain, Dest, CC, Cond);
6557 }
6558
6559
6560 // Lower dynamic stack allocation to _alloca call for Cygwin/Mingw targets.
6561 // Calls to _alloca is needed to probe the stack when allocating more than 4k
6562 // bytes in one go. Touching the stack at 4K increments is necessary to ensure
6563 // that the guard pages used by the OS virtual memory manager are allocated in
6564 // correct sequence.
6565 SDValue
6566 X86TargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
6567                                            SelectionDAG &DAG) const {
6568   assert(Subtarget->isTargetCygMing() &&
6569          "This should be used only on Cygwin/Mingw targets");
6570   DebugLoc dl = Op.getDebugLoc();
6571
6572   // Get the inputs.
6573   SDValue Chain = Op.getOperand(0);
6574   SDValue Size  = Op.getOperand(1);
6575   // FIXME: Ensure alignment here
6576
6577   SDValue Flag;
6578
6579   EVT IntPtr = getPointerTy();
6580   EVT SPTy = Subtarget->is64Bit() ? MVT::i64 : MVT::i32;
6581
6582   Chain = DAG.getCopyToReg(Chain, dl, X86::EAX, Size, Flag);
6583   Flag = Chain.getValue(1);
6584
6585   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Flag);
6586
6587   Chain = DAG.getNode(X86ISD::MINGW_ALLOCA, dl, NodeTys, Chain, Flag);
6588   Flag = Chain.getValue(1);
6589
6590   Chain = DAG.getCopyFromReg(Chain, dl, X86StackPtr, SPTy).getValue(1);
6591
6592   SDValue Ops1[2] = { Chain.getValue(0), Chain };
6593   return DAG.getMergeValues(Ops1, 2, dl);
6594 }
6595
6596 SDValue
6597 X86TargetLowering::EmitTargetCodeForMemset(SelectionDAG &DAG, DebugLoc dl,
6598                                            SDValue Chain,
6599                                            SDValue Dst, SDValue Src,
6600                                            SDValue Size, unsigned Align,
6601                                            bool isVolatile,
6602                                            const Value *DstSV,
6603                                            uint64_t DstSVOff) const {
6604   ConstantSDNode *ConstantSize = dyn_cast<ConstantSDNode>(Size);
6605
6606   // If not DWORD aligned or size is more than the threshold, call the library.
6607   // The libc version is likely to be faster for these cases. It can use the
6608   // address value and run time information about the CPU.
6609   if ((Align & 3) != 0 ||
6610       !ConstantSize ||
6611       ConstantSize->getZExtValue() >
6612         getSubtarget()->getMaxInlineSizeThreshold()) {
6613     SDValue InFlag(0, 0);
6614
6615     // Check to see if there is a specialized entry-point for memory zeroing.
6616     ConstantSDNode *V = dyn_cast<ConstantSDNode>(Src);
6617
6618     if (const char *bzeroEntry =  V &&
6619         V->isNullValue() ? Subtarget->getBZeroEntry() : 0) {
6620       EVT IntPtr = getPointerTy();
6621       const Type *IntPtrTy = TD->getIntPtrType(*DAG.getContext());
6622       TargetLowering::ArgListTy Args;
6623       TargetLowering::ArgListEntry Entry;
6624       Entry.Node = Dst;
6625       Entry.Ty = IntPtrTy;
6626       Args.push_back(Entry);
6627       Entry.Node = Size;
6628       Args.push_back(Entry);
6629       std::pair<SDValue,SDValue> CallResult =
6630         LowerCallTo(Chain, Type::getVoidTy(*DAG.getContext()),
6631                     false, false, false, false,
6632                     0, CallingConv::C, false, /*isReturnValueUsed=*/false,
6633                     DAG.getExternalSymbol(bzeroEntry, IntPtr), Args, DAG, dl);
6634       return CallResult.second;
6635     }
6636
6637     // Otherwise have the target-independent code call memset.
6638     return SDValue();
6639   }
6640
6641   uint64_t SizeVal = ConstantSize->getZExtValue();
6642   SDValue InFlag(0, 0);
6643   EVT AVT;
6644   SDValue Count;
6645   ConstantSDNode *ValC = dyn_cast<ConstantSDNode>(Src);
6646   unsigned BytesLeft = 0;
6647   bool TwoRepStos = false;
6648   if (ValC) {
6649     unsigned ValReg;
6650     uint64_t Val = ValC->getZExtValue() & 255;
6651
6652     // If the value is a constant, then we can potentially use larger sets.
6653     switch (Align & 3) {
6654     case 2:   // WORD aligned
6655       AVT = MVT::i16;
6656       ValReg = X86::AX;
6657       Val = (Val << 8) | Val;
6658       break;
6659     case 0:  // DWORD aligned
6660       AVT = MVT::i32;
6661       ValReg = X86::EAX;
6662       Val = (Val << 8)  | Val;
6663       Val = (Val << 16) | Val;
6664       if (Subtarget->is64Bit() && ((Align & 0x7) == 0)) {  // QWORD aligned
6665         AVT = MVT::i64;
6666         ValReg = X86::RAX;
6667         Val = (Val << 32) | Val;
6668       }
6669       break;
6670     default:  // Byte aligned
6671       AVT = MVT::i8;
6672       ValReg = X86::AL;
6673       Count = DAG.getIntPtrConstant(SizeVal);
6674       break;
6675     }
6676
6677     if (AVT.bitsGT(MVT::i8)) {
6678       unsigned UBytes = AVT.getSizeInBits() / 8;
6679       Count = DAG.getIntPtrConstant(SizeVal / UBytes);
6680       BytesLeft = SizeVal % UBytes;
6681     }
6682
6683     Chain  = DAG.getCopyToReg(Chain, dl, ValReg, DAG.getConstant(Val, AVT),
6684                               InFlag);
6685     InFlag = Chain.getValue(1);
6686   } else {
6687     AVT = MVT::i8;
6688     Count  = DAG.getIntPtrConstant(SizeVal);
6689     Chain  = DAG.getCopyToReg(Chain, dl, X86::AL, Src, InFlag);
6690     InFlag = Chain.getValue(1);
6691   }
6692
6693   Chain  = DAG.getCopyToReg(Chain, dl, Subtarget->is64Bit() ? X86::RCX :
6694                                                               X86::ECX,
6695                             Count, InFlag);
6696   InFlag = Chain.getValue(1);
6697   Chain  = DAG.getCopyToReg(Chain, dl, Subtarget->is64Bit() ? X86::RDI :
6698                                                               X86::EDI,
6699                             Dst, InFlag);
6700   InFlag = Chain.getValue(1);
6701
6702   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Flag);
6703   SDValue Ops[] = { Chain, DAG.getValueType(AVT), InFlag };
6704   Chain = DAG.getNode(X86ISD::REP_STOS, dl, Tys, Ops, array_lengthof(Ops));
6705
6706   if (TwoRepStos) {
6707     InFlag = Chain.getValue(1);
6708     Count  = Size;
6709     EVT CVT = Count.getValueType();
6710     SDValue Left = DAG.getNode(ISD::AND, dl, CVT, Count,
6711                                DAG.getConstant((AVT == MVT::i64) ? 7 : 3, CVT));
6712     Chain  = DAG.getCopyToReg(Chain, dl, (CVT == MVT::i64) ? X86::RCX :
6713                                                              X86::ECX,
6714                               Left, InFlag);
6715     InFlag = Chain.getValue(1);
6716     Tys = DAG.getVTList(MVT::Other, MVT::Flag);
6717     SDValue Ops[] = { Chain, DAG.getValueType(MVT::i8), InFlag };
6718     Chain = DAG.getNode(X86ISD::REP_STOS, dl, Tys, Ops, array_lengthof(Ops));
6719   } else if (BytesLeft) {
6720     // Handle the last 1 - 7 bytes.
6721     unsigned Offset = SizeVal - BytesLeft;
6722     EVT AddrVT = Dst.getValueType();
6723     EVT SizeVT = Size.getValueType();
6724
6725     Chain = DAG.getMemset(Chain, dl,
6726                           DAG.getNode(ISD::ADD, dl, AddrVT, Dst,
6727                                       DAG.getConstant(Offset, AddrVT)),
6728                           Src,
6729                           DAG.getConstant(BytesLeft, SizeVT),
6730                           Align, isVolatile, DstSV, DstSVOff + Offset);
6731   }
6732
6733   // TODO: Use a Tokenfactor, as in memcpy, instead of a single chain.
6734   return Chain;
6735 }
6736
6737 SDValue
6738 X86TargetLowering::EmitTargetCodeForMemcpy(SelectionDAG &DAG, DebugLoc dl,
6739                                       SDValue Chain, SDValue Dst, SDValue Src,
6740                                       SDValue Size, unsigned Align,
6741                                       bool isVolatile, bool AlwaysInline,
6742                                       const Value *DstSV,
6743                                       uint64_t DstSVOff,
6744                                       const Value *SrcSV,
6745                                       uint64_t SrcSVOff) const {
6746   // This requires the copy size to be a constant, preferrably
6747   // within a subtarget-specific limit.
6748   ConstantSDNode *ConstantSize = dyn_cast<ConstantSDNode>(Size);
6749   if (!ConstantSize)
6750     return SDValue();
6751   uint64_t SizeVal = ConstantSize->getZExtValue();
6752   if (!AlwaysInline && SizeVal > getSubtarget()->getMaxInlineSizeThreshold())
6753     return SDValue();
6754
6755   /// If not DWORD aligned, call the library.
6756   if ((Align & 3) != 0)
6757     return SDValue();
6758
6759   // DWORD aligned
6760   EVT AVT = MVT::i32;
6761   if (Subtarget->is64Bit() && ((Align & 0x7) == 0))  // QWORD aligned
6762     AVT = MVT::i64;
6763
6764   unsigned UBytes = AVT.getSizeInBits() / 8;
6765   unsigned CountVal = SizeVal / UBytes;
6766   SDValue Count = DAG.getIntPtrConstant(CountVal);
6767   unsigned BytesLeft = SizeVal % UBytes;
6768
6769   SDValue InFlag(0, 0);
6770   Chain  = DAG.getCopyToReg(Chain, dl, Subtarget->is64Bit() ? X86::RCX :
6771                                                               X86::ECX,
6772                             Count, InFlag);
6773   InFlag = Chain.getValue(1);
6774   Chain  = DAG.getCopyToReg(Chain, dl, Subtarget->is64Bit() ? X86::RDI :
6775                                                               X86::EDI,
6776                             Dst, InFlag);
6777   InFlag = Chain.getValue(1);
6778   Chain  = DAG.getCopyToReg(Chain, dl, Subtarget->is64Bit() ? X86::RSI :
6779                                                               X86::ESI,
6780                             Src, InFlag);
6781   InFlag = Chain.getValue(1);
6782
6783   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Flag);
6784   SDValue Ops[] = { Chain, DAG.getValueType(AVT), InFlag };
6785   SDValue RepMovs = DAG.getNode(X86ISD::REP_MOVS, dl, Tys, Ops,
6786                                 array_lengthof(Ops));
6787
6788   SmallVector<SDValue, 4> Results;
6789   Results.push_back(RepMovs);
6790   if (BytesLeft) {
6791     // Handle the last 1 - 7 bytes.
6792     unsigned Offset = SizeVal - BytesLeft;
6793     EVT DstVT = Dst.getValueType();
6794     EVT SrcVT = Src.getValueType();
6795     EVT SizeVT = Size.getValueType();
6796     Results.push_back(DAG.getMemcpy(Chain, dl,
6797                                     DAG.getNode(ISD::ADD, dl, DstVT, Dst,
6798                                                 DAG.getConstant(Offset, DstVT)),
6799                                     DAG.getNode(ISD::ADD, dl, SrcVT, Src,
6800                                                 DAG.getConstant(Offset, SrcVT)),
6801                                     DAG.getConstant(BytesLeft, SizeVT),
6802                                     Align, isVolatile, AlwaysInline,
6803                                     DstSV, DstSVOff + Offset,
6804                                     SrcSV, SrcSVOff + Offset));
6805   }
6806
6807   return DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
6808                      &Results[0], Results.size());
6809 }
6810
6811 SDValue X86TargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) const {
6812   MachineFunction &MF = DAG.getMachineFunction();
6813   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
6814
6815   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
6816   DebugLoc dl = Op.getDebugLoc();
6817
6818   if (!Subtarget->is64Bit()) {
6819     // vastart just stores the address of the VarArgsFrameIndex slot into the
6820     // memory location argument.
6821     SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
6822                                    getPointerTy());
6823     return DAG.getStore(Op.getOperand(0), dl, FR, Op.getOperand(1), SV, 0,
6824                         false, false, 0);
6825   }
6826
6827   // __va_list_tag:
6828   //   gp_offset         (0 - 6 * 8)
6829   //   fp_offset         (48 - 48 + 8 * 16)
6830   //   overflow_arg_area (point to parameters coming in memory).
6831   //   reg_save_area
6832   SmallVector<SDValue, 8> MemOps;
6833   SDValue FIN = Op.getOperand(1);
6834   // Store gp_offset
6835   SDValue Store = DAG.getStore(Op.getOperand(0), dl,
6836                                DAG.getConstant(FuncInfo->getVarArgsGPOffset(),
6837                                                MVT::i32),
6838                                FIN, SV, 0, false, false, 0);
6839   MemOps.push_back(Store);
6840
6841   // Store fp_offset
6842   FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(),
6843                     FIN, DAG.getIntPtrConstant(4));
6844   Store = DAG.getStore(Op.getOperand(0), dl,
6845                        DAG.getConstant(FuncInfo->getVarArgsFPOffset(),
6846                                        MVT::i32),
6847                        FIN, SV, 0, false, false, 0);
6848   MemOps.push_back(Store);
6849
6850   // Store ptr to overflow_arg_area
6851   FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(),
6852                     FIN, DAG.getIntPtrConstant(4));
6853   SDValue OVFIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
6854                                     getPointerTy());
6855   Store = DAG.getStore(Op.getOperand(0), dl, OVFIN, FIN, SV, 0,
6856                        false, false, 0);
6857   MemOps.push_back(Store);
6858
6859   // Store ptr to reg_save_area.
6860   FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(),
6861                     FIN, DAG.getIntPtrConstant(8));
6862   SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
6863                                     getPointerTy());
6864   Store = DAG.getStore(Op.getOperand(0), dl, RSFIN, FIN, SV, 0,
6865                        false, false, 0);
6866   MemOps.push_back(Store);
6867   return DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
6868                      &MemOps[0], MemOps.size());
6869 }
6870
6871 SDValue X86TargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) const {
6872   // X86-64 va_list is a struct { i32, i32, i8*, i8* }.
6873   assert(Subtarget->is64Bit() && "This code only handles 64-bit va_arg!");
6874   SDValue Chain = Op.getOperand(0);
6875   SDValue SrcPtr = Op.getOperand(1);
6876   SDValue SrcSV = Op.getOperand(2);
6877
6878   report_fatal_error("VAArgInst is not yet implemented for x86-64!");
6879   return SDValue();
6880 }
6881
6882 SDValue X86TargetLowering::LowerVACOPY(SDValue Op, SelectionDAG &DAG) const {
6883   // X86-64 va_list is a struct { i32, i32, i8*, i8* }.
6884   assert(Subtarget->is64Bit() && "This code only handles 64-bit va_copy!");
6885   SDValue Chain = Op.getOperand(0);
6886   SDValue DstPtr = Op.getOperand(1);
6887   SDValue SrcPtr = Op.getOperand(2);
6888   const Value *DstSV = cast<SrcValueSDNode>(Op.getOperand(3))->getValue();
6889   const Value *SrcSV = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
6890   DebugLoc dl = Op.getDebugLoc();
6891
6892   return DAG.getMemcpy(Chain, dl, DstPtr, SrcPtr,
6893                        DAG.getIntPtrConstant(24), 8, /*isVolatile*/false,
6894                        false, DstSV, 0, SrcSV, 0);
6895 }
6896
6897 SDValue
6898 X86TargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op, SelectionDAG &DAG) const {
6899   DebugLoc dl = Op.getDebugLoc();
6900   unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
6901   switch (IntNo) {
6902   default: return SDValue();    // Don't custom lower most intrinsics.
6903   // Comparison intrinsics.
6904   case Intrinsic::x86_sse_comieq_ss:
6905   case Intrinsic::x86_sse_comilt_ss:
6906   case Intrinsic::x86_sse_comile_ss:
6907   case Intrinsic::x86_sse_comigt_ss:
6908   case Intrinsic::x86_sse_comige_ss:
6909   case Intrinsic::x86_sse_comineq_ss:
6910   case Intrinsic::x86_sse_ucomieq_ss:
6911   case Intrinsic::x86_sse_ucomilt_ss:
6912   case Intrinsic::x86_sse_ucomile_ss:
6913   case Intrinsic::x86_sse_ucomigt_ss:
6914   case Intrinsic::x86_sse_ucomige_ss:
6915   case Intrinsic::x86_sse_ucomineq_ss:
6916   case Intrinsic::x86_sse2_comieq_sd:
6917   case Intrinsic::x86_sse2_comilt_sd:
6918   case Intrinsic::x86_sse2_comile_sd:
6919   case Intrinsic::x86_sse2_comigt_sd:
6920   case Intrinsic::x86_sse2_comige_sd:
6921   case Intrinsic::x86_sse2_comineq_sd:
6922   case Intrinsic::x86_sse2_ucomieq_sd:
6923   case Intrinsic::x86_sse2_ucomilt_sd:
6924   case Intrinsic::x86_sse2_ucomile_sd:
6925   case Intrinsic::x86_sse2_ucomigt_sd:
6926   case Intrinsic::x86_sse2_ucomige_sd:
6927   case Intrinsic::x86_sse2_ucomineq_sd: {
6928     unsigned Opc = 0;
6929     ISD::CondCode CC = ISD::SETCC_INVALID;
6930     switch (IntNo) {
6931     default: break;
6932     case Intrinsic::x86_sse_comieq_ss:
6933     case Intrinsic::x86_sse2_comieq_sd:
6934       Opc = X86ISD::COMI;
6935       CC = ISD::SETEQ;
6936       break;
6937     case Intrinsic::x86_sse_comilt_ss:
6938     case Intrinsic::x86_sse2_comilt_sd:
6939       Opc = X86ISD::COMI;
6940       CC = ISD::SETLT;
6941       break;
6942     case Intrinsic::x86_sse_comile_ss:
6943     case Intrinsic::x86_sse2_comile_sd:
6944       Opc = X86ISD::COMI;
6945       CC = ISD::SETLE;
6946       break;
6947     case Intrinsic::x86_sse_comigt_ss:
6948     case Intrinsic::x86_sse2_comigt_sd:
6949       Opc = X86ISD::COMI;
6950       CC = ISD::SETGT;
6951       break;
6952     case Intrinsic::x86_sse_comige_ss:
6953     case Intrinsic::x86_sse2_comige_sd:
6954       Opc = X86ISD::COMI;
6955       CC = ISD::SETGE;
6956       break;
6957     case Intrinsic::x86_sse_comineq_ss:
6958     case Intrinsic::x86_sse2_comineq_sd:
6959       Opc = X86ISD::COMI;
6960       CC = ISD::SETNE;
6961       break;
6962     case Intrinsic::x86_sse_ucomieq_ss:
6963     case Intrinsic::x86_sse2_ucomieq_sd:
6964       Opc = X86ISD::UCOMI;
6965       CC = ISD::SETEQ;
6966       break;
6967     case Intrinsic::x86_sse_ucomilt_ss:
6968     case Intrinsic::x86_sse2_ucomilt_sd:
6969       Opc = X86ISD::UCOMI;
6970       CC = ISD::SETLT;
6971       break;
6972     case Intrinsic::x86_sse_ucomile_ss:
6973     case Intrinsic::x86_sse2_ucomile_sd:
6974       Opc = X86ISD::UCOMI;
6975       CC = ISD::SETLE;
6976       break;
6977     case Intrinsic::x86_sse_ucomigt_ss:
6978     case Intrinsic::x86_sse2_ucomigt_sd:
6979       Opc = X86ISD::UCOMI;
6980       CC = ISD::SETGT;
6981       break;
6982     case Intrinsic::x86_sse_ucomige_ss:
6983     case Intrinsic::x86_sse2_ucomige_sd:
6984       Opc = X86ISD::UCOMI;
6985       CC = ISD::SETGE;
6986       break;
6987     case Intrinsic::x86_sse_ucomineq_ss:
6988     case Intrinsic::x86_sse2_ucomineq_sd:
6989       Opc = X86ISD::UCOMI;
6990       CC = ISD::SETNE;
6991       break;
6992     }
6993
6994     SDValue LHS = Op.getOperand(1);
6995     SDValue RHS = Op.getOperand(2);
6996     unsigned X86CC = TranslateX86CC(CC, true, LHS, RHS, DAG);
6997     assert(X86CC != X86::COND_INVALID && "Unexpected illegal condition!");
6998     SDValue Cond = DAG.getNode(Opc, dl, MVT::i32, LHS, RHS);
6999     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
7000                                 DAG.getConstant(X86CC, MVT::i8), Cond);
7001     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
7002   }
7003   // ptest intrinsics. The intrinsic these come from are designed to return
7004   // an integer value, not just an instruction so lower it to the ptest
7005   // pattern and a setcc for the result.
7006   case Intrinsic::x86_sse41_ptestz:
7007   case Intrinsic::x86_sse41_ptestc:
7008   case Intrinsic::x86_sse41_ptestnzc:{
7009     unsigned X86CC = 0;
7010     switch (IntNo) {
7011     default: llvm_unreachable("Bad fallthrough in Intrinsic lowering.");
7012     case Intrinsic::x86_sse41_ptestz:
7013       // ZF = 1
7014       X86CC = X86::COND_E;
7015       break;
7016     case Intrinsic::x86_sse41_ptestc:
7017       // CF = 1
7018       X86CC = X86::COND_B;
7019       break;
7020     case Intrinsic::x86_sse41_ptestnzc:
7021       // ZF and CF = 0
7022       X86CC = X86::COND_A;
7023       break;
7024     }
7025
7026     SDValue LHS = Op.getOperand(1);
7027     SDValue RHS = Op.getOperand(2);
7028     SDValue Test = DAG.getNode(X86ISD::PTEST, dl, MVT::i32, LHS, RHS);
7029     SDValue CC = DAG.getConstant(X86CC, MVT::i8);
7030     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8, CC, Test);
7031     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
7032   }
7033
7034   // Fix vector shift instructions where the last operand is a non-immediate
7035   // i32 value.
7036   case Intrinsic::x86_sse2_pslli_w:
7037   case Intrinsic::x86_sse2_pslli_d:
7038   case Intrinsic::x86_sse2_pslli_q:
7039   case Intrinsic::x86_sse2_psrli_w:
7040   case Intrinsic::x86_sse2_psrli_d:
7041   case Intrinsic::x86_sse2_psrli_q:
7042   case Intrinsic::x86_sse2_psrai_w:
7043   case Intrinsic::x86_sse2_psrai_d:
7044   case Intrinsic::x86_mmx_pslli_w:
7045   case Intrinsic::x86_mmx_pslli_d:
7046   case Intrinsic::x86_mmx_pslli_q:
7047   case Intrinsic::x86_mmx_psrli_w:
7048   case Intrinsic::x86_mmx_psrli_d:
7049   case Intrinsic::x86_mmx_psrli_q:
7050   case Intrinsic::x86_mmx_psrai_w:
7051   case Intrinsic::x86_mmx_psrai_d: {
7052     SDValue ShAmt = Op.getOperand(2);
7053     if (isa<ConstantSDNode>(ShAmt))
7054       return SDValue();
7055
7056     unsigned NewIntNo = 0;
7057     EVT ShAmtVT = MVT::v4i32;
7058     switch (IntNo) {
7059     case Intrinsic::x86_sse2_pslli_w:
7060       NewIntNo = Intrinsic::x86_sse2_psll_w;
7061       break;
7062     case Intrinsic::x86_sse2_pslli_d:
7063       NewIntNo = Intrinsic::x86_sse2_psll_d;
7064       break;
7065     case Intrinsic::x86_sse2_pslli_q:
7066       NewIntNo = Intrinsic::x86_sse2_psll_q;
7067       break;
7068     case Intrinsic::x86_sse2_psrli_w:
7069       NewIntNo = Intrinsic::x86_sse2_psrl_w;
7070       break;
7071     case Intrinsic::x86_sse2_psrli_d:
7072       NewIntNo = Intrinsic::x86_sse2_psrl_d;
7073       break;
7074     case Intrinsic::x86_sse2_psrli_q:
7075       NewIntNo = Intrinsic::x86_sse2_psrl_q;
7076       break;
7077     case Intrinsic::x86_sse2_psrai_w:
7078       NewIntNo = Intrinsic::x86_sse2_psra_w;
7079       break;
7080     case Intrinsic::x86_sse2_psrai_d:
7081       NewIntNo = Intrinsic::x86_sse2_psra_d;
7082       break;
7083     default: {
7084       ShAmtVT = MVT::v2i32;
7085       switch (IntNo) {
7086       case Intrinsic::x86_mmx_pslli_w:
7087         NewIntNo = Intrinsic::x86_mmx_psll_w;
7088         break;
7089       case Intrinsic::x86_mmx_pslli_d:
7090         NewIntNo = Intrinsic::x86_mmx_psll_d;
7091         break;
7092       case Intrinsic::x86_mmx_pslli_q:
7093         NewIntNo = Intrinsic::x86_mmx_psll_q;
7094         break;
7095       case Intrinsic::x86_mmx_psrli_w:
7096         NewIntNo = Intrinsic::x86_mmx_psrl_w;
7097         break;
7098       case Intrinsic::x86_mmx_psrli_d:
7099         NewIntNo = Intrinsic::x86_mmx_psrl_d;
7100         break;
7101       case Intrinsic::x86_mmx_psrli_q:
7102         NewIntNo = Intrinsic::x86_mmx_psrl_q;
7103         break;
7104       case Intrinsic::x86_mmx_psrai_w:
7105         NewIntNo = Intrinsic::x86_mmx_psra_w;
7106         break;
7107       case Intrinsic::x86_mmx_psrai_d:
7108         NewIntNo = Intrinsic::x86_mmx_psra_d;
7109         break;
7110       default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
7111       }
7112       break;
7113     }
7114     }
7115
7116     // The vector shift intrinsics with scalars uses 32b shift amounts but
7117     // the sse2/mmx shift instructions reads 64 bits. Set the upper 32 bits
7118     // to be zero.
7119     SDValue ShOps[4];
7120     ShOps[0] = ShAmt;
7121     ShOps[1] = DAG.getConstant(0, MVT::i32);
7122     if (ShAmtVT == MVT::v4i32) {
7123       ShOps[2] = DAG.getUNDEF(MVT::i32);
7124       ShOps[3] = DAG.getUNDEF(MVT::i32);
7125       ShAmt =  DAG.getNode(ISD::BUILD_VECTOR, dl, ShAmtVT, &ShOps[0], 4);
7126     } else {
7127       ShAmt =  DAG.getNode(ISD::BUILD_VECTOR, dl, ShAmtVT, &ShOps[0], 2);
7128     }
7129
7130     EVT VT = Op.getValueType();
7131     ShAmt = DAG.getNode(ISD::BIT_CONVERT, dl, VT, ShAmt);
7132     return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
7133                        DAG.getConstant(NewIntNo, MVT::i32),
7134                        Op.getOperand(1), ShAmt);
7135   }
7136   }
7137 }
7138
7139 SDValue X86TargetLowering::LowerRETURNADDR(SDValue Op,
7140                                            SelectionDAG &DAG) const {
7141   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
7142   DebugLoc dl = Op.getDebugLoc();
7143
7144   if (Depth > 0) {
7145     SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
7146     SDValue Offset =
7147       DAG.getConstant(TD->getPointerSize(),
7148                       Subtarget->is64Bit() ? MVT::i64 : MVT::i32);
7149     return DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(),
7150                        DAG.getNode(ISD::ADD, dl, getPointerTy(),
7151                                    FrameAddr, Offset),
7152                        NULL, 0, false, false, 0);
7153   }
7154
7155   // Just load the return address.
7156   SDValue RetAddrFI = getReturnAddressFrameIndex(DAG);
7157   return DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(),
7158                      RetAddrFI, NULL, 0, false, false, 0);
7159 }
7160
7161 SDValue X86TargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
7162   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
7163   MFI->setFrameAddressIsTaken(true);
7164   EVT VT = Op.getValueType();
7165   DebugLoc dl = Op.getDebugLoc();  // FIXME probably not meaningful
7166   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
7167   unsigned FrameReg = Subtarget->is64Bit() ? X86::RBP : X86::EBP;
7168   SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
7169   while (Depth--)
7170     FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr, NULL, 0,
7171                             false, false, 0);
7172   return FrameAddr;
7173 }
7174
7175 SDValue X86TargetLowering::LowerFRAME_TO_ARGS_OFFSET(SDValue Op,
7176                                                      SelectionDAG &DAG) const {
7177   return DAG.getIntPtrConstant(2*TD->getPointerSize());
7178 }
7179
7180 SDValue X86TargetLowering::LowerEH_RETURN(SDValue Op, SelectionDAG &DAG) const {
7181   MachineFunction &MF = DAG.getMachineFunction();
7182   SDValue Chain     = Op.getOperand(0);
7183   SDValue Offset    = Op.getOperand(1);
7184   SDValue Handler   = Op.getOperand(2);
7185   DebugLoc dl       = Op.getDebugLoc();
7186
7187   SDValue Frame = DAG.getRegister(Subtarget->is64Bit() ? X86::RBP : X86::EBP,
7188                                   getPointerTy());
7189   unsigned StoreAddrReg = (Subtarget->is64Bit() ? X86::RCX : X86::ECX);
7190
7191   SDValue StoreAddr = DAG.getNode(ISD::SUB, dl, getPointerTy(), Frame,
7192                                   DAG.getIntPtrConstant(-TD->getPointerSize()));
7193   StoreAddr = DAG.getNode(ISD::ADD, dl, getPointerTy(), StoreAddr, Offset);
7194   Chain = DAG.getStore(Chain, dl, Handler, StoreAddr, NULL, 0, false, false, 0);
7195   Chain = DAG.getCopyToReg(Chain, dl, StoreAddrReg, StoreAddr);
7196   MF.getRegInfo().addLiveOut(StoreAddrReg);
7197
7198   return DAG.getNode(X86ISD::EH_RETURN, dl,
7199                      MVT::Other,
7200                      Chain, DAG.getRegister(StoreAddrReg, getPointerTy()));
7201 }
7202
7203 SDValue X86TargetLowering::LowerTRAMPOLINE(SDValue Op,
7204                                              SelectionDAG &DAG) const {
7205   SDValue Root = Op.getOperand(0);
7206   SDValue Trmp = Op.getOperand(1); // trampoline
7207   SDValue FPtr = Op.getOperand(2); // nested function
7208   SDValue Nest = Op.getOperand(3); // 'nest' parameter value
7209   DebugLoc dl  = Op.getDebugLoc();
7210
7211   const Value *TrmpAddr = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
7212
7213   if (Subtarget->is64Bit()) {
7214     SDValue OutChains[6];
7215
7216     // Large code-model.
7217     const unsigned char JMP64r  = 0xFF; // 64-bit jmp through register opcode.
7218     const unsigned char MOV64ri = 0xB8; // X86::MOV64ri opcode.
7219
7220     const unsigned char N86R10 = RegInfo->getX86RegNum(X86::R10);
7221     const unsigned char N86R11 = RegInfo->getX86RegNum(X86::R11);
7222
7223     const unsigned char REX_WB = 0x40 | 0x08 | 0x01; // REX prefix
7224
7225     // Load the pointer to the nested function into R11.
7226     unsigned OpCode = ((MOV64ri | N86R11) << 8) | REX_WB; // movabsq r11
7227     SDValue Addr = Trmp;
7228     OutChains[0] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
7229                                 Addr, TrmpAddr, 0, false, false, 0);
7230
7231     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
7232                        DAG.getConstant(2, MVT::i64));
7233     OutChains[1] = DAG.getStore(Root, dl, FPtr, Addr, TrmpAddr, 2,
7234                                 false, false, 2);
7235
7236     // Load the 'nest' parameter value into R10.
7237     // R10 is specified in X86CallingConv.td
7238     OpCode = ((MOV64ri | N86R10) << 8) | REX_WB; // movabsq r10
7239     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
7240                        DAG.getConstant(10, MVT::i64));
7241     OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
7242                                 Addr, TrmpAddr, 10, false, false, 0);
7243
7244     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
7245                        DAG.getConstant(12, MVT::i64));
7246     OutChains[3] = DAG.getStore(Root, dl, Nest, Addr, TrmpAddr, 12,
7247                                 false, false, 2);
7248
7249     // Jump to the nested function.
7250     OpCode = (JMP64r << 8) | REX_WB; // jmpq *...
7251     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
7252                        DAG.getConstant(20, MVT::i64));
7253     OutChains[4] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
7254                                 Addr, TrmpAddr, 20, false, false, 0);
7255
7256     unsigned char ModRM = N86R11 | (4 << 3) | (3 << 6); // ...r11
7257     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
7258                        DAG.getConstant(22, MVT::i64));
7259     OutChains[5] = DAG.getStore(Root, dl, DAG.getConstant(ModRM, MVT::i8), Addr,
7260                                 TrmpAddr, 22, false, false, 0);
7261
7262     SDValue Ops[] =
7263       { Trmp, DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains, 6) };
7264     return DAG.getMergeValues(Ops, 2, dl);
7265   } else {
7266     const Function *Func =
7267       cast<Function>(cast<SrcValueSDNode>(Op.getOperand(5))->getValue());
7268     CallingConv::ID CC = Func->getCallingConv();
7269     unsigned NestReg;
7270
7271     switch (CC) {
7272     default:
7273       llvm_unreachable("Unsupported calling convention");
7274     case CallingConv::C:
7275     case CallingConv::X86_StdCall: {
7276       // Pass 'nest' parameter in ECX.
7277       // Must be kept in sync with X86CallingConv.td
7278       NestReg = X86::ECX;
7279
7280       // Check that ECX wasn't needed by an 'inreg' parameter.
7281       const FunctionType *FTy = Func->getFunctionType();
7282       const AttrListPtr &Attrs = Func->getAttributes();
7283
7284       if (!Attrs.isEmpty() && !Func->isVarArg()) {
7285         unsigned InRegCount = 0;
7286         unsigned Idx = 1;
7287
7288         for (FunctionType::param_iterator I = FTy->param_begin(),
7289              E = FTy->param_end(); I != E; ++I, ++Idx)
7290           if (Attrs.paramHasAttr(Idx, Attribute::InReg))
7291             // FIXME: should only count parameters that are lowered to integers.
7292             InRegCount += (TD->getTypeSizeInBits(*I) + 31) / 32;
7293
7294         if (InRegCount > 2) {
7295           report_fatal_error("Nest register in use - reduce number of inreg parameters!");
7296         }
7297       }
7298       break;
7299     }
7300     case CallingConv::X86_FastCall:
7301     case CallingConv::Fast:
7302       // Pass 'nest' parameter in EAX.
7303       // Must be kept in sync with X86CallingConv.td
7304       NestReg = X86::EAX;
7305       break;
7306     }
7307
7308     SDValue OutChains[4];
7309     SDValue Addr, Disp;
7310
7311     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
7312                        DAG.getConstant(10, MVT::i32));
7313     Disp = DAG.getNode(ISD::SUB, dl, MVT::i32, FPtr, Addr);
7314
7315     // This is storing the opcode for MOV32ri.
7316     const unsigned char MOV32ri = 0xB8; // X86::MOV32ri's opcode byte.
7317     const unsigned char N86Reg = RegInfo->getX86RegNum(NestReg);
7318     OutChains[0] = DAG.getStore(Root, dl,
7319                                 DAG.getConstant(MOV32ri|N86Reg, MVT::i8),
7320                                 Trmp, TrmpAddr, 0, false, false, 0);
7321
7322     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
7323                        DAG.getConstant(1, MVT::i32));
7324     OutChains[1] = DAG.getStore(Root, dl, Nest, Addr, TrmpAddr, 1,
7325                                 false, false, 1);
7326
7327     const unsigned char JMP = 0xE9; // jmp <32bit dst> opcode.
7328     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
7329                        DAG.getConstant(5, MVT::i32));
7330     OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(JMP, MVT::i8), Addr,
7331                                 TrmpAddr, 5, false, false, 1);
7332
7333     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
7334                        DAG.getConstant(6, MVT::i32));
7335     OutChains[3] = DAG.getStore(Root, dl, Disp, Addr, TrmpAddr, 6,
7336                                 false, false, 1);
7337
7338     SDValue Ops[] =
7339       { Trmp, DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains, 4) };
7340     return DAG.getMergeValues(Ops, 2, dl);
7341   }
7342 }
7343
7344 SDValue X86TargetLowering::LowerFLT_ROUNDS_(SDValue Op,
7345                                             SelectionDAG &DAG) const {
7346   /*
7347    The rounding mode is in bits 11:10 of FPSR, and has the following
7348    settings:
7349      00 Round to nearest
7350      01 Round to -inf
7351      10 Round to +inf
7352      11 Round to 0
7353
7354   FLT_ROUNDS, on the other hand, expects the following:
7355     -1 Undefined
7356      0 Round to 0
7357      1 Round to nearest
7358      2 Round to +inf
7359      3 Round to -inf
7360
7361   To perform the conversion, we do:
7362     (((((FPSR & 0x800) >> 11) | ((FPSR & 0x400) >> 9)) + 1) & 3)
7363   */
7364
7365   MachineFunction &MF = DAG.getMachineFunction();
7366   const TargetMachine &TM = MF.getTarget();
7367   const TargetFrameInfo &TFI = *TM.getFrameInfo();
7368   unsigned StackAlignment = TFI.getStackAlignment();
7369   EVT VT = Op.getValueType();
7370   DebugLoc dl = Op.getDebugLoc();
7371
7372   // Save FP Control Word to stack slot
7373   int SSFI = MF.getFrameInfo()->CreateStackObject(2, StackAlignment, false);
7374   SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
7375
7376   SDValue Chain = DAG.getNode(X86ISD::FNSTCW16m, dl, MVT::Other,
7377                               DAG.getEntryNode(), StackSlot);
7378
7379   // Load FP Control Word from stack slot
7380   SDValue CWD = DAG.getLoad(MVT::i16, dl, Chain, StackSlot, NULL, 0,
7381                             false, false, 0);
7382
7383   // Transform as necessary
7384   SDValue CWD1 =
7385     DAG.getNode(ISD::SRL, dl, MVT::i16,
7386                 DAG.getNode(ISD::AND, dl, MVT::i16,
7387                             CWD, DAG.getConstant(0x800, MVT::i16)),
7388                 DAG.getConstant(11, MVT::i8));
7389   SDValue CWD2 =
7390     DAG.getNode(ISD::SRL, dl, MVT::i16,
7391                 DAG.getNode(ISD::AND, dl, MVT::i16,
7392                             CWD, DAG.getConstant(0x400, MVT::i16)),
7393                 DAG.getConstant(9, MVT::i8));
7394
7395   SDValue RetVal =
7396     DAG.getNode(ISD::AND, dl, MVT::i16,
7397                 DAG.getNode(ISD::ADD, dl, MVT::i16,
7398                             DAG.getNode(ISD::OR, dl, MVT::i16, CWD1, CWD2),
7399                             DAG.getConstant(1, MVT::i16)),
7400                 DAG.getConstant(3, MVT::i16));
7401
7402
7403   return DAG.getNode((VT.getSizeInBits() < 16 ?
7404                       ISD::TRUNCATE : ISD::ZERO_EXTEND), dl, VT, RetVal);
7405 }
7406
7407 SDValue X86TargetLowering::LowerCTLZ(SDValue Op, SelectionDAG &DAG) const {
7408   EVT VT = Op.getValueType();
7409   EVT OpVT = VT;
7410   unsigned NumBits = VT.getSizeInBits();
7411   DebugLoc dl = Op.getDebugLoc();
7412
7413   Op = Op.getOperand(0);
7414   if (VT == MVT::i8) {
7415     // Zero extend to i32 since there is not an i8 bsr.
7416     OpVT = MVT::i32;
7417     Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
7418   }
7419
7420   // Issue a bsr (scan bits in reverse) which also sets EFLAGS.
7421   SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
7422   Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
7423
7424   // If src is zero (i.e. bsr sets ZF), returns NumBits.
7425   SDValue Ops[] = {
7426     Op,
7427     DAG.getConstant(NumBits+NumBits-1, OpVT),
7428     DAG.getConstant(X86::COND_E, MVT::i8),
7429     Op.getValue(1)
7430   };
7431   Op = DAG.getNode(X86ISD::CMOV, dl, OpVT, Ops, array_lengthof(Ops));
7432
7433   // Finally xor with NumBits-1.
7434   Op = DAG.getNode(ISD::XOR, dl, OpVT, Op, DAG.getConstant(NumBits-1, OpVT));
7435
7436   if (VT == MVT::i8)
7437     Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
7438   return Op;
7439 }
7440
7441 SDValue X86TargetLowering::LowerCTTZ(SDValue Op, SelectionDAG &DAG) const {
7442   EVT VT = Op.getValueType();
7443   EVT OpVT = VT;
7444   unsigned NumBits = VT.getSizeInBits();
7445   DebugLoc dl = Op.getDebugLoc();
7446
7447   Op = Op.getOperand(0);
7448   if (VT == MVT::i8) {
7449     OpVT = MVT::i32;
7450     Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
7451   }
7452
7453   // Issue a bsf (scan bits forward) which also sets EFLAGS.
7454   SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
7455   Op = DAG.getNode(X86ISD::BSF, dl, VTs, Op);
7456
7457   // If src is zero (i.e. bsf sets ZF), returns NumBits.
7458   SDValue Ops[] = {
7459     Op,
7460     DAG.getConstant(NumBits, OpVT),
7461     DAG.getConstant(X86::COND_E, MVT::i8),
7462     Op.getValue(1)
7463   };
7464   Op = DAG.getNode(X86ISD::CMOV, dl, OpVT, Ops, array_lengthof(Ops));
7465
7466   if (VT == MVT::i8)
7467     Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
7468   return Op;
7469 }
7470
7471 SDValue X86TargetLowering::LowerMUL_V2I64(SDValue Op, SelectionDAG &DAG) const {
7472   EVT VT = Op.getValueType();
7473   assert(VT == MVT::v2i64 && "Only know how to lower V2I64 multiply");
7474   DebugLoc dl = Op.getDebugLoc();
7475
7476   //  ulong2 Ahi = __builtin_ia32_psrlqi128( a, 32);
7477   //  ulong2 Bhi = __builtin_ia32_psrlqi128( b, 32);
7478   //  ulong2 AloBlo = __builtin_ia32_pmuludq128( a, b );
7479   //  ulong2 AloBhi = __builtin_ia32_pmuludq128( a, Bhi );
7480   //  ulong2 AhiBlo = __builtin_ia32_pmuludq128( Ahi, b );
7481   //
7482   //  AloBhi = __builtin_ia32_psllqi128( AloBhi, 32 );
7483   //  AhiBlo = __builtin_ia32_psllqi128( AhiBlo, 32 );
7484   //  return AloBlo + AloBhi + AhiBlo;
7485
7486   SDValue A = Op.getOperand(0);
7487   SDValue B = Op.getOperand(1);
7488
7489   SDValue Ahi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
7490                        DAG.getConstant(Intrinsic::x86_sse2_psrli_q, MVT::i32),
7491                        A, DAG.getConstant(32, MVT::i32));
7492   SDValue Bhi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
7493                        DAG.getConstant(Intrinsic::x86_sse2_psrli_q, MVT::i32),
7494                        B, DAG.getConstant(32, MVT::i32));
7495   SDValue AloBlo = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
7496                        DAG.getConstant(Intrinsic::x86_sse2_pmulu_dq, MVT::i32),
7497                        A, B);
7498   SDValue AloBhi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
7499                        DAG.getConstant(Intrinsic::x86_sse2_pmulu_dq, MVT::i32),
7500                        A, Bhi);
7501   SDValue AhiBlo = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
7502                        DAG.getConstant(Intrinsic::x86_sse2_pmulu_dq, MVT::i32),
7503                        Ahi, B);
7504   AloBhi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
7505                        DAG.getConstant(Intrinsic::x86_sse2_pslli_q, MVT::i32),
7506                        AloBhi, DAG.getConstant(32, MVT::i32));
7507   AhiBlo = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
7508                        DAG.getConstant(Intrinsic::x86_sse2_pslli_q, MVT::i32),
7509                        AhiBlo, DAG.getConstant(32, MVT::i32));
7510   SDValue Res = DAG.getNode(ISD::ADD, dl, VT, AloBlo, AloBhi);
7511   Res = DAG.getNode(ISD::ADD, dl, VT, Res, AhiBlo);
7512   return Res;
7513 }
7514
7515
7516 SDValue X86TargetLowering::LowerXALUO(SDValue Op, SelectionDAG &DAG) const {
7517   // Lower the "add/sub/mul with overflow" instruction into a regular ins plus
7518   // a "setcc" instruction that checks the overflow flag. The "brcond" lowering
7519   // looks for this combo and may remove the "setcc" instruction if the "setcc"
7520   // has only one use.
7521   SDNode *N = Op.getNode();
7522   SDValue LHS = N->getOperand(0);
7523   SDValue RHS = N->getOperand(1);
7524   unsigned BaseOp = 0;
7525   unsigned Cond = 0;
7526   DebugLoc dl = Op.getDebugLoc();
7527
7528   switch (Op.getOpcode()) {
7529   default: llvm_unreachable("Unknown ovf instruction!");
7530   case ISD::SADDO:
7531     // A subtract of one will be selected as a INC. Note that INC doesn't
7532     // set CF, so we can't do this for UADDO.
7533     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op))
7534       if (C->getAPIntValue() == 1) {
7535         BaseOp = X86ISD::INC;
7536         Cond = X86::COND_O;
7537         break;
7538       }
7539     BaseOp = X86ISD::ADD;
7540     Cond = X86::COND_O;
7541     break;
7542   case ISD::UADDO:
7543     BaseOp = X86ISD::ADD;
7544     Cond = X86::COND_B;
7545     break;
7546   case ISD::SSUBO:
7547     // A subtract of one will be selected as a DEC. Note that DEC doesn't
7548     // set CF, so we can't do this for USUBO.
7549     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op))
7550       if (C->getAPIntValue() == 1) {
7551         BaseOp = X86ISD::DEC;
7552         Cond = X86::COND_O;
7553         break;
7554       }
7555     BaseOp = X86ISD::SUB;
7556     Cond = X86::COND_O;
7557     break;
7558   case ISD::USUBO:
7559     BaseOp = X86ISD::SUB;
7560     Cond = X86::COND_B;
7561     break;
7562   case ISD::SMULO:
7563     BaseOp = X86ISD::SMUL;
7564     Cond = X86::COND_O;
7565     break;
7566   case ISD::UMULO:
7567     BaseOp = X86ISD::UMUL;
7568     Cond = X86::COND_B;
7569     break;
7570   }
7571
7572   // Also sets EFLAGS.
7573   SDVTList VTs = DAG.getVTList(N->getValueType(0), MVT::i32);
7574   SDValue Sum = DAG.getNode(BaseOp, dl, VTs, LHS, RHS);
7575
7576   SDValue SetCC =
7577     DAG.getNode(X86ISD::SETCC, dl, N->getValueType(1),
7578                 DAG.getConstant(Cond, MVT::i32), SDValue(Sum.getNode(), 1));
7579
7580   DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), SetCC);
7581   return Sum;
7582 }
7583
7584 SDValue X86TargetLowering::LowerCMP_SWAP(SDValue Op, SelectionDAG &DAG) const {
7585   EVT T = Op.getValueType();
7586   DebugLoc dl = Op.getDebugLoc();
7587   unsigned Reg = 0;
7588   unsigned size = 0;
7589   switch(T.getSimpleVT().SimpleTy) {
7590   default:
7591     assert(false && "Invalid value type!");
7592   case MVT::i8:  Reg = X86::AL;  size = 1; break;
7593   case MVT::i16: Reg = X86::AX;  size = 2; break;
7594   case MVT::i32: Reg = X86::EAX; size = 4; break;
7595   case MVT::i64:
7596     assert(Subtarget->is64Bit() && "Node not type legal!");
7597     Reg = X86::RAX; size = 8;
7598     break;
7599   }
7600   SDValue cpIn = DAG.getCopyToReg(Op.getOperand(0), dl, Reg,
7601                                     Op.getOperand(2), SDValue());
7602   SDValue Ops[] = { cpIn.getValue(0),
7603                     Op.getOperand(1),
7604                     Op.getOperand(3),
7605                     DAG.getTargetConstant(size, MVT::i8),
7606                     cpIn.getValue(1) };
7607   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Flag);
7608   SDValue Result = DAG.getNode(X86ISD::LCMPXCHG_DAG, dl, Tys, Ops, 5);
7609   SDValue cpOut =
7610     DAG.getCopyFromReg(Result.getValue(0), dl, Reg, T, Result.getValue(1));
7611   return cpOut;
7612 }
7613
7614 SDValue X86TargetLowering::LowerREADCYCLECOUNTER(SDValue Op,
7615                                                  SelectionDAG &DAG) const {
7616   assert(Subtarget->is64Bit() && "Result not type legalized?");
7617   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Flag);
7618   SDValue TheChain = Op.getOperand(0);
7619   DebugLoc dl = Op.getDebugLoc();
7620   SDValue rd = DAG.getNode(X86ISD::RDTSC_DAG, dl, Tys, &TheChain, 1);
7621   SDValue rax = DAG.getCopyFromReg(rd, dl, X86::RAX, MVT::i64, rd.getValue(1));
7622   SDValue rdx = DAG.getCopyFromReg(rax.getValue(1), dl, X86::RDX, MVT::i64,
7623                                    rax.getValue(2));
7624   SDValue Tmp = DAG.getNode(ISD::SHL, dl, MVT::i64, rdx,
7625                             DAG.getConstant(32, MVT::i8));
7626   SDValue Ops[] = {
7627     DAG.getNode(ISD::OR, dl, MVT::i64, rax, Tmp),
7628     rdx.getValue(1)
7629   };
7630   return DAG.getMergeValues(Ops, 2, dl);
7631 }
7632
7633 SDValue X86TargetLowering::LowerLOAD_SUB(SDValue Op, SelectionDAG &DAG) const {
7634   SDNode *Node = Op.getNode();
7635   DebugLoc dl = Node->getDebugLoc();
7636   EVT T = Node->getValueType(0);
7637   SDValue negOp = DAG.getNode(ISD::SUB, dl, T,
7638                               DAG.getConstant(0, T), Node->getOperand(2));
7639   return DAG.getAtomic(ISD::ATOMIC_LOAD_ADD, dl,
7640                        cast<AtomicSDNode>(Node)->getMemoryVT(),
7641                        Node->getOperand(0),
7642                        Node->getOperand(1), negOp,
7643                        cast<AtomicSDNode>(Node)->getSrcValue(),
7644                        cast<AtomicSDNode>(Node)->getAlignment());
7645 }
7646
7647 /// LowerOperation - Provide custom lowering hooks for some operations.
7648 ///
7649 SDValue X86TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
7650   switch (Op.getOpcode()) {
7651   default: llvm_unreachable("Should not custom lower this!");
7652   case ISD::ATOMIC_CMP_SWAP:    return LowerCMP_SWAP(Op,DAG);
7653   case ISD::ATOMIC_LOAD_SUB:    return LowerLOAD_SUB(Op,DAG);
7654   case ISD::BUILD_VECTOR:       return LowerBUILD_VECTOR(Op, DAG);
7655   case ISD::CONCAT_VECTORS:     return LowerCONCAT_VECTORS(Op, DAG);
7656   case ISD::VECTOR_SHUFFLE:     return LowerVECTOR_SHUFFLE(Op, DAG);
7657   case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
7658   case ISD::INSERT_VECTOR_ELT:  return LowerINSERT_VECTOR_ELT(Op, DAG);
7659   case ISD::SCALAR_TO_VECTOR:   return LowerSCALAR_TO_VECTOR(Op, DAG);
7660   case ISD::ConstantPool:       return LowerConstantPool(Op, DAG);
7661   case ISD::GlobalAddress:      return LowerGlobalAddress(Op, DAG);
7662   case ISD::GlobalTLSAddress:   return LowerGlobalTLSAddress(Op, DAG);
7663   case ISD::ExternalSymbol:     return LowerExternalSymbol(Op, DAG);
7664   case ISD::BlockAddress:       return LowerBlockAddress(Op, DAG);
7665   case ISD::SHL_PARTS:
7666   case ISD::SRA_PARTS:
7667   case ISD::SRL_PARTS:          return LowerShift(Op, DAG);
7668   case ISD::SINT_TO_FP:         return LowerSINT_TO_FP(Op, DAG);
7669   case ISD::UINT_TO_FP:         return LowerUINT_TO_FP(Op, DAG);
7670   case ISD::FP_TO_SINT:         return LowerFP_TO_SINT(Op, DAG);
7671   case ISD::FP_TO_UINT:         return LowerFP_TO_UINT(Op, DAG);
7672   case ISD::FABS:               return LowerFABS(Op, DAG);
7673   case ISD::FNEG:               return LowerFNEG(Op, DAG);
7674   case ISD::FCOPYSIGN:          return LowerFCOPYSIGN(Op, DAG);
7675   case ISD::SETCC:              return LowerSETCC(Op, DAG);
7676   case ISD::VSETCC:             return LowerVSETCC(Op, DAG);
7677   case ISD::SELECT:             return LowerSELECT(Op, DAG);
7678   case ISD::BRCOND:             return LowerBRCOND(Op, DAG);
7679   case ISD::JumpTable:          return LowerJumpTable(Op, DAG);
7680   case ISD::VASTART:            return LowerVASTART(Op, DAG);
7681   case ISD::VAARG:              return LowerVAARG(Op, DAG);
7682   case ISD::VACOPY:             return LowerVACOPY(Op, DAG);
7683   case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
7684   case ISD::RETURNADDR:         return LowerRETURNADDR(Op, DAG);
7685   case ISD::FRAMEADDR:          return LowerFRAMEADDR(Op, DAG);
7686   case ISD::FRAME_TO_ARGS_OFFSET:
7687                                 return LowerFRAME_TO_ARGS_OFFSET(Op, DAG);
7688   case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG);
7689   case ISD::EH_RETURN:          return LowerEH_RETURN(Op, DAG);
7690   case ISD::TRAMPOLINE:         return LowerTRAMPOLINE(Op, DAG);
7691   case ISD::FLT_ROUNDS_:        return LowerFLT_ROUNDS_(Op, DAG);
7692   case ISD::CTLZ:               return LowerCTLZ(Op, DAG);
7693   case ISD::CTTZ:               return LowerCTTZ(Op, DAG);
7694   case ISD::MUL:                return LowerMUL_V2I64(Op, DAG);
7695   case ISD::SADDO:
7696   case ISD::UADDO:
7697   case ISD::SSUBO:
7698   case ISD::USUBO:
7699   case ISD::SMULO:
7700   case ISD::UMULO:              return LowerXALUO(Op, DAG);
7701   case ISD::READCYCLECOUNTER:   return LowerREADCYCLECOUNTER(Op, DAG);
7702   }
7703 }
7704
7705 void X86TargetLowering::
7706 ReplaceATOMIC_BINARY_64(SDNode *Node, SmallVectorImpl<SDValue>&Results,
7707                         SelectionDAG &DAG, unsigned NewOp) const {
7708   EVT T = Node->getValueType(0);
7709   DebugLoc dl = Node->getDebugLoc();
7710   assert (T == MVT::i64 && "Only know how to expand i64 atomics");
7711
7712   SDValue Chain = Node->getOperand(0);
7713   SDValue In1 = Node->getOperand(1);
7714   SDValue In2L = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
7715                              Node->getOperand(2), DAG.getIntPtrConstant(0));
7716   SDValue In2H = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
7717                              Node->getOperand(2), DAG.getIntPtrConstant(1));
7718   SDValue Ops[] = { Chain, In1, In2L, In2H };
7719   SDVTList Tys = DAG.getVTList(MVT::i32, MVT::i32, MVT::Other);
7720   SDValue Result =
7721     DAG.getMemIntrinsicNode(NewOp, dl, Tys, Ops, 4, MVT::i64,
7722                             cast<MemSDNode>(Node)->getMemOperand());
7723   SDValue OpsF[] = { Result.getValue(0), Result.getValue(1)};
7724   Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, OpsF, 2));
7725   Results.push_back(Result.getValue(2));
7726 }
7727
7728 /// ReplaceNodeResults - Replace a node with an illegal result type
7729 /// with a new node built out of custom code.
7730 void X86TargetLowering::ReplaceNodeResults(SDNode *N,
7731                                            SmallVectorImpl<SDValue>&Results,
7732                                            SelectionDAG &DAG) const {
7733   DebugLoc dl = N->getDebugLoc();
7734   switch (N->getOpcode()) {
7735   default:
7736     assert(false && "Do not know how to custom type legalize this operation!");
7737     return;
7738   case ISD::FP_TO_SINT: {
7739     std::pair<SDValue,SDValue> Vals =
7740         FP_TO_INTHelper(SDValue(N, 0), DAG, true);
7741     SDValue FIST = Vals.first, StackSlot = Vals.second;
7742     if (FIST.getNode() != 0) {
7743       EVT VT = N->getValueType(0);
7744       // Return a load from the stack slot.
7745       Results.push_back(DAG.getLoad(VT, dl, FIST, StackSlot, NULL, 0,
7746                                     false, false, 0));
7747     }
7748     return;
7749   }
7750   case ISD::READCYCLECOUNTER: {
7751     SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Flag);
7752     SDValue TheChain = N->getOperand(0);
7753     SDValue rd = DAG.getNode(X86ISD::RDTSC_DAG, dl, Tys, &TheChain, 1);
7754     SDValue eax = DAG.getCopyFromReg(rd, dl, X86::EAX, MVT::i32,
7755                                      rd.getValue(1));
7756     SDValue edx = DAG.getCopyFromReg(eax.getValue(1), dl, X86::EDX, MVT::i32,
7757                                      eax.getValue(2));
7758     // Use a buildpair to merge the two 32-bit values into a 64-bit one.
7759     SDValue Ops[] = { eax, edx };
7760     Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Ops, 2));
7761     Results.push_back(edx.getValue(1));
7762     return;
7763   }
7764   case ISD::ATOMIC_CMP_SWAP: {
7765     EVT T = N->getValueType(0);
7766     assert (T == MVT::i64 && "Only know how to expand i64 Cmp and Swap");
7767     SDValue cpInL, cpInH;
7768     cpInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(2),
7769                         DAG.getConstant(0, MVT::i32));
7770     cpInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(2),
7771                         DAG.getConstant(1, MVT::i32));
7772     cpInL = DAG.getCopyToReg(N->getOperand(0), dl, X86::EAX, cpInL, SDValue());
7773     cpInH = DAG.getCopyToReg(cpInL.getValue(0), dl, X86::EDX, cpInH,
7774                              cpInL.getValue(1));
7775     SDValue swapInL, swapInH;
7776     swapInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(3),
7777                           DAG.getConstant(0, MVT::i32));
7778     swapInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(3),
7779                           DAG.getConstant(1, MVT::i32));
7780     swapInL = DAG.getCopyToReg(cpInH.getValue(0), dl, X86::EBX, swapInL,
7781                                cpInH.getValue(1));
7782     swapInH = DAG.getCopyToReg(swapInL.getValue(0), dl, X86::ECX, swapInH,
7783                                swapInL.getValue(1));
7784     SDValue Ops[] = { swapInH.getValue(0),
7785                       N->getOperand(1),
7786                       swapInH.getValue(1) };
7787     SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Flag);
7788     SDValue Result = DAG.getNode(X86ISD::LCMPXCHG8_DAG, dl, Tys, Ops, 3);
7789     SDValue cpOutL = DAG.getCopyFromReg(Result.getValue(0), dl, X86::EAX,
7790                                         MVT::i32, Result.getValue(1));
7791     SDValue cpOutH = DAG.getCopyFromReg(cpOutL.getValue(1), dl, X86::EDX,
7792                                         MVT::i32, cpOutL.getValue(2));
7793     SDValue OpsF[] = { cpOutL.getValue(0), cpOutH.getValue(0)};
7794     Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, OpsF, 2));
7795     Results.push_back(cpOutH.getValue(1));
7796     return;
7797   }
7798   case ISD::ATOMIC_LOAD_ADD:
7799     ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMADD64_DAG);
7800     return;
7801   case ISD::ATOMIC_LOAD_AND:
7802     ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMAND64_DAG);
7803     return;
7804   case ISD::ATOMIC_LOAD_NAND:
7805     ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMNAND64_DAG);
7806     return;
7807   case ISD::ATOMIC_LOAD_OR:
7808     ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMOR64_DAG);
7809     return;
7810   case ISD::ATOMIC_LOAD_SUB:
7811     ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMSUB64_DAG);
7812     return;
7813   case ISD::ATOMIC_LOAD_XOR:
7814     ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMXOR64_DAG);
7815     return;
7816   case ISD::ATOMIC_SWAP:
7817     ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMSWAP64_DAG);
7818     return;
7819   }
7820 }
7821
7822 const char *X86TargetLowering::getTargetNodeName(unsigned Opcode) const {
7823   switch (Opcode) {
7824   default: return NULL;
7825   case X86ISD::BSF:                return "X86ISD::BSF";
7826   case X86ISD::BSR:                return "X86ISD::BSR";
7827   case X86ISD::SHLD:               return "X86ISD::SHLD";
7828   case X86ISD::SHRD:               return "X86ISD::SHRD";
7829   case X86ISD::FAND:               return "X86ISD::FAND";
7830   case X86ISD::FOR:                return "X86ISD::FOR";
7831   case X86ISD::FXOR:               return "X86ISD::FXOR";
7832   case X86ISD::FSRL:               return "X86ISD::FSRL";
7833   case X86ISD::FILD:               return "X86ISD::FILD";
7834   case X86ISD::FILD_FLAG:          return "X86ISD::FILD_FLAG";
7835   case X86ISD::FP_TO_INT16_IN_MEM: return "X86ISD::FP_TO_INT16_IN_MEM";
7836   case X86ISD::FP_TO_INT32_IN_MEM: return "X86ISD::FP_TO_INT32_IN_MEM";
7837   case X86ISD::FP_TO_INT64_IN_MEM: return "X86ISD::FP_TO_INT64_IN_MEM";
7838   case X86ISD::FLD:                return "X86ISD::FLD";
7839   case X86ISD::FST:                return "X86ISD::FST";
7840   case X86ISD::CALL:               return "X86ISD::CALL";
7841   case X86ISD::RDTSC_DAG:          return "X86ISD::RDTSC_DAG";
7842   case X86ISD::BT:                 return "X86ISD::BT";
7843   case X86ISD::CMP:                return "X86ISD::CMP";
7844   case X86ISD::COMI:               return "X86ISD::COMI";
7845   case X86ISD::UCOMI:              return "X86ISD::UCOMI";
7846   case X86ISD::SETCC:              return "X86ISD::SETCC";
7847   case X86ISD::SETCC_CARRY:        return "X86ISD::SETCC_CARRY";
7848   case X86ISD::CMOV:               return "X86ISD::CMOV";
7849   case X86ISD::BRCOND:             return "X86ISD::BRCOND";
7850   case X86ISD::RET_FLAG:           return "X86ISD::RET_FLAG";
7851   case X86ISD::REP_STOS:           return "X86ISD::REP_STOS";
7852   case X86ISD::REP_MOVS:           return "X86ISD::REP_MOVS";
7853   case X86ISD::GlobalBaseReg:      return "X86ISD::GlobalBaseReg";
7854   case X86ISD::Wrapper:            return "X86ISD::Wrapper";
7855   case X86ISD::WrapperRIP:         return "X86ISD::WrapperRIP";
7856   case X86ISD::PEXTRB:             return "X86ISD::PEXTRB";
7857   case X86ISD::PEXTRW:             return "X86ISD::PEXTRW";
7858   case X86ISD::INSERTPS:           return "X86ISD::INSERTPS";
7859   case X86ISD::PINSRB:             return "X86ISD::PINSRB";
7860   case X86ISD::PINSRW:             return "X86ISD::PINSRW";
7861   case X86ISD::MMX_PINSRW:         return "X86ISD::MMX_PINSRW";
7862   case X86ISD::PSHUFB:             return "X86ISD::PSHUFB";
7863   case X86ISD::FMAX:               return "X86ISD::FMAX";
7864   case X86ISD::FMIN:               return "X86ISD::FMIN";
7865   case X86ISD::FRSQRT:             return "X86ISD::FRSQRT";
7866   case X86ISD::FRCP:               return "X86ISD::FRCP";
7867   case X86ISD::TLSADDR:            return "X86ISD::TLSADDR";
7868   case X86ISD::SegmentBaseAddress: return "X86ISD::SegmentBaseAddress";
7869   case X86ISD::EH_RETURN:          return "X86ISD::EH_RETURN";
7870   case X86ISD::TC_RETURN:          return "X86ISD::TC_RETURN";
7871   case X86ISD::FNSTCW16m:          return "X86ISD::FNSTCW16m";
7872   case X86ISD::LCMPXCHG_DAG:       return "X86ISD::LCMPXCHG_DAG";
7873   case X86ISD::LCMPXCHG8_DAG:      return "X86ISD::LCMPXCHG8_DAG";
7874   case X86ISD::ATOMADD64_DAG:      return "X86ISD::ATOMADD64_DAG";
7875   case X86ISD::ATOMSUB64_DAG:      return "X86ISD::ATOMSUB64_DAG";
7876   case X86ISD::ATOMOR64_DAG:       return "X86ISD::ATOMOR64_DAG";
7877   case X86ISD::ATOMXOR64_DAG:      return "X86ISD::ATOMXOR64_DAG";
7878   case X86ISD::ATOMAND64_DAG:      return "X86ISD::ATOMAND64_DAG";
7879   case X86ISD::ATOMNAND64_DAG:     return "X86ISD::ATOMNAND64_DAG";
7880   case X86ISD::VZEXT_MOVL:         return "X86ISD::VZEXT_MOVL";
7881   case X86ISD::VZEXT_LOAD:         return "X86ISD::VZEXT_LOAD";
7882   case X86ISD::VSHL:               return "X86ISD::VSHL";
7883   case X86ISD::VSRL:               return "X86ISD::VSRL";
7884   case X86ISD::CMPPD:              return "X86ISD::CMPPD";
7885   case X86ISD::CMPPS:              return "X86ISD::CMPPS";
7886   case X86ISD::PCMPEQB:            return "X86ISD::PCMPEQB";
7887   case X86ISD::PCMPEQW:            return "X86ISD::PCMPEQW";
7888   case X86ISD::PCMPEQD:            return "X86ISD::PCMPEQD";
7889   case X86ISD::PCMPEQQ:            return "X86ISD::PCMPEQQ";
7890   case X86ISD::PCMPGTB:            return "X86ISD::PCMPGTB";
7891   case X86ISD::PCMPGTW:            return "X86ISD::PCMPGTW";
7892   case X86ISD::PCMPGTD:            return "X86ISD::PCMPGTD";
7893   case X86ISD::PCMPGTQ:            return "X86ISD::PCMPGTQ";
7894   case X86ISD::ADD:                return "X86ISD::ADD";
7895   case X86ISD::SUB:                return "X86ISD::SUB";
7896   case X86ISD::SMUL:               return "X86ISD::SMUL";
7897   case X86ISD::UMUL:               return "X86ISD::UMUL";
7898   case X86ISD::INC:                return "X86ISD::INC";
7899   case X86ISD::DEC:                return "X86ISD::DEC";
7900   case X86ISD::OR:                 return "X86ISD::OR";
7901   case X86ISD::XOR:                return "X86ISD::XOR";
7902   case X86ISD::AND:                return "X86ISD::AND";
7903   case X86ISD::MUL_IMM:            return "X86ISD::MUL_IMM";
7904   case X86ISD::PTEST:              return "X86ISD::PTEST";
7905   case X86ISD::VASTART_SAVE_XMM_REGS: return "X86ISD::VASTART_SAVE_XMM_REGS";
7906   case X86ISD::MINGW_ALLOCA:       return "X86ISD::MINGW_ALLOCA";
7907   }
7908 }
7909
7910 // isLegalAddressingMode - Return true if the addressing mode represented
7911 // by AM is legal for this target, for a load/store of the specified type.
7912 bool X86TargetLowering::isLegalAddressingMode(const AddrMode &AM,
7913                                               const Type *Ty) const {
7914   // X86 supports extremely general addressing modes.
7915   CodeModel::Model M = getTargetMachine().getCodeModel();
7916
7917   // X86 allows a sign-extended 32-bit immediate field as a displacement.
7918   if (!X86::isOffsetSuitableForCodeModel(AM.BaseOffs, M, AM.BaseGV != NULL))
7919     return false;
7920
7921   if (AM.BaseGV) {
7922     unsigned GVFlags =
7923       Subtarget->ClassifyGlobalReference(AM.BaseGV, getTargetMachine());
7924
7925     // If a reference to this global requires an extra load, we can't fold it.
7926     if (isGlobalStubReference(GVFlags))
7927       return false;
7928
7929     // If BaseGV requires a register for the PIC base, we cannot also have a
7930     // BaseReg specified.
7931     if (AM.HasBaseReg && isGlobalRelativeToPICBase(GVFlags))
7932       return false;
7933
7934     // If lower 4G is not available, then we must use rip-relative addressing.
7935     if (Subtarget->is64Bit() && (AM.BaseOffs || AM.Scale > 1))
7936       return false;
7937   }
7938
7939   switch (AM.Scale) {
7940   case 0:
7941   case 1:
7942   case 2:
7943   case 4:
7944   case 8:
7945     // These scales always work.
7946     break;
7947   case 3:
7948   case 5:
7949   case 9:
7950     // These scales are formed with basereg+scalereg.  Only accept if there is
7951     // no basereg yet.
7952     if (AM.HasBaseReg)
7953       return false;
7954     break;
7955   default:  // Other stuff never works.
7956     return false;
7957   }
7958
7959   return true;
7960 }
7961
7962
7963 bool X86TargetLowering::isTruncateFree(const Type *Ty1, const Type *Ty2) const {
7964   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
7965     return false;
7966   unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
7967   unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
7968   if (NumBits1 <= NumBits2)
7969     return false;
7970   return true;
7971 }
7972
7973 bool X86TargetLowering::isTruncateFree(EVT VT1, EVT VT2) const {
7974   if (!VT1.isInteger() || !VT2.isInteger())
7975     return false;
7976   unsigned NumBits1 = VT1.getSizeInBits();
7977   unsigned NumBits2 = VT2.getSizeInBits();
7978   if (NumBits1 <= NumBits2)
7979     return false;
7980   return true;
7981 }
7982
7983 bool X86TargetLowering::isZExtFree(const Type *Ty1, const Type *Ty2) const {
7984   // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
7985   return Ty1->isIntegerTy(32) && Ty2->isIntegerTy(64) && Subtarget->is64Bit();
7986 }
7987
7988 bool X86TargetLowering::isZExtFree(EVT VT1, EVT VT2) const {
7989   // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
7990   return VT1 == MVT::i32 && VT2 == MVT::i64 && Subtarget->is64Bit();
7991 }
7992
7993 bool X86TargetLowering::isNarrowingProfitable(EVT VT1, EVT VT2) const {
7994   // i16 instructions are longer (0x66 prefix) and potentially slower.
7995   return !(VT1 == MVT::i32 && VT2 == MVT::i16);
7996 }
7997
7998 /// isShuffleMaskLegal - Targets can use this to indicate that they only
7999 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
8000 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
8001 /// are assumed to be legal.
8002 bool
8003 X86TargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M,
8004                                       EVT VT) const {
8005   // Very little shuffling can be done for 64-bit vectors right now.
8006   if (VT.getSizeInBits() == 64)
8007     return isPALIGNRMask(M, VT, Subtarget->hasSSSE3());
8008
8009   // FIXME: pshufb, blends, shifts.
8010   return (VT.getVectorNumElements() == 2 ||
8011           ShuffleVectorSDNode::isSplatMask(&M[0], VT) ||
8012           isMOVLMask(M, VT) ||
8013           isSHUFPMask(M, VT) ||
8014           isPSHUFDMask(M, VT) ||
8015           isPSHUFHWMask(M, VT) ||
8016           isPSHUFLWMask(M, VT) ||
8017           isPALIGNRMask(M, VT, Subtarget->hasSSSE3()) ||
8018           isUNPCKLMask(M, VT) ||
8019           isUNPCKHMask(M, VT) ||
8020           isUNPCKL_v_undef_Mask(M, VT) ||
8021           isUNPCKH_v_undef_Mask(M, VT));
8022 }
8023
8024 bool
8025 X86TargetLowering::isVectorClearMaskLegal(const SmallVectorImpl<int> &Mask,
8026                                           EVT VT) const {
8027   unsigned NumElts = VT.getVectorNumElements();
8028   // FIXME: This collection of masks seems suspect.
8029   if (NumElts == 2)
8030     return true;
8031   if (NumElts == 4 && VT.getSizeInBits() == 128) {
8032     return (isMOVLMask(Mask, VT)  ||
8033             isCommutedMOVLMask(Mask, VT, true) ||
8034             isSHUFPMask(Mask, VT) ||
8035             isCommutedSHUFPMask(Mask, VT));
8036   }
8037   return false;
8038 }
8039
8040 //===----------------------------------------------------------------------===//
8041 //                           X86 Scheduler Hooks
8042 //===----------------------------------------------------------------------===//
8043
8044 // private utility function
8045 MachineBasicBlock *
8046 X86TargetLowering::EmitAtomicBitwiseWithCustomInserter(MachineInstr *bInstr,
8047                                                        MachineBasicBlock *MBB,
8048                                                        unsigned regOpc,
8049                                                        unsigned immOpc,
8050                                                        unsigned LoadOpc,
8051                                                        unsigned CXchgOpc,
8052                                                        unsigned copyOpc,
8053                                                        unsigned notOpc,
8054                                                        unsigned EAXreg,
8055                                                        TargetRegisterClass *RC,
8056                                                        bool invSrc) const {
8057   // For the atomic bitwise operator, we generate
8058   //   thisMBB:
8059   //   newMBB:
8060   //     ld  t1 = [bitinstr.addr]
8061   //     op  t2 = t1, [bitinstr.val]
8062   //     mov EAX = t1
8063   //     lcs dest = [bitinstr.addr], t2  [EAX is implicit]
8064   //     bz  newMBB
8065   //     fallthrough -->nextMBB
8066   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
8067   const BasicBlock *LLVM_BB = MBB->getBasicBlock();
8068   MachineFunction::iterator MBBIter = MBB;
8069   ++MBBIter;
8070
8071   /// First build the CFG
8072   MachineFunction *F = MBB->getParent();
8073   MachineBasicBlock *thisMBB = MBB;
8074   MachineBasicBlock *newMBB = F->CreateMachineBasicBlock(LLVM_BB);
8075   MachineBasicBlock *nextMBB = F->CreateMachineBasicBlock(LLVM_BB);
8076   F->insert(MBBIter, newMBB);
8077   F->insert(MBBIter, nextMBB);
8078
8079   // Move all successors to thisMBB to nextMBB
8080   nextMBB->transferSuccessors(thisMBB);
8081
8082   // Update thisMBB to fall through to newMBB
8083   thisMBB->addSuccessor(newMBB);
8084
8085   // newMBB jumps to itself and fall through to nextMBB
8086   newMBB->addSuccessor(nextMBB);
8087   newMBB->addSuccessor(newMBB);
8088
8089   // Insert instructions into newMBB based on incoming instruction
8090   assert(bInstr->getNumOperands() < X86AddrNumOperands + 4 &&
8091          "unexpected number of operands");
8092   DebugLoc dl = bInstr->getDebugLoc();
8093   MachineOperand& destOper = bInstr->getOperand(0);
8094   MachineOperand* argOpers[2 + X86AddrNumOperands];
8095   int numArgs = bInstr->getNumOperands() - 1;
8096   for (int i=0; i < numArgs; ++i)
8097     argOpers[i] = &bInstr->getOperand(i+1);
8098
8099   // x86 address has 4 operands: base, index, scale, and displacement
8100   int lastAddrIndx = X86AddrNumOperands - 1; // [0,3]
8101   int valArgIndx = lastAddrIndx + 1;
8102
8103   unsigned t1 = F->getRegInfo().createVirtualRegister(RC);
8104   MachineInstrBuilder MIB = BuildMI(newMBB, dl, TII->get(LoadOpc), t1);
8105   for (int i=0; i <= lastAddrIndx; ++i)
8106     (*MIB).addOperand(*argOpers[i]);
8107
8108   unsigned tt = F->getRegInfo().createVirtualRegister(RC);
8109   if (invSrc) {
8110     MIB = BuildMI(newMBB, dl, TII->get(notOpc), tt).addReg(t1);
8111   }
8112   else
8113     tt = t1;
8114
8115   unsigned t2 = F->getRegInfo().createVirtualRegister(RC);
8116   assert((argOpers[valArgIndx]->isReg() ||
8117           argOpers[valArgIndx]->isImm()) &&
8118          "invalid operand");
8119   if (argOpers[valArgIndx]->isReg())
8120     MIB = BuildMI(newMBB, dl, TII->get(regOpc), t2);
8121   else
8122     MIB = BuildMI(newMBB, dl, TII->get(immOpc), t2);
8123   MIB.addReg(tt);
8124   (*MIB).addOperand(*argOpers[valArgIndx]);
8125
8126   MIB = BuildMI(newMBB, dl, TII->get(copyOpc), EAXreg);
8127   MIB.addReg(t1);
8128
8129   MIB = BuildMI(newMBB, dl, TII->get(CXchgOpc));
8130   for (int i=0; i <= lastAddrIndx; ++i)
8131     (*MIB).addOperand(*argOpers[i]);
8132   MIB.addReg(t2);
8133   assert(bInstr->hasOneMemOperand() && "Unexpected number of memoperand");
8134   (*MIB).setMemRefs(bInstr->memoperands_begin(),
8135                     bInstr->memoperands_end());
8136
8137   MIB = BuildMI(newMBB, dl, TII->get(copyOpc), destOper.getReg());
8138   MIB.addReg(EAXreg);
8139
8140   // insert branch
8141   BuildMI(newMBB, dl, TII->get(X86::JNE_4)).addMBB(newMBB);
8142
8143   F->DeleteMachineInstr(bInstr);   // The pseudo instruction is gone now.
8144   return nextMBB;
8145 }
8146
8147 // private utility function:  64 bit atomics on 32 bit host.
8148 MachineBasicBlock *
8149 X86TargetLowering::EmitAtomicBit6432WithCustomInserter(MachineInstr *bInstr,
8150                                                        MachineBasicBlock *MBB,
8151                                                        unsigned regOpcL,
8152                                                        unsigned regOpcH,
8153                                                        unsigned immOpcL,
8154                                                        unsigned immOpcH,
8155                                                        bool invSrc) const {
8156   // For the atomic bitwise operator, we generate
8157   //   thisMBB (instructions are in pairs, except cmpxchg8b)
8158   //     ld t1,t2 = [bitinstr.addr]
8159   //   newMBB:
8160   //     out1, out2 = phi (thisMBB, t1/t2) (newMBB, t3/t4)
8161   //     op  t5, t6 <- out1, out2, [bitinstr.val]
8162   //      (for SWAP, substitute:  mov t5, t6 <- [bitinstr.val])
8163   //     mov ECX, EBX <- t5, t6
8164   //     mov EAX, EDX <- t1, t2
8165   //     cmpxchg8b [bitinstr.addr]  [EAX, EDX, EBX, ECX implicit]
8166   //     mov t3, t4 <- EAX, EDX
8167   //     bz  newMBB
8168   //     result in out1, out2
8169   //     fallthrough -->nextMBB
8170
8171   const TargetRegisterClass *RC = X86::GR32RegisterClass;
8172   const unsigned LoadOpc = X86::MOV32rm;
8173   const unsigned copyOpc = X86::MOV32rr;
8174   const unsigned NotOpc = X86::NOT32r;
8175   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
8176   const BasicBlock *LLVM_BB = MBB->getBasicBlock();
8177   MachineFunction::iterator MBBIter = MBB;
8178   ++MBBIter;
8179
8180   /// First build the CFG
8181   MachineFunction *F = MBB->getParent();
8182   MachineBasicBlock *thisMBB = MBB;
8183   MachineBasicBlock *newMBB = F->CreateMachineBasicBlock(LLVM_BB);
8184   MachineBasicBlock *nextMBB = F->CreateMachineBasicBlock(LLVM_BB);
8185   F->insert(MBBIter, newMBB);
8186   F->insert(MBBIter, nextMBB);
8187
8188   // Move all successors to thisMBB to nextMBB
8189   nextMBB->transferSuccessors(thisMBB);
8190
8191   // Update thisMBB to fall through to newMBB
8192   thisMBB->addSuccessor(newMBB);
8193
8194   // newMBB jumps to itself and fall through to nextMBB
8195   newMBB->addSuccessor(nextMBB);
8196   newMBB->addSuccessor(newMBB);
8197
8198   DebugLoc dl = bInstr->getDebugLoc();
8199   // Insert instructions into newMBB based on incoming instruction
8200   // There are 8 "real" operands plus 9 implicit def/uses, ignored here.
8201   assert(bInstr->getNumOperands() < X86AddrNumOperands + 14 &&
8202          "unexpected number of operands");
8203   MachineOperand& dest1Oper = bInstr->getOperand(0);
8204   MachineOperand& dest2Oper = bInstr->getOperand(1);
8205   MachineOperand* argOpers[2 + X86AddrNumOperands];
8206   for (int i=0; i < 2 + X86AddrNumOperands; ++i)
8207     argOpers[i] = &bInstr->getOperand(i+2);
8208
8209   // x86 address has 5 operands: base, index, scale, displacement, and segment.
8210   int lastAddrIndx = X86AddrNumOperands - 1; // [0,3]
8211
8212   unsigned t1 = F->getRegInfo().createVirtualRegister(RC);
8213   MachineInstrBuilder MIB = BuildMI(thisMBB, dl, TII->get(LoadOpc), t1);
8214   for (int i=0; i <= lastAddrIndx; ++i)
8215     (*MIB).addOperand(*argOpers[i]);
8216   unsigned t2 = F->getRegInfo().createVirtualRegister(RC);
8217   MIB = BuildMI(thisMBB, dl, TII->get(LoadOpc), t2);
8218   // add 4 to displacement.
8219   for (int i=0; i <= lastAddrIndx-2; ++i)
8220     (*MIB).addOperand(*argOpers[i]);
8221   MachineOperand newOp3 = *(argOpers[3]);
8222   if (newOp3.isImm())
8223     newOp3.setImm(newOp3.getImm()+4);
8224   else
8225     newOp3.setOffset(newOp3.getOffset()+4);
8226   (*MIB).addOperand(newOp3);
8227   (*MIB).addOperand(*argOpers[lastAddrIndx]);
8228
8229   // t3/4 are defined later, at the bottom of the loop
8230   unsigned t3 = F->getRegInfo().createVirtualRegister(RC);
8231   unsigned t4 = F->getRegInfo().createVirtualRegister(RC);
8232   BuildMI(newMBB, dl, TII->get(X86::PHI), dest1Oper.getReg())
8233     .addReg(t1).addMBB(thisMBB).addReg(t3).addMBB(newMBB);
8234   BuildMI(newMBB, dl, TII->get(X86::PHI), dest2Oper.getReg())
8235     .addReg(t2).addMBB(thisMBB).addReg(t4).addMBB(newMBB);
8236
8237   // The subsequent operations should be using the destination registers of
8238   //the PHI instructions.
8239   if (invSrc) {
8240     t1 = F->getRegInfo().createVirtualRegister(RC);
8241     t2 = F->getRegInfo().createVirtualRegister(RC);
8242     MIB = BuildMI(newMBB, dl, TII->get(NotOpc), t1).addReg(dest1Oper.getReg());
8243     MIB = BuildMI(newMBB, dl, TII->get(NotOpc), t2).addReg(dest2Oper.getReg());
8244   } else {
8245     t1 = dest1Oper.getReg();
8246     t2 = dest2Oper.getReg();
8247   }
8248
8249   int valArgIndx = lastAddrIndx + 1;
8250   assert((argOpers[valArgIndx]->isReg() ||
8251           argOpers[valArgIndx]->isImm()) &&
8252          "invalid operand");
8253   unsigned t5 = F->getRegInfo().createVirtualRegister(RC);
8254   unsigned t6 = F->getRegInfo().createVirtualRegister(RC);
8255   if (argOpers[valArgIndx]->isReg())
8256     MIB = BuildMI(newMBB, dl, TII->get(regOpcL), t5);
8257   else
8258     MIB = BuildMI(newMBB, dl, TII->get(immOpcL), t5);
8259   if (regOpcL != X86::MOV32rr)
8260     MIB.addReg(t1);
8261   (*MIB).addOperand(*argOpers[valArgIndx]);
8262   assert(argOpers[valArgIndx + 1]->isReg() ==
8263          argOpers[valArgIndx]->isReg());
8264   assert(argOpers[valArgIndx + 1]->isImm() ==
8265          argOpers[valArgIndx]->isImm());
8266   if (argOpers[valArgIndx + 1]->isReg())
8267     MIB = BuildMI(newMBB, dl, TII->get(regOpcH), t6);
8268   else
8269     MIB = BuildMI(newMBB, dl, TII->get(immOpcH), t6);
8270   if (regOpcH != X86::MOV32rr)
8271     MIB.addReg(t2);
8272   (*MIB).addOperand(*argOpers[valArgIndx + 1]);
8273
8274   MIB = BuildMI(newMBB, dl, TII->get(copyOpc), X86::EAX);
8275   MIB.addReg(t1);
8276   MIB = BuildMI(newMBB, dl, TII->get(copyOpc), X86::EDX);
8277   MIB.addReg(t2);
8278
8279   MIB = BuildMI(newMBB, dl, TII->get(copyOpc), X86::EBX);
8280   MIB.addReg(t5);
8281   MIB = BuildMI(newMBB, dl, TII->get(copyOpc), X86::ECX);
8282   MIB.addReg(t6);
8283
8284   MIB = BuildMI(newMBB, dl, TII->get(X86::LCMPXCHG8B));
8285   for (int i=0; i <= lastAddrIndx; ++i)
8286     (*MIB).addOperand(*argOpers[i]);
8287
8288   assert(bInstr->hasOneMemOperand() && "Unexpected number of memoperand");
8289   (*MIB).setMemRefs(bInstr->memoperands_begin(),
8290                     bInstr->memoperands_end());
8291
8292   MIB = BuildMI(newMBB, dl, TII->get(copyOpc), t3);
8293   MIB.addReg(X86::EAX);
8294   MIB = BuildMI(newMBB, dl, TII->get(copyOpc), t4);
8295   MIB.addReg(X86::EDX);
8296
8297   // insert branch
8298   BuildMI(newMBB, dl, TII->get(X86::JNE_4)).addMBB(newMBB);
8299
8300   F->DeleteMachineInstr(bInstr);   // The pseudo instruction is gone now.
8301   return nextMBB;
8302 }
8303
8304 // private utility function
8305 MachineBasicBlock *
8306 X86TargetLowering::EmitAtomicMinMaxWithCustomInserter(MachineInstr *mInstr,
8307                                                       MachineBasicBlock *MBB,
8308                                                       unsigned cmovOpc) const {
8309   // For the atomic min/max operator, we generate
8310   //   thisMBB:
8311   //   newMBB:
8312   //     ld t1 = [min/max.addr]
8313   //     mov t2 = [min/max.val]
8314   //     cmp  t1, t2
8315   //     cmov[cond] t2 = t1
8316   //     mov EAX = t1
8317   //     lcs dest = [bitinstr.addr], t2  [EAX is implicit]
8318   //     bz   newMBB
8319   //     fallthrough -->nextMBB
8320   //
8321   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
8322   const BasicBlock *LLVM_BB = MBB->getBasicBlock();
8323   MachineFunction::iterator MBBIter = MBB;
8324   ++MBBIter;
8325
8326   /// First build the CFG
8327   MachineFunction *F = MBB->getParent();
8328   MachineBasicBlock *thisMBB = MBB;
8329   MachineBasicBlock *newMBB = F->CreateMachineBasicBlock(LLVM_BB);
8330   MachineBasicBlock *nextMBB = F->CreateMachineBasicBlock(LLVM_BB);
8331   F->insert(MBBIter, newMBB);
8332   F->insert(MBBIter, nextMBB);
8333
8334   // Move all successors of thisMBB to nextMBB
8335   nextMBB->transferSuccessors(thisMBB);
8336
8337   // Update thisMBB to fall through to newMBB
8338   thisMBB->addSuccessor(newMBB);
8339
8340   // newMBB jumps to newMBB and fall through to nextMBB
8341   newMBB->addSuccessor(nextMBB);
8342   newMBB->addSuccessor(newMBB);
8343
8344   DebugLoc dl = mInstr->getDebugLoc();
8345   // Insert instructions into newMBB based on incoming instruction
8346   assert(mInstr->getNumOperands() < X86AddrNumOperands + 4 &&
8347          "unexpected number of operands");
8348   MachineOperand& destOper = mInstr->getOperand(0);
8349   MachineOperand* argOpers[2 + X86AddrNumOperands];
8350   int numArgs = mInstr->getNumOperands() - 1;
8351   for (int i=0; i < numArgs; ++i)
8352     argOpers[i] = &mInstr->getOperand(i+1);
8353
8354   // x86 address has 4 operands: base, index, scale, and displacement
8355   int lastAddrIndx = X86AddrNumOperands - 1; // [0,3]
8356   int valArgIndx = lastAddrIndx + 1;
8357
8358   unsigned t1 = F->getRegInfo().createVirtualRegister(X86::GR32RegisterClass);
8359   MachineInstrBuilder MIB = BuildMI(newMBB, dl, TII->get(X86::MOV32rm), t1);
8360   for (int i=0; i <= lastAddrIndx; ++i)
8361     (*MIB).addOperand(*argOpers[i]);
8362
8363   // We only support register and immediate values
8364   assert((argOpers[valArgIndx]->isReg() ||
8365           argOpers[valArgIndx]->isImm()) &&
8366          "invalid operand");
8367
8368   unsigned t2 = F->getRegInfo().createVirtualRegister(X86::GR32RegisterClass);
8369   if (argOpers[valArgIndx]->isReg())
8370     MIB = BuildMI(newMBB, dl, TII->get(X86::MOV32rr), t2);
8371   else
8372     MIB = BuildMI(newMBB, dl, TII->get(X86::MOV32rr), t2);
8373   (*MIB).addOperand(*argOpers[valArgIndx]);
8374
8375   MIB = BuildMI(newMBB, dl, TII->get(X86::MOV32rr), X86::EAX);
8376   MIB.addReg(t1);
8377
8378   MIB = BuildMI(newMBB, dl, TII->get(X86::CMP32rr));
8379   MIB.addReg(t1);
8380   MIB.addReg(t2);
8381
8382   // Generate movc
8383   unsigned t3 = F->getRegInfo().createVirtualRegister(X86::GR32RegisterClass);
8384   MIB = BuildMI(newMBB, dl, TII->get(cmovOpc),t3);
8385   MIB.addReg(t2);
8386   MIB.addReg(t1);
8387
8388   // Cmp and exchange if none has modified the memory location
8389   MIB = BuildMI(newMBB, dl, TII->get(X86::LCMPXCHG32));
8390   for (int i=0; i <= lastAddrIndx; ++i)
8391     (*MIB).addOperand(*argOpers[i]);
8392   MIB.addReg(t3);
8393   assert(mInstr->hasOneMemOperand() && "Unexpected number of memoperand");
8394   (*MIB).setMemRefs(mInstr->memoperands_begin(),
8395                     mInstr->memoperands_end());
8396
8397   MIB = BuildMI(newMBB, dl, TII->get(X86::MOV32rr), destOper.getReg());
8398   MIB.addReg(X86::EAX);
8399
8400   // insert branch
8401   BuildMI(newMBB, dl, TII->get(X86::JNE_4)).addMBB(newMBB);
8402
8403   F->DeleteMachineInstr(mInstr);   // The pseudo instruction is gone now.
8404   return nextMBB;
8405 }
8406
8407 // FIXME: When we get size specific XMM0 registers, i.e. XMM0_V16I8
8408 // all of this code can be replaced with that in the .td file.
8409 MachineBasicBlock *
8410 X86TargetLowering::EmitPCMP(MachineInstr *MI, MachineBasicBlock *BB,
8411                             unsigned numArgs, bool memArg) const {
8412
8413   MachineFunction *F = BB->getParent();
8414   DebugLoc dl = MI->getDebugLoc();
8415   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
8416
8417   unsigned Opc;
8418   if (memArg)
8419     Opc = numArgs == 3 ? X86::PCMPISTRM128rm : X86::PCMPESTRM128rm;
8420   else
8421     Opc = numArgs == 3 ? X86::PCMPISTRM128rr : X86::PCMPESTRM128rr;
8422
8423   MachineInstrBuilder MIB = BuildMI(BB, dl, TII->get(Opc));
8424
8425   for (unsigned i = 0; i < numArgs; ++i) {
8426     MachineOperand &Op = MI->getOperand(i+1);
8427
8428     if (!(Op.isReg() && Op.isImplicit()))
8429       MIB.addOperand(Op);
8430   }
8431
8432   BuildMI(BB, dl, TII->get(X86::MOVAPSrr), MI->getOperand(0).getReg())
8433     .addReg(X86::XMM0);
8434
8435   F->DeleteMachineInstr(MI);
8436
8437   return BB;
8438 }
8439
8440 MachineBasicBlock *
8441 X86TargetLowering::EmitVAStartSaveXMMRegsWithCustomInserter(
8442                                                  MachineInstr *MI,
8443                                                  MachineBasicBlock *MBB) const {
8444   // Emit code to save XMM registers to the stack. The ABI says that the
8445   // number of registers to save is given in %al, so it's theoretically
8446   // possible to do an indirect jump trick to avoid saving all of them,
8447   // however this code takes a simpler approach and just executes all
8448   // of the stores if %al is non-zero. It's less code, and it's probably
8449   // easier on the hardware branch predictor, and stores aren't all that
8450   // expensive anyway.
8451
8452   // Create the new basic blocks. One block contains all the XMM stores,
8453   // and one block is the final destination regardless of whether any
8454   // stores were performed.
8455   const BasicBlock *LLVM_BB = MBB->getBasicBlock();
8456   MachineFunction *F = MBB->getParent();
8457   MachineFunction::iterator MBBIter = MBB;
8458   ++MBBIter;
8459   MachineBasicBlock *XMMSaveMBB = F->CreateMachineBasicBlock(LLVM_BB);
8460   MachineBasicBlock *EndMBB = F->CreateMachineBasicBlock(LLVM_BB);
8461   F->insert(MBBIter, XMMSaveMBB);
8462   F->insert(MBBIter, EndMBB);
8463
8464   // Set up the CFG.
8465   // Move any original successors of MBB to the end block.
8466   EndMBB->transferSuccessors(MBB);
8467   // The original block will now fall through to the XMM save block.
8468   MBB->addSuccessor(XMMSaveMBB);
8469   // The XMMSaveMBB will fall through to the end block.
8470   XMMSaveMBB->addSuccessor(EndMBB);
8471
8472   // Now add the instructions.
8473   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
8474   DebugLoc DL = MI->getDebugLoc();
8475
8476   unsigned CountReg = MI->getOperand(0).getReg();
8477   int64_t RegSaveFrameIndex = MI->getOperand(1).getImm();
8478   int64_t VarArgsFPOffset = MI->getOperand(2).getImm();
8479
8480   if (!Subtarget->isTargetWin64()) {
8481     // If %al is 0, branch around the XMM save block.
8482     BuildMI(MBB, DL, TII->get(X86::TEST8rr)).addReg(CountReg).addReg(CountReg);
8483     BuildMI(MBB, DL, TII->get(X86::JE_4)).addMBB(EndMBB);
8484     MBB->addSuccessor(EndMBB);
8485   }
8486
8487   // In the XMM save block, save all the XMM argument registers.
8488   for (int i = 3, e = MI->getNumOperands(); i != e; ++i) {
8489     int64_t Offset = (i - 3) * 16 + VarArgsFPOffset;
8490     MachineMemOperand *MMO =
8491       F->getMachineMemOperand(
8492         PseudoSourceValue::getFixedStack(RegSaveFrameIndex),
8493         MachineMemOperand::MOStore, Offset,
8494         /*Size=*/16, /*Align=*/16);
8495     BuildMI(XMMSaveMBB, DL, TII->get(X86::MOVAPSmr))
8496       .addFrameIndex(RegSaveFrameIndex)
8497       .addImm(/*Scale=*/1)
8498       .addReg(/*IndexReg=*/0)
8499       .addImm(/*Disp=*/Offset)
8500       .addReg(/*Segment=*/0)
8501       .addReg(MI->getOperand(i).getReg())
8502       .addMemOperand(MMO);
8503   }
8504
8505   F->DeleteMachineInstr(MI);   // The pseudo instruction is gone now.
8506
8507   return EndMBB;
8508 }
8509
8510 MachineBasicBlock *
8511 X86TargetLowering::EmitLoweredSelect(MachineInstr *MI,
8512                                      MachineBasicBlock *BB) const {
8513   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
8514   DebugLoc DL = MI->getDebugLoc();
8515
8516   // To "insert" a SELECT_CC instruction, we actually have to insert the
8517   // diamond control-flow pattern.  The incoming instruction knows the
8518   // destination vreg to set, the condition code register to branch on, the
8519   // true/false values to select between, and a branch opcode to use.
8520   const BasicBlock *LLVM_BB = BB->getBasicBlock();
8521   MachineFunction::iterator It = BB;
8522   ++It;
8523
8524   //  thisMBB:
8525   //  ...
8526   //   TrueVal = ...
8527   //   cmpTY ccX, r1, r2
8528   //   bCC copy1MBB
8529   //   fallthrough --> copy0MBB
8530   MachineBasicBlock *thisMBB = BB;
8531   MachineFunction *F = BB->getParent();
8532   MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
8533   MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
8534   unsigned Opc =
8535     X86::GetCondBranchFromCond((X86::CondCode)MI->getOperand(3).getImm());
8536   BuildMI(BB, DL, TII->get(Opc)).addMBB(sinkMBB);
8537   F->insert(It, copy0MBB);
8538   F->insert(It, sinkMBB);
8539   // Update machine-CFG edges by first adding all successors of the current
8540   // block to the new block which will contain the Phi node for the select.
8541   for (MachineBasicBlock::succ_iterator I = BB->succ_begin(),
8542          E = BB->succ_end(); I != E; ++I)
8543     sinkMBB->addSuccessor(*I);
8544   // Next, remove all successors of the current block, and add the true
8545   // and fallthrough blocks as its successors.
8546   while (!BB->succ_empty())
8547     BB->removeSuccessor(BB->succ_begin());
8548   // Add the true and fallthrough blocks as its successors.
8549   BB->addSuccessor(copy0MBB);
8550   BB->addSuccessor(sinkMBB);
8551
8552   //  copy0MBB:
8553   //   %FalseValue = ...
8554   //   # fallthrough to sinkMBB
8555   copy0MBB->addSuccessor(sinkMBB);
8556
8557   //  sinkMBB:
8558   //   %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
8559   //  ...
8560   BuildMI(sinkMBB, DL, TII->get(X86::PHI), MI->getOperand(0).getReg())
8561     .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB)
8562     .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
8563
8564   F->DeleteMachineInstr(MI);   // The pseudo instruction is gone now.
8565   return sinkMBB;
8566 }
8567
8568 MachineBasicBlock *
8569 X86TargetLowering::EmitLoweredMingwAlloca(MachineInstr *MI,
8570                                           MachineBasicBlock *BB) const {
8571   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
8572   DebugLoc DL = MI->getDebugLoc();
8573   MachineFunction *F = BB->getParent();
8574
8575   // The lowering is pretty easy: we're just emitting the call to _alloca.  The
8576   // non-trivial part is impdef of ESP.
8577   // FIXME: The code should be tweaked as soon as we'll try to do codegen for
8578   // mingw-w64.
8579
8580   BuildMI(BB, DL, TII->get(X86::CALLpcrel32))
8581     .addExternalSymbol("_alloca")
8582     .addReg(X86::EAX, RegState::Implicit)
8583     .addReg(X86::ESP, RegState::Implicit)
8584     .addReg(X86::EAX, RegState::Define | RegState::Implicit)
8585     .addReg(X86::ESP, RegState::Define | RegState::Implicit);
8586
8587   F->DeleteMachineInstr(MI);   // The pseudo instruction is gone now.
8588   return BB;
8589 }
8590
8591 MachineBasicBlock *
8592 X86TargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
8593                                                MachineBasicBlock *BB) const {
8594   switch (MI->getOpcode()) {
8595   default: assert(false && "Unexpected instr type to insert");
8596   case X86::MINGW_ALLOCA:
8597     return EmitLoweredMingwAlloca(MI, BB);
8598   case X86::CMOV_GR8:
8599   case X86::CMOV_V1I64:
8600   case X86::CMOV_FR32:
8601   case X86::CMOV_FR64:
8602   case X86::CMOV_V4F32:
8603   case X86::CMOV_V2F64:
8604   case X86::CMOV_V2I64:
8605   case X86::CMOV_GR16:
8606   case X86::CMOV_GR32:
8607   case X86::CMOV_RFP32:
8608   case X86::CMOV_RFP64:
8609   case X86::CMOV_RFP80:
8610     return EmitLoweredSelect(MI, BB);
8611
8612   case X86::FP32_TO_INT16_IN_MEM:
8613   case X86::FP32_TO_INT32_IN_MEM:
8614   case X86::FP32_TO_INT64_IN_MEM:
8615   case X86::FP64_TO_INT16_IN_MEM:
8616   case X86::FP64_TO_INT32_IN_MEM:
8617   case X86::FP64_TO_INT64_IN_MEM:
8618   case X86::FP80_TO_INT16_IN_MEM:
8619   case X86::FP80_TO_INT32_IN_MEM:
8620   case X86::FP80_TO_INT64_IN_MEM: {
8621     const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
8622     DebugLoc DL = MI->getDebugLoc();
8623
8624     // Change the floating point control register to use "round towards zero"
8625     // mode when truncating to an integer value.
8626     MachineFunction *F = BB->getParent();
8627     int CWFrameIdx = F->getFrameInfo()->CreateStackObject(2, 2, false);
8628     addFrameReference(BuildMI(BB, DL, TII->get(X86::FNSTCW16m)), CWFrameIdx);
8629
8630     // Load the old value of the high byte of the control word...
8631     unsigned OldCW =
8632       F->getRegInfo().createVirtualRegister(X86::GR16RegisterClass);
8633     addFrameReference(BuildMI(BB, DL, TII->get(X86::MOV16rm), OldCW),
8634                       CWFrameIdx);
8635
8636     // Set the high part to be round to zero...
8637     addFrameReference(BuildMI(BB, DL, TII->get(X86::MOV16mi)), CWFrameIdx)
8638       .addImm(0xC7F);
8639
8640     // Reload the modified control word now...
8641     addFrameReference(BuildMI(BB, DL, TII->get(X86::FLDCW16m)), CWFrameIdx);
8642
8643     // Restore the memory image of control word to original value
8644     addFrameReference(BuildMI(BB, DL, TII->get(X86::MOV16mr)), CWFrameIdx)
8645       .addReg(OldCW);
8646
8647     // Get the X86 opcode to use.
8648     unsigned Opc;
8649     switch (MI->getOpcode()) {
8650     default: llvm_unreachable("illegal opcode!");
8651     case X86::FP32_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m32; break;
8652     case X86::FP32_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m32; break;
8653     case X86::FP32_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m32; break;
8654     case X86::FP64_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m64; break;
8655     case X86::FP64_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m64; break;
8656     case X86::FP64_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m64; break;
8657     case X86::FP80_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m80; break;
8658     case X86::FP80_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m80; break;
8659     case X86::FP80_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m80; break;
8660     }
8661
8662     X86AddressMode AM;
8663     MachineOperand &Op = MI->getOperand(0);
8664     if (Op.isReg()) {
8665       AM.BaseType = X86AddressMode::RegBase;
8666       AM.Base.Reg = Op.getReg();
8667     } else {
8668       AM.BaseType = X86AddressMode::FrameIndexBase;
8669       AM.Base.FrameIndex = Op.getIndex();
8670     }
8671     Op = MI->getOperand(1);
8672     if (Op.isImm())
8673       AM.Scale = Op.getImm();
8674     Op = MI->getOperand(2);
8675     if (Op.isImm())
8676       AM.IndexReg = Op.getImm();
8677     Op = MI->getOperand(3);
8678     if (Op.isGlobal()) {
8679       AM.GV = Op.getGlobal();
8680     } else {
8681       AM.Disp = Op.getImm();
8682     }
8683     addFullAddress(BuildMI(BB, DL, TII->get(Opc)), AM)
8684                       .addReg(MI->getOperand(X86AddrNumOperands).getReg());
8685
8686     // Reload the original control word now.
8687     addFrameReference(BuildMI(BB, DL, TII->get(X86::FLDCW16m)), CWFrameIdx);
8688
8689     F->DeleteMachineInstr(MI);   // The pseudo instruction is gone now.
8690     return BB;
8691   }
8692     // String/text processing lowering.
8693   case X86::PCMPISTRM128REG:
8694     return EmitPCMP(MI, BB, 3, false /* in-mem */);
8695   case X86::PCMPISTRM128MEM:
8696     return EmitPCMP(MI, BB, 3, true /* in-mem */);
8697   case X86::PCMPESTRM128REG:
8698     return EmitPCMP(MI, BB, 5, false /* in mem */);
8699   case X86::PCMPESTRM128MEM:
8700     return EmitPCMP(MI, BB, 5, true /* in mem */);
8701
8702     // Atomic Lowering.
8703   case X86::ATOMAND32:
8704     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND32rr,
8705                                                X86::AND32ri, X86::MOV32rm,
8706                                                X86::LCMPXCHG32, X86::MOV32rr,
8707                                                X86::NOT32r, X86::EAX,
8708                                                X86::GR32RegisterClass);
8709   case X86::ATOMOR32:
8710     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR32rr,
8711                                                X86::OR32ri, X86::MOV32rm,
8712                                                X86::LCMPXCHG32, X86::MOV32rr,
8713                                                X86::NOT32r, X86::EAX,
8714                                                X86::GR32RegisterClass);
8715   case X86::ATOMXOR32:
8716     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR32rr,
8717                                                X86::XOR32ri, X86::MOV32rm,
8718                                                X86::LCMPXCHG32, X86::MOV32rr,
8719                                                X86::NOT32r, X86::EAX,
8720                                                X86::GR32RegisterClass);
8721   case X86::ATOMNAND32:
8722     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND32rr,
8723                                                X86::AND32ri, X86::MOV32rm,
8724                                                X86::LCMPXCHG32, X86::MOV32rr,
8725                                                X86::NOT32r, X86::EAX,
8726                                                X86::GR32RegisterClass, true);
8727   case X86::ATOMMIN32:
8728     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVL32rr);
8729   case X86::ATOMMAX32:
8730     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVG32rr);
8731   case X86::ATOMUMIN32:
8732     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVB32rr);
8733   case X86::ATOMUMAX32:
8734     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVA32rr);
8735
8736   case X86::ATOMAND16:
8737     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND16rr,
8738                                                X86::AND16ri, X86::MOV16rm,
8739                                                X86::LCMPXCHG16, X86::MOV16rr,
8740                                                X86::NOT16r, X86::AX,
8741                                                X86::GR16RegisterClass);
8742   case X86::ATOMOR16:
8743     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR16rr,
8744                                                X86::OR16ri, X86::MOV16rm,
8745                                                X86::LCMPXCHG16, X86::MOV16rr,
8746                                                X86::NOT16r, X86::AX,
8747                                                X86::GR16RegisterClass);
8748   case X86::ATOMXOR16:
8749     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR16rr,
8750                                                X86::XOR16ri, X86::MOV16rm,
8751                                                X86::LCMPXCHG16, X86::MOV16rr,
8752                                                X86::NOT16r, X86::AX,
8753                                                X86::GR16RegisterClass);
8754   case X86::ATOMNAND16:
8755     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND16rr,
8756                                                X86::AND16ri, X86::MOV16rm,
8757                                                X86::LCMPXCHG16, X86::MOV16rr,
8758                                                X86::NOT16r, X86::AX,
8759                                                X86::GR16RegisterClass, true);
8760   case X86::ATOMMIN16:
8761     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVL16rr);
8762   case X86::ATOMMAX16:
8763     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVG16rr);
8764   case X86::ATOMUMIN16:
8765     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVB16rr);
8766   case X86::ATOMUMAX16:
8767     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVA16rr);
8768
8769   case X86::ATOMAND8:
8770     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND8rr,
8771                                                X86::AND8ri, X86::MOV8rm,
8772                                                X86::LCMPXCHG8, X86::MOV8rr,
8773                                                X86::NOT8r, X86::AL,
8774                                                X86::GR8RegisterClass);
8775   case X86::ATOMOR8:
8776     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR8rr,
8777                                                X86::OR8ri, X86::MOV8rm,
8778                                                X86::LCMPXCHG8, X86::MOV8rr,
8779                                                X86::NOT8r, X86::AL,
8780                                                X86::GR8RegisterClass);
8781   case X86::ATOMXOR8:
8782     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR8rr,
8783                                                X86::XOR8ri, X86::MOV8rm,
8784                                                X86::LCMPXCHG8, X86::MOV8rr,
8785                                                X86::NOT8r, X86::AL,
8786                                                X86::GR8RegisterClass);
8787   case X86::ATOMNAND8:
8788     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND8rr,
8789                                                X86::AND8ri, X86::MOV8rm,
8790                                                X86::LCMPXCHG8, X86::MOV8rr,
8791                                                X86::NOT8r, X86::AL,
8792                                                X86::GR8RegisterClass, true);
8793   // FIXME: There are no CMOV8 instructions; MIN/MAX need some other way.
8794   // This group is for 64-bit host.
8795   case X86::ATOMAND64:
8796     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND64rr,
8797                                                X86::AND64ri32, X86::MOV64rm,
8798                                                X86::LCMPXCHG64, X86::MOV64rr,
8799                                                X86::NOT64r, X86::RAX,
8800                                                X86::GR64RegisterClass);
8801   case X86::ATOMOR64:
8802     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR64rr,
8803                                                X86::OR64ri32, X86::MOV64rm,
8804                                                X86::LCMPXCHG64, X86::MOV64rr,
8805                                                X86::NOT64r, X86::RAX,
8806                                                X86::GR64RegisterClass);
8807   case X86::ATOMXOR64:
8808     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR64rr,
8809                                                X86::XOR64ri32, X86::MOV64rm,
8810                                                X86::LCMPXCHG64, X86::MOV64rr,
8811                                                X86::NOT64r, X86::RAX,
8812                                                X86::GR64RegisterClass);
8813   case X86::ATOMNAND64:
8814     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND64rr,
8815                                                X86::AND64ri32, X86::MOV64rm,
8816                                                X86::LCMPXCHG64, X86::MOV64rr,
8817                                                X86::NOT64r, X86::RAX,
8818                                                X86::GR64RegisterClass, true);
8819   case X86::ATOMMIN64:
8820     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVL64rr);
8821   case X86::ATOMMAX64:
8822     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVG64rr);
8823   case X86::ATOMUMIN64:
8824     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVB64rr);
8825   case X86::ATOMUMAX64:
8826     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVA64rr);
8827
8828   // This group does 64-bit operations on a 32-bit host.
8829   case X86::ATOMAND6432:
8830     return EmitAtomicBit6432WithCustomInserter(MI, BB,
8831                                                X86::AND32rr, X86::AND32rr,
8832                                                X86::AND32ri, X86::AND32ri,
8833                                                false);
8834   case X86::ATOMOR6432:
8835     return EmitAtomicBit6432WithCustomInserter(MI, BB,
8836                                                X86::OR32rr, X86::OR32rr,
8837                                                X86::OR32ri, X86::OR32ri,
8838                                                false);
8839   case X86::ATOMXOR6432:
8840     return EmitAtomicBit6432WithCustomInserter(MI, BB,
8841                                                X86::XOR32rr, X86::XOR32rr,
8842                                                X86::XOR32ri, X86::XOR32ri,
8843                                                false);
8844   case X86::ATOMNAND6432:
8845     return EmitAtomicBit6432WithCustomInserter(MI, BB,
8846                                                X86::AND32rr, X86::AND32rr,
8847                                                X86::AND32ri, X86::AND32ri,
8848                                                true);
8849   case X86::ATOMADD6432:
8850     return EmitAtomicBit6432WithCustomInserter(MI, BB,
8851                                                X86::ADD32rr, X86::ADC32rr,
8852                                                X86::ADD32ri, X86::ADC32ri,
8853                                                false);
8854   case X86::ATOMSUB6432:
8855     return EmitAtomicBit6432WithCustomInserter(MI, BB,
8856                                                X86::SUB32rr, X86::SBB32rr,
8857                                                X86::SUB32ri, X86::SBB32ri,
8858                                                false);
8859   case X86::ATOMSWAP6432:
8860     return EmitAtomicBit6432WithCustomInserter(MI, BB,
8861                                                X86::MOV32rr, X86::MOV32rr,
8862                                                X86::MOV32ri, X86::MOV32ri,
8863                                                false);
8864   case X86::VASTART_SAVE_XMM_REGS:
8865     return EmitVAStartSaveXMMRegsWithCustomInserter(MI, BB);
8866   }
8867 }
8868
8869 //===----------------------------------------------------------------------===//
8870 //                           X86 Optimization Hooks
8871 //===----------------------------------------------------------------------===//
8872
8873 void X86TargetLowering::computeMaskedBitsForTargetNode(const SDValue Op,
8874                                                        const APInt &Mask,
8875                                                        APInt &KnownZero,
8876                                                        APInt &KnownOne,
8877                                                        const SelectionDAG &DAG,
8878                                                        unsigned Depth) const {
8879   unsigned Opc = Op.getOpcode();
8880   assert((Opc >= ISD::BUILTIN_OP_END ||
8881           Opc == ISD::INTRINSIC_WO_CHAIN ||
8882           Opc == ISD::INTRINSIC_W_CHAIN ||
8883           Opc == ISD::INTRINSIC_VOID) &&
8884          "Should use MaskedValueIsZero if you don't know whether Op"
8885          " is a target node!");
8886
8887   KnownZero = KnownOne = APInt(Mask.getBitWidth(), 0);   // Don't know anything.
8888   switch (Opc) {
8889   default: break;
8890   case X86ISD::ADD:
8891   case X86ISD::SUB:
8892   case X86ISD::SMUL:
8893   case X86ISD::UMUL:
8894   case X86ISD::INC:
8895   case X86ISD::DEC:
8896   case X86ISD::OR:
8897   case X86ISD::XOR:
8898   case X86ISD::AND:
8899     // These nodes' second result is a boolean.
8900     if (Op.getResNo() == 0)
8901       break;
8902     // Fallthrough
8903   case X86ISD::SETCC:
8904     KnownZero |= APInt::getHighBitsSet(Mask.getBitWidth(),
8905                                        Mask.getBitWidth() - 1);
8906     break;
8907   }
8908 }
8909
8910 /// isGAPlusOffset - Returns true (and the GlobalValue and the offset) if the
8911 /// node is a GlobalAddress + offset.
8912 bool X86TargetLowering::isGAPlusOffset(SDNode *N,
8913                                        const GlobalValue* &GA,
8914                                        int64_t &Offset) const {
8915   if (N->getOpcode() == X86ISD::Wrapper) {
8916     if (isa<GlobalAddressSDNode>(N->getOperand(0))) {
8917       GA = cast<GlobalAddressSDNode>(N->getOperand(0))->getGlobal();
8918       Offset = cast<GlobalAddressSDNode>(N->getOperand(0))->getOffset();
8919       return true;
8920     }
8921   }
8922   return TargetLowering::isGAPlusOffset(N, GA, Offset);
8923 }
8924
8925 /// PerformShuffleCombine - Combine a vector_shuffle that is equal to
8926 /// build_vector load1, load2, load3, load4, <0, 1, 2, 3> into a 128-bit load
8927 /// if the load addresses are consecutive, non-overlapping, and in the right
8928 /// order.
8929 static SDValue PerformShuffleCombine(SDNode *N, SelectionDAG &DAG,
8930                                      const TargetLowering &TLI) {
8931   DebugLoc dl = N->getDebugLoc();
8932   EVT VT = N->getValueType(0);
8933   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
8934
8935   if (VT.getSizeInBits() != 128)
8936     return SDValue();
8937
8938   SmallVector<SDValue, 16> Elts;
8939   for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i)
8940     Elts.push_back(DAG.getShuffleScalarElt(SVN, i));
8941   
8942   return EltsFromConsecutiveLoads(VT, Elts, dl, DAG);
8943 }
8944
8945 /// PerformShuffleCombine - Detect vector gather/scatter index generation
8946 /// and convert it from being a bunch of shuffles and extracts to a simple
8947 /// store and scalar loads to extract the elements.
8948 static SDValue PerformEXTRACT_VECTOR_ELTCombine(SDNode *N, SelectionDAG &DAG,
8949                                                 const TargetLowering &TLI) {
8950   SDValue InputVector = N->getOperand(0);
8951
8952   // Only operate on vectors of 4 elements, where the alternative shuffling
8953   // gets to be more expensive.
8954   if (InputVector.getValueType() != MVT::v4i32)
8955     return SDValue();
8956
8957   // Check whether every use of InputVector is an EXTRACT_VECTOR_ELT with a
8958   // single use which is a sign-extend or zero-extend, and all elements are
8959   // used.
8960   SmallVector<SDNode *, 4> Uses;
8961   unsigned ExtractedElements = 0;
8962   for (SDNode::use_iterator UI = InputVector.getNode()->use_begin(),
8963        UE = InputVector.getNode()->use_end(); UI != UE; ++UI) {
8964     if (UI.getUse().getResNo() != InputVector.getResNo())
8965       return SDValue();
8966
8967     SDNode *Extract = *UI;
8968     if (Extract->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
8969       return SDValue();
8970
8971     if (Extract->getValueType(0) != MVT::i32)
8972       return SDValue();
8973     if (!Extract->hasOneUse())
8974       return SDValue();
8975     if (Extract->use_begin()->getOpcode() != ISD::SIGN_EXTEND &&
8976         Extract->use_begin()->getOpcode() != ISD::ZERO_EXTEND)
8977       return SDValue();
8978     if (!isa<ConstantSDNode>(Extract->getOperand(1)))
8979       return SDValue();
8980
8981     // Record which element was extracted.
8982     ExtractedElements |=
8983       1 << cast<ConstantSDNode>(Extract->getOperand(1))->getZExtValue();
8984
8985     Uses.push_back(Extract);
8986   }
8987
8988   // If not all the elements were used, this may not be worthwhile.
8989   if (ExtractedElements != 15)
8990     return SDValue();
8991
8992   // Ok, we've now decided to do the transformation.
8993   DebugLoc dl = InputVector.getDebugLoc();
8994
8995   // Store the value to a temporary stack slot.
8996   SDValue StackPtr = DAG.CreateStackTemporary(InputVector.getValueType());
8997   SDValue Ch = DAG.getStore(DAG.getEntryNode(), dl, InputVector, StackPtr, NULL, 0,
8998                             false, false, 0);
8999
9000   // Replace each use (extract) with a load of the appropriate element.
9001   for (SmallVectorImpl<SDNode *>::iterator UI = Uses.begin(),
9002        UE = Uses.end(); UI != UE; ++UI) {
9003     SDNode *Extract = *UI;
9004
9005     // Compute the element's address.
9006     SDValue Idx = Extract->getOperand(1);
9007     unsigned EltSize =
9008         InputVector.getValueType().getVectorElementType().getSizeInBits()/8;
9009     uint64_t Offset = EltSize * cast<ConstantSDNode>(Idx)->getZExtValue();
9010     SDValue OffsetVal = DAG.getConstant(Offset, TLI.getPointerTy());
9011
9012     SDValue ScalarAddr = DAG.getNode(ISD::ADD, dl, Idx.getValueType(), OffsetVal, StackPtr);
9013
9014     // Load the scalar.
9015     SDValue LoadScalar = DAG.getLoad(Extract->getValueType(0), dl, Ch, ScalarAddr,
9016                           NULL, 0, false, false, 0);
9017
9018     // Replace the exact with the load.
9019     DAG.ReplaceAllUsesOfValueWith(SDValue(Extract, 0), LoadScalar);
9020   }
9021
9022   // The replacement was made in place; don't return anything.
9023   return SDValue();
9024 }
9025
9026 /// PerformSELECTCombine - Do target-specific dag combines on SELECT nodes.
9027 static SDValue PerformSELECTCombine(SDNode *N, SelectionDAG &DAG,
9028                                     const X86Subtarget *Subtarget) {
9029   DebugLoc DL = N->getDebugLoc();
9030   SDValue Cond = N->getOperand(0);
9031   // Get the LHS/RHS of the select.
9032   SDValue LHS = N->getOperand(1);
9033   SDValue RHS = N->getOperand(2);
9034
9035   // If we have SSE[12] support, try to form min/max nodes. SSE min/max
9036   // instructions match the semantics of the common C idiom x<y?x:y but not
9037   // x<=y?x:y, because of how they handle negative zero (which can be
9038   // ignored in unsafe-math mode).
9039   if (Subtarget->hasSSE2() &&
9040       (LHS.getValueType() == MVT::f32 || LHS.getValueType() == MVT::f64) &&
9041       Cond.getOpcode() == ISD::SETCC) {
9042     ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
9043
9044     unsigned Opcode = 0;
9045     // Check for x CC y ? x : y.
9046     if (DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
9047         DAG.isEqualTo(RHS, Cond.getOperand(1))) {
9048       switch (CC) {
9049       default: break;
9050       case ISD::SETULT:
9051         // Converting this to a min would handle NaNs incorrectly, and swapping
9052         // the operands would cause it to handle comparisons between positive
9053         // and negative zero incorrectly.
9054         if (!FiniteOnlyFPMath() &&
9055             (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))) {
9056           if (!UnsafeFPMath &&
9057               !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
9058             break;
9059           std::swap(LHS, RHS);
9060         }
9061         Opcode = X86ISD::FMIN;
9062         break;
9063       case ISD::SETOLE:
9064         // Converting this to a min would handle comparisons between positive
9065         // and negative zero incorrectly.
9066         if (!UnsafeFPMath &&
9067             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
9068           break;
9069         Opcode = X86ISD::FMIN;
9070         break;
9071       case ISD::SETULE:
9072         // Converting this to a min would handle both negative zeros and NaNs
9073         // incorrectly, but we can swap the operands to fix both.
9074         std::swap(LHS, RHS);
9075       case ISD::SETOLT:
9076       case ISD::SETLT:
9077       case ISD::SETLE:
9078         Opcode = X86ISD::FMIN;
9079         break;
9080
9081       case ISD::SETOGE:
9082         // Converting this to a max would handle comparisons between positive
9083         // and negative zero incorrectly.
9084         if (!UnsafeFPMath &&
9085             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(LHS))
9086           break;
9087         Opcode = X86ISD::FMAX;
9088         break;
9089       case ISD::SETUGT:
9090         // Converting this to a max would handle NaNs incorrectly, and swapping
9091         // the operands would cause it to handle comparisons between positive
9092         // and negative zero incorrectly.
9093         if (!FiniteOnlyFPMath() &&
9094             (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))) {
9095           if (!UnsafeFPMath &&
9096               !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
9097             break;
9098           std::swap(LHS, RHS);
9099         }
9100         Opcode = X86ISD::FMAX;
9101         break;
9102       case ISD::SETUGE:
9103         // Converting this to a max would handle both negative zeros and NaNs
9104         // incorrectly, but we can swap the operands to fix both.
9105         std::swap(LHS, RHS);
9106       case ISD::SETOGT:
9107       case ISD::SETGT:
9108       case ISD::SETGE:
9109         Opcode = X86ISD::FMAX;
9110         break;
9111       }
9112     // Check for x CC y ? y : x -- a min/max with reversed arms.
9113     } else if (DAG.isEqualTo(LHS, Cond.getOperand(1)) &&
9114                DAG.isEqualTo(RHS, Cond.getOperand(0))) {
9115       switch (CC) {
9116       default: break;
9117       case ISD::SETOGE:
9118         // Converting this to a min would handle comparisons between positive
9119         // and negative zero incorrectly, and swapping the operands would
9120         // cause it to handle NaNs incorrectly.
9121         if (!UnsafeFPMath &&
9122             !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS))) {
9123           if (!FiniteOnlyFPMath() &&
9124               (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)))
9125             break;
9126           std::swap(LHS, RHS);
9127         }
9128         Opcode = X86ISD::FMIN;
9129         break;
9130       case ISD::SETUGT:
9131         // Converting this to a min would handle NaNs incorrectly.
9132         if (!UnsafeFPMath &&
9133             (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)))
9134           break;
9135         Opcode = X86ISD::FMIN;
9136         break;
9137       case ISD::SETUGE:
9138         // Converting this to a min would handle both negative zeros and NaNs
9139         // incorrectly, but we can swap the operands to fix both.
9140         std::swap(LHS, RHS);
9141       case ISD::SETOGT:
9142       case ISD::SETGT:
9143       case ISD::SETGE:
9144         Opcode = X86ISD::FMIN;
9145         break;
9146
9147       case ISD::SETULT:
9148         // Converting this to a max would handle NaNs incorrectly.
9149         if (!FiniteOnlyFPMath() &&
9150             (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)))
9151           break;
9152         Opcode = X86ISD::FMAX;
9153         break;
9154       case ISD::SETOLE:
9155         // Converting this to a max would handle comparisons between positive
9156         // and negative zero incorrectly, and swapping the operands would
9157         // cause it to handle NaNs incorrectly.
9158         if (!UnsafeFPMath &&
9159             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS)) {
9160           if (!FiniteOnlyFPMath() &&
9161               (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)))
9162             break;
9163           std::swap(LHS, RHS);
9164         }
9165         Opcode = X86ISD::FMAX;
9166         break;
9167       case ISD::SETULE:
9168         // Converting this to a max would handle both negative zeros and NaNs
9169         // incorrectly, but we can swap the operands to fix both.
9170         std::swap(LHS, RHS);
9171       case ISD::SETOLT:
9172       case ISD::SETLT:
9173       case ISD::SETLE:
9174         Opcode = X86ISD::FMAX;
9175         break;
9176       }
9177     }
9178
9179     if (Opcode)
9180       return DAG.getNode(Opcode, DL, N->getValueType(0), LHS, RHS);
9181   }
9182
9183   // If this is a select between two integer constants, try to do some
9184   // optimizations.
9185   if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(LHS)) {
9186     if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(RHS))
9187       // Don't do this for crazy integer types.
9188       if (DAG.getTargetLoweringInfo().isTypeLegal(LHS.getValueType())) {
9189         // If this is efficiently invertible, canonicalize the LHSC/RHSC values
9190         // so that TrueC (the true value) is larger than FalseC.
9191         bool NeedsCondInvert = false;
9192
9193         if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue()) &&
9194             // Efficiently invertible.
9195             (Cond.getOpcode() == ISD::SETCC ||  // setcc -> invertible.
9196              (Cond.getOpcode() == ISD::XOR &&   // xor(X, C) -> invertible.
9197               isa<ConstantSDNode>(Cond.getOperand(1))))) {
9198           NeedsCondInvert = true;
9199           std::swap(TrueC, FalseC);
9200         }
9201
9202         // Optimize C ? 8 : 0 -> zext(C) << 3.  Likewise for any pow2/0.
9203         if (FalseC->getAPIntValue() == 0 &&
9204             TrueC->getAPIntValue().isPowerOf2()) {
9205           if (NeedsCondInvert) // Invert the condition if needed.
9206             Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
9207                                DAG.getConstant(1, Cond.getValueType()));
9208
9209           // Zero extend the condition if needed.
9210           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, LHS.getValueType(), Cond);
9211
9212           unsigned ShAmt = TrueC->getAPIntValue().logBase2();
9213           return DAG.getNode(ISD::SHL, DL, LHS.getValueType(), Cond,
9214                              DAG.getConstant(ShAmt, MVT::i8));
9215         }
9216
9217         // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.
9218         if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
9219           if (NeedsCondInvert) // Invert the condition if needed.
9220             Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
9221                                DAG.getConstant(1, Cond.getValueType()));
9222
9223           // Zero extend the condition if needed.
9224           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
9225                              FalseC->getValueType(0), Cond);
9226           return DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
9227                              SDValue(FalseC, 0));
9228         }
9229
9230         // Optimize cases that will turn into an LEA instruction.  This requires
9231         // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
9232         if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
9233           uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
9234           if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
9235
9236           bool isFastMultiplier = false;
9237           if (Diff < 10) {
9238             switch ((unsigned char)Diff) {
9239               default: break;
9240               case 1:  // result = add base, cond
9241               case 2:  // result = lea base(    , cond*2)
9242               case 3:  // result = lea base(cond, cond*2)
9243               case 4:  // result = lea base(    , cond*4)
9244               case 5:  // result = lea base(cond, cond*4)
9245               case 8:  // result = lea base(    , cond*8)
9246               case 9:  // result = lea base(cond, cond*8)
9247                 isFastMultiplier = true;
9248                 break;
9249             }
9250           }
9251
9252           if (isFastMultiplier) {
9253             APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
9254             if (NeedsCondInvert) // Invert the condition if needed.
9255               Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
9256                                  DAG.getConstant(1, Cond.getValueType()));
9257
9258             // Zero extend the condition if needed.
9259             Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
9260                                Cond);
9261             // Scale the condition by the difference.
9262             if (Diff != 1)
9263               Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
9264                                  DAG.getConstant(Diff, Cond.getValueType()));
9265
9266             // Add the base if non-zero.
9267             if (FalseC->getAPIntValue() != 0)
9268               Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
9269                                  SDValue(FalseC, 0));
9270             return Cond;
9271           }
9272         }
9273       }
9274   }
9275
9276   return SDValue();
9277 }
9278
9279 /// Optimize X86ISD::CMOV [LHS, RHS, CONDCODE (e.g. X86::COND_NE), CONDVAL]
9280 static SDValue PerformCMOVCombine(SDNode *N, SelectionDAG &DAG,
9281                                   TargetLowering::DAGCombinerInfo &DCI) {
9282   DebugLoc DL = N->getDebugLoc();
9283
9284   // If the flag operand isn't dead, don't touch this CMOV.
9285   if (N->getNumValues() == 2 && !SDValue(N, 1).use_empty())
9286     return SDValue();
9287
9288   // If this is a select between two integer constants, try to do some
9289   // optimizations.  Note that the operands are ordered the opposite of SELECT
9290   // operands.
9291   if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(N->getOperand(1))) {
9292     if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(N->getOperand(0))) {
9293       // Canonicalize the TrueC/FalseC values so that TrueC (the true value) is
9294       // larger than FalseC (the false value).
9295       X86::CondCode CC = (X86::CondCode)N->getConstantOperandVal(2);
9296
9297       if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue())) {
9298         CC = X86::GetOppositeBranchCondition(CC);
9299         std::swap(TrueC, FalseC);
9300       }
9301
9302       // Optimize C ? 8 : 0 -> zext(setcc(C)) << 3.  Likewise for any pow2/0.
9303       // This is efficient for any integer data type (including i8/i16) and
9304       // shift amount.
9305       if (FalseC->getAPIntValue() == 0 && TrueC->getAPIntValue().isPowerOf2()) {
9306         SDValue Cond = N->getOperand(3);
9307         Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
9308                            DAG.getConstant(CC, MVT::i8), Cond);
9309
9310         // Zero extend the condition if needed.
9311         Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, TrueC->getValueType(0), Cond);
9312
9313         unsigned ShAmt = TrueC->getAPIntValue().logBase2();
9314         Cond = DAG.getNode(ISD::SHL, DL, Cond.getValueType(), Cond,
9315                            DAG.getConstant(ShAmt, MVT::i8));
9316         if (N->getNumValues() == 2)  // Dead flag value?
9317           return DCI.CombineTo(N, Cond, SDValue());
9318         return Cond;
9319       }
9320
9321       // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.  This is efficient
9322       // for any integer data type, including i8/i16.
9323       if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
9324         SDValue Cond = N->getOperand(3);
9325         Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
9326                            DAG.getConstant(CC, MVT::i8), Cond);
9327
9328         // Zero extend the condition if needed.
9329         Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
9330                            FalseC->getValueType(0), Cond);
9331         Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
9332                            SDValue(FalseC, 0));
9333
9334         if (N->getNumValues() == 2)  // Dead flag value?
9335           return DCI.CombineTo(N, Cond, SDValue());
9336         return Cond;
9337       }
9338
9339       // Optimize cases that will turn into an LEA instruction.  This requires
9340       // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
9341       if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
9342         uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
9343         if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
9344
9345         bool isFastMultiplier = false;
9346         if (Diff < 10) {
9347           switch ((unsigned char)Diff) {
9348           default: break;
9349           case 1:  // result = add base, cond
9350           case 2:  // result = lea base(    , cond*2)
9351           case 3:  // result = lea base(cond, cond*2)
9352           case 4:  // result = lea base(    , cond*4)
9353           case 5:  // result = lea base(cond, cond*4)
9354           case 8:  // result = lea base(    , cond*8)
9355           case 9:  // result = lea base(cond, cond*8)
9356             isFastMultiplier = true;
9357             break;
9358           }
9359         }
9360
9361         if (isFastMultiplier) {
9362           APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
9363           SDValue Cond = N->getOperand(3);
9364           Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
9365                              DAG.getConstant(CC, MVT::i8), Cond);
9366           // Zero extend the condition if needed.
9367           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
9368                              Cond);
9369           // Scale the condition by the difference.
9370           if (Diff != 1)
9371             Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
9372                                DAG.getConstant(Diff, Cond.getValueType()));
9373
9374           // Add the base if non-zero.
9375           if (FalseC->getAPIntValue() != 0)
9376             Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
9377                                SDValue(FalseC, 0));
9378           if (N->getNumValues() == 2)  // Dead flag value?
9379             return DCI.CombineTo(N, Cond, SDValue());
9380           return Cond;
9381         }
9382       }
9383     }
9384   }
9385   return SDValue();
9386 }
9387
9388
9389 /// PerformMulCombine - Optimize a single multiply with constant into two
9390 /// in order to implement it with two cheaper instructions, e.g.
9391 /// LEA + SHL, LEA + LEA.
9392 static SDValue PerformMulCombine(SDNode *N, SelectionDAG &DAG,
9393                                  TargetLowering::DAGCombinerInfo &DCI) {
9394   if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
9395     return SDValue();
9396
9397   EVT VT = N->getValueType(0);
9398   if (VT != MVT::i64)
9399     return SDValue();
9400
9401   ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
9402   if (!C)
9403     return SDValue();
9404   uint64_t MulAmt = C->getZExtValue();
9405   if (isPowerOf2_64(MulAmt) || MulAmt == 3 || MulAmt == 5 || MulAmt == 9)
9406     return SDValue();
9407
9408   uint64_t MulAmt1 = 0;
9409   uint64_t MulAmt2 = 0;
9410   if ((MulAmt % 9) == 0) {
9411     MulAmt1 = 9;
9412     MulAmt2 = MulAmt / 9;
9413   } else if ((MulAmt % 5) == 0) {
9414     MulAmt1 = 5;
9415     MulAmt2 = MulAmt / 5;
9416   } else if ((MulAmt % 3) == 0) {
9417     MulAmt1 = 3;
9418     MulAmt2 = MulAmt / 3;
9419   }
9420   if (MulAmt2 &&
9421       (isPowerOf2_64(MulAmt2) || MulAmt2 == 3 || MulAmt2 == 5 || MulAmt2 == 9)){
9422     DebugLoc DL = N->getDebugLoc();
9423
9424     if (isPowerOf2_64(MulAmt2) &&
9425         !(N->hasOneUse() && N->use_begin()->getOpcode() == ISD::ADD))
9426       // If second multiplifer is pow2, issue it first. We want the multiply by
9427       // 3, 5, or 9 to be folded into the addressing mode unless the lone use
9428       // is an add.
9429       std::swap(MulAmt1, MulAmt2);
9430
9431     SDValue NewMul;
9432     if (isPowerOf2_64(MulAmt1))
9433       NewMul = DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
9434                            DAG.getConstant(Log2_64(MulAmt1), MVT::i8));
9435     else
9436       NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, N->getOperand(0),
9437                            DAG.getConstant(MulAmt1, VT));
9438
9439     if (isPowerOf2_64(MulAmt2))
9440       NewMul = DAG.getNode(ISD::SHL, DL, VT, NewMul,
9441                            DAG.getConstant(Log2_64(MulAmt2), MVT::i8));
9442     else
9443       NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, NewMul,
9444                            DAG.getConstant(MulAmt2, VT));
9445
9446     // Do not add new nodes to DAG combiner worklist.
9447     DCI.CombineTo(N, NewMul, false);
9448   }
9449   return SDValue();
9450 }
9451
9452 static SDValue PerformSHLCombine(SDNode *N, SelectionDAG &DAG) {
9453   SDValue N0 = N->getOperand(0);
9454   SDValue N1 = N->getOperand(1);
9455   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
9456   EVT VT = N0.getValueType();
9457
9458   // fold (shl (and (setcc_c), c1), c2) -> (and setcc_c, (c1 << c2))
9459   // since the result of setcc_c is all zero's or all ones.
9460   if (N1C && N0.getOpcode() == ISD::AND &&
9461       N0.getOperand(1).getOpcode() == ISD::Constant) {
9462     SDValue N00 = N0.getOperand(0);
9463     if (N00.getOpcode() == X86ISD::SETCC_CARRY ||
9464         ((N00.getOpcode() == ISD::ANY_EXTEND ||
9465           N00.getOpcode() == ISD::ZERO_EXTEND) &&
9466          N00.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY)) {
9467       APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
9468       APInt ShAmt = N1C->getAPIntValue();
9469       Mask = Mask.shl(ShAmt);
9470       if (Mask != 0)
9471         return DAG.getNode(ISD::AND, N->getDebugLoc(), VT,
9472                            N00, DAG.getConstant(Mask, VT));
9473     }
9474   }
9475
9476   return SDValue();
9477 }
9478
9479 /// PerformShiftCombine - Transforms vector shift nodes to use vector shifts
9480 ///                       when possible.
9481 static SDValue PerformShiftCombine(SDNode* N, SelectionDAG &DAG,
9482                                    const X86Subtarget *Subtarget) {
9483   EVT VT = N->getValueType(0);
9484   if (!VT.isVector() && VT.isInteger() &&
9485       N->getOpcode() == ISD::SHL)
9486     return PerformSHLCombine(N, DAG);
9487
9488   // On X86 with SSE2 support, we can transform this to a vector shift if
9489   // all elements are shifted by the same amount.  We can't do this in legalize
9490   // because the a constant vector is typically transformed to a constant pool
9491   // so we have no knowledge of the shift amount.
9492   if (!Subtarget->hasSSE2())
9493     return SDValue();
9494
9495   if (VT != MVT::v2i64 && VT != MVT::v4i32 && VT != MVT::v8i16)
9496     return SDValue();
9497
9498   SDValue ShAmtOp = N->getOperand(1);
9499   EVT EltVT = VT.getVectorElementType();
9500   DebugLoc DL = N->getDebugLoc();
9501   SDValue BaseShAmt = SDValue();
9502   if (ShAmtOp.getOpcode() == ISD::BUILD_VECTOR) {
9503     unsigned NumElts = VT.getVectorNumElements();
9504     unsigned i = 0;
9505     for (; i != NumElts; ++i) {
9506       SDValue Arg = ShAmtOp.getOperand(i);
9507       if (Arg.getOpcode() == ISD::UNDEF) continue;
9508       BaseShAmt = Arg;
9509       break;
9510     }
9511     for (; i != NumElts; ++i) {
9512       SDValue Arg = ShAmtOp.getOperand(i);
9513       if (Arg.getOpcode() == ISD::UNDEF) continue;
9514       if (Arg != BaseShAmt) {
9515         return SDValue();
9516       }
9517     }
9518   } else if (ShAmtOp.getOpcode() == ISD::VECTOR_SHUFFLE &&
9519              cast<ShuffleVectorSDNode>(ShAmtOp)->isSplat()) {
9520     SDValue InVec = ShAmtOp.getOperand(0);
9521     if (InVec.getOpcode() == ISD::BUILD_VECTOR) {
9522       unsigned NumElts = InVec.getValueType().getVectorNumElements();
9523       unsigned i = 0;
9524       for (; i != NumElts; ++i) {
9525         SDValue Arg = InVec.getOperand(i);
9526         if (Arg.getOpcode() == ISD::UNDEF) continue;
9527         BaseShAmt = Arg;
9528         break;
9529       }
9530     } else if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT) {
9531        if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(InVec.getOperand(2))) {
9532          unsigned SplatIdx= cast<ShuffleVectorSDNode>(ShAmtOp)->getSplatIndex();
9533          if (C->getZExtValue() == SplatIdx)
9534            BaseShAmt = InVec.getOperand(1);
9535        }
9536     }
9537     if (BaseShAmt.getNode() == 0)
9538       BaseShAmt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, EltVT, ShAmtOp,
9539                               DAG.getIntPtrConstant(0));
9540   } else
9541     return SDValue();
9542
9543   // The shift amount is an i32.
9544   if (EltVT.bitsGT(MVT::i32))
9545     BaseShAmt = DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, BaseShAmt);
9546   else if (EltVT.bitsLT(MVT::i32))
9547     BaseShAmt = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, BaseShAmt);
9548
9549   // The shift amount is identical so we can do a vector shift.
9550   SDValue  ValOp = N->getOperand(0);
9551   switch (N->getOpcode()) {
9552   default:
9553     llvm_unreachable("Unknown shift opcode!");
9554     break;
9555   case ISD::SHL:
9556     if (VT == MVT::v2i64)
9557       return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
9558                          DAG.getConstant(Intrinsic::x86_sse2_pslli_q, MVT::i32),
9559                          ValOp, BaseShAmt);
9560     if (VT == MVT::v4i32)
9561       return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
9562                          DAG.getConstant(Intrinsic::x86_sse2_pslli_d, MVT::i32),
9563                          ValOp, BaseShAmt);
9564     if (VT == MVT::v8i16)
9565       return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
9566                          DAG.getConstant(Intrinsic::x86_sse2_pslli_w, MVT::i32),
9567                          ValOp, BaseShAmt);
9568     break;
9569   case ISD::SRA:
9570     if (VT == MVT::v4i32)
9571       return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
9572                          DAG.getConstant(Intrinsic::x86_sse2_psrai_d, MVT::i32),
9573                          ValOp, BaseShAmt);
9574     if (VT == MVT::v8i16)
9575       return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
9576                          DAG.getConstant(Intrinsic::x86_sse2_psrai_w, MVT::i32),
9577                          ValOp, BaseShAmt);
9578     break;
9579   case ISD::SRL:
9580     if (VT == MVT::v2i64)
9581       return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
9582                          DAG.getConstant(Intrinsic::x86_sse2_psrli_q, MVT::i32),
9583                          ValOp, BaseShAmt);
9584     if (VT == MVT::v4i32)
9585       return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
9586                          DAG.getConstant(Intrinsic::x86_sse2_psrli_d, MVT::i32),
9587                          ValOp, BaseShAmt);
9588     if (VT ==  MVT::v8i16)
9589       return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
9590                          DAG.getConstant(Intrinsic::x86_sse2_psrli_w, MVT::i32),
9591                          ValOp, BaseShAmt);
9592     break;
9593   }
9594   return SDValue();
9595 }
9596
9597 static SDValue PerformOrCombine(SDNode *N, SelectionDAG &DAG,
9598                                 TargetLowering::DAGCombinerInfo &DCI,
9599                                 const X86Subtarget *Subtarget) {
9600   if (DCI.isBeforeLegalizeOps())
9601     return SDValue();
9602
9603   EVT VT = N->getValueType(0);
9604   if (VT != MVT::i16 && VT != MVT::i32 && VT != MVT::i64)
9605     return SDValue();
9606
9607   // fold (or (x << c) | (y >> (64 - c))) ==> (shld64 x, y, c)
9608   SDValue N0 = N->getOperand(0);
9609   SDValue N1 = N->getOperand(1);
9610   if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL)
9611     std::swap(N0, N1);
9612   if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL)
9613     return SDValue();
9614   if (!N0.hasOneUse() || !N1.hasOneUse())
9615     return SDValue();
9616
9617   SDValue ShAmt0 = N0.getOperand(1);
9618   if (ShAmt0.getValueType() != MVT::i8)
9619     return SDValue();
9620   SDValue ShAmt1 = N1.getOperand(1);
9621   if (ShAmt1.getValueType() != MVT::i8)
9622     return SDValue();
9623   if (ShAmt0.getOpcode() == ISD::TRUNCATE)
9624     ShAmt0 = ShAmt0.getOperand(0);
9625   if (ShAmt1.getOpcode() == ISD::TRUNCATE)
9626     ShAmt1 = ShAmt1.getOperand(0);
9627
9628   DebugLoc DL = N->getDebugLoc();
9629   unsigned Opc = X86ISD::SHLD;
9630   SDValue Op0 = N0.getOperand(0);
9631   SDValue Op1 = N1.getOperand(0);
9632   if (ShAmt0.getOpcode() == ISD::SUB) {
9633     Opc = X86ISD::SHRD;
9634     std::swap(Op0, Op1);
9635     std::swap(ShAmt0, ShAmt1);
9636   }
9637
9638   unsigned Bits = VT.getSizeInBits();
9639   if (ShAmt1.getOpcode() == ISD::SUB) {
9640     SDValue Sum = ShAmt1.getOperand(0);
9641     if (ConstantSDNode *SumC = dyn_cast<ConstantSDNode>(Sum)) {
9642       if (SumC->getSExtValue() == Bits &&
9643           ShAmt1.getOperand(1) == ShAmt0)
9644         return DAG.getNode(Opc, DL, VT,
9645                            Op0, Op1,
9646                            DAG.getNode(ISD::TRUNCATE, DL,
9647                                        MVT::i8, ShAmt0));
9648     }
9649   } else if (ConstantSDNode *ShAmt1C = dyn_cast<ConstantSDNode>(ShAmt1)) {
9650     ConstantSDNode *ShAmt0C = dyn_cast<ConstantSDNode>(ShAmt0);
9651     if (ShAmt0C &&
9652         ShAmt0C->getSExtValue() + ShAmt1C->getSExtValue() == Bits)
9653       return DAG.getNode(Opc, DL, VT,
9654                          N0.getOperand(0), N1.getOperand(0),
9655                          DAG.getNode(ISD::TRUNCATE, DL,
9656                                        MVT::i8, ShAmt0));
9657   }
9658
9659   return SDValue();
9660 }
9661
9662 /// PerformSTORECombine - Do target-specific dag combines on STORE nodes.
9663 static SDValue PerformSTORECombine(SDNode *N, SelectionDAG &DAG,
9664                                    const X86Subtarget *Subtarget) {
9665   // Turn load->store of MMX types into GPR load/stores.  This avoids clobbering
9666   // the FP state in cases where an emms may be missing.
9667   // A preferable solution to the general problem is to figure out the right
9668   // places to insert EMMS.  This qualifies as a quick hack.
9669
9670   // Similarly, turn load->store of i64 into double load/stores in 32-bit mode.
9671   StoreSDNode *St = cast<StoreSDNode>(N);
9672   EVT VT = St->getValue().getValueType();
9673   if (VT.getSizeInBits() != 64)
9674     return SDValue();
9675
9676   const Function *F = DAG.getMachineFunction().getFunction();
9677   bool NoImplicitFloatOps = F->hasFnAttr(Attribute::NoImplicitFloat);
9678   bool F64IsLegal = !UseSoftFloat && !NoImplicitFloatOps
9679     && Subtarget->hasSSE2();
9680   if ((VT.isVector() ||
9681        (VT == MVT::i64 && F64IsLegal && !Subtarget->is64Bit())) &&
9682       isa<LoadSDNode>(St->getValue()) &&
9683       !cast<LoadSDNode>(St->getValue())->isVolatile() &&
9684       St->getChain().hasOneUse() && !St->isVolatile()) {
9685     SDNode* LdVal = St->getValue().getNode();
9686     LoadSDNode *Ld = 0;
9687     int TokenFactorIndex = -1;
9688     SmallVector<SDValue, 8> Ops;
9689     SDNode* ChainVal = St->getChain().getNode();
9690     // Must be a store of a load.  We currently handle two cases:  the load
9691     // is a direct child, and it's under an intervening TokenFactor.  It is
9692     // possible to dig deeper under nested TokenFactors.
9693     if (ChainVal == LdVal)
9694       Ld = cast<LoadSDNode>(St->getChain());
9695     else if (St->getValue().hasOneUse() &&
9696              ChainVal->getOpcode() == ISD::TokenFactor) {
9697       for (unsigned i=0, e = ChainVal->getNumOperands(); i != e; ++i) {
9698         if (ChainVal->getOperand(i).getNode() == LdVal) {
9699           TokenFactorIndex = i;
9700           Ld = cast<LoadSDNode>(St->getValue());
9701         } else
9702           Ops.push_back(ChainVal->getOperand(i));
9703       }
9704     }
9705
9706     if (!Ld || !ISD::isNormalLoad(Ld))
9707       return SDValue();
9708
9709     // If this is not the MMX case, i.e. we are just turning i64 load/store
9710     // into f64 load/store, avoid the transformation if there are multiple
9711     // uses of the loaded value.
9712     if (!VT.isVector() && !Ld->hasNUsesOfValue(1, 0))
9713       return SDValue();
9714
9715     DebugLoc LdDL = Ld->getDebugLoc();
9716     DebugLoc StDL = N->getDebugLoc();
9717     // If we are a 64-bit capable x86, lower to a single movq load/store pair.
9718     // Otherwise, if it's legal to use f64 SSE instructions, use f64 load/store
9719     // pair instead.
9720     if (Subtarget->is64Bit() || F64IsLegal) {
9721       EVT LdVT = Subtarget->is64Bit() ? MVT::i64 : MVT::f64;
9722       SDValue NewLd = DAG.getLoad(LdVT, LdDL, Ld->getChain(),
9723                                   Ld->getBasePtr(), Ld->getSrcValue(),
9724                                   Ld->getSrcValueOffset(), Ld->isVolatile(),
9725                                   Ld->isNonTemporal(), Ld->getAlignment());
9726       SDValue NewChain = NewLd.getValue(1);
9727       if (TokenFactorIndex != -1) {
9728         Ops.push_back(NewChain);
9729         NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, &Ops[0],
9730                                Ops.size());
9731       }
9732       return DAG.getStore(NewChain, StDL, NewLd, St->getBasePtr(),
9733                           St->getSrcValue(), St->getSrcValueOffset(),
9734                           St->isVolatile(), St->isNonTemporal(),
9735                           St->getAlignment());
9736     }
9737
9738     // Otherwise, lower to two pairs of 32-bit loads / stores.
9739     SDValue LoAddr = Ld->getBasePtr();
9740     SDValue HiAddr = DAG.getNode(ISD::ADD, LdDL, MVT::i32, LoAddr,
9741                                  DAG.getConstant(4, MVT::i32));
9742
9743     SDValue LoLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), LoAddr,
9744                                Ld->getSrcValue(), Ld->getSrcValueOffset(),
9745                                Ld->isVolatile(), Ld->isNonTemporal(),
9746                                Ld->getAlignment());
9747     SDValue HiLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), HiAddr,
9748                                Ld->getSrcValue(), Ld->getSrcValueOffset()+4,
9749                                Ld->isVolatile(), Ld->isNonTemporal(),
9750                                MinAlign(Ld->getAlignment(), 4));
9751
9752     SDValue NewChain = LoLd.getValue(1);
9753     if (TokenFactorIndex != -1) {
9754       Ops.push_back(LoLd);
9755       Ops.push_back(HiLd);
9756       NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, &Ops[0],
9757                              Ops.size());
9758     }
9759
9760     LoAddr = St->getBasePtr();
9761     HiAddr = DAG.getNode(ISD::ADD, StDL, MVT::i32, LoAddr,
9762                          DAG.getConstant(4, MVT::i32));
9763
9764     SDValue LoSt = DAG.getStore(NewChain, StDL, LoLd, LoAddr,
9765                                 St->getSrcValue(), St->getSrcValueOffset(),
9766                                 St->isVolatile(), St->isNonTemporal(),
9767                                 St->getAlignment());
9768     SDValue HiSt = DAG.getStore(NewChain, StDL, HiLd, HiAddr,
9769                                 St->getSrcValue(),
9770                                 St->getSrcValueOffset() + 4,
9771                                 St->isVolatile(),
9772                                 St->isNonTemporal(),
9773                                 MinAlign(St->getAlignment(), 4));
9774     return DAG.getNode(ISD::TokenFactor, StDL, MVT::Other, LoSt, HiSt);
9775   }
9776   return SDValue();
9777 }
9778
9779 /// PerformFORCombine - Do target-specific dag combines on X86ISD::FOR and
9780 /// X86ISD::FXOR nodes.
9781 static SDValue PerformFORCombine(SDNode *N, SelectionDAG &DAG) {
9782   assert(N->getOpcode() == X86ISD::FOR || N->getOpcode() == X86ISD::FXOR);
9783   // F[X]OR(0.0, x) -> x
9784   // F[X]OR(x, 0.0) -> x
9785   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
9786     if (C->getValueAPF().isPosZero())
9787       return N->getOperand(1);
9788   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
9789     if (C->getValueAPF().isPosZero())
9790       return N->getOperand(0);
9791   return SDValue();
9792 }
9793
9794 /// PerformFANDCombine - Do target-specific dag combines on X86ISD::FAND nodes.
9795 static SDValue PerformFANDCombine(SDNode *N, SelectionDAG &DAG) {
9796   // FAND(0.0, x) -> 0.0
9797   // FAND(x, 0.0) -> 0.0
9798   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
9799     if (C->getValueAPF().isPosZero())
9800       return N->getOperand(0);
9801   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
9802     if (C->getValueAPF().isPosZero())
9803       return N->getOperand(1);
9804   return SDValue();
9805 }
9806
9807 static SDValue PerformBTCombine(SDNode *N,
9808                                 SelectionDAG &DAG,
9809                                 TargetLowering::DAGCombinerInfo &DCI) {
9810   // BT ignores high bits in the bit index operand.
9811   SDValue Op1 = N->getOperand(1);
9812   if (Op1.hasOneUse()) {
9813     unsigned BitWidth = Op1.getValueSizeInBits();
9814     APInt DemandedMask = APInt::getLowBitsSet(BitWidth, Log2_32(BitWidth));
9815     APInt KnownZero, KnownOne;
9816     TargetLowering::TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(),
9817                                           !DCI.isBeforeLegalizeOps());
9818     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9819     if (TLO.ShrinkDemandedConstant(Op1, DemandedMask) ||
9820         TLI.SimplifyDemandedBits(Op1, DemandedMask, KnownZero, KnownOne, TLO))
9821       DCI.CommitTargetLoweringOpt(TLO);
9822   }
9823   return SDValue();
9824 }
9825
9826 static SDValue PerformVZEXT_MOVLCombine(SDNode *N, SelectionDAG &DAG) {
9827   SDValue Op = N->getOperand(0);
9828   if (Op.getOpcode() == ISD::BIT_CONVERT)
9829     Op = Op.getOperand(0);
9830   EVT VT = N->getValueType(0), OpVT = Op.getValueType();
9831   if (Op.getOpcode() == X86ISD::VZEXT_LOAD &&
9832       VT.getVectorElementType().getSizeInBits() ==
9833       OpVT.getVectorElementType().getSizeInBits()) {
9834     return DAG.getNode(ISD::BIT_CONVERT, N->getDebugLoc(), VT, Op);
9835   }
9836   return SDValue();
9837 }
9838
9839 // On X86 and X86-64, atomic operations are lowered to locked instructions.
9840 // Locked instructions, in turn, have implicit fence semantics (all memory
9841 // operations are flushed before issuing the locked instruction, and the
9842 // are not buffered), so we can fold away the common pattern of
9843 // fence-atomic-fence.
9844 static SDValue PerformMEMBARRIERCombine(SDNode* N, SelectionDAG &DAG) {
9845   SDValue atomic = N->getOperand(0);
9846   switch (atomic.getOpcode()) {
9847     case ISD::ATOMIC_CMP_SWAP:
9848     case ISD::ATOMIC_SWAP:
9849     case ISD::ATOMIC_LOAD_ADD:
9850     case ISD::ATOMIC_LOAD_SUB:
9851     case ISD::ATOMIC_LOAD_AND:
9852     case ISD::ATOMIC_LOAD_OR:
9853     case ISD::ATOMIC_LOAD_XOR:
9854     case ISD::ATOMIC_LOAD_NAND:
9855     case ISD::ATOMIC_LOAD_MIN:
9856     case ISD::ATOMIC_LOAD_MAX:
9857     case ISD::ATOMIC_LOAD_UMIN:
9858     case ISD::ATOMIC_LOAD_UMAX:
9859       break;
9860     default:
9861       return SDValue();
9862   }
9863
9864   SDValue fence = atomic.getOperand(0);
9865   if (fence.getOpcode() != ISD::MEMBARRIER)
9866     return SDValue();
9867
9868   switch (atomic.getOpcode()) {
9869     case ISD::ATOMIC_CMP_SWAP:
9870       return DAG.UpdateNodeOperands(atomic, fence.getOperand(0),
9871                                     atomic.getOperand(1), atomic.getOperand(2),
9872                                     atomic.getOperand(3));
9873     case ISD::ATOMIC_SWAP:
9874     case ISD::ATOMIC_LOAD_ADD:
9875     case ISD::ATOMIC_LOAD_SUB:
9876     case ISD::ATOMIC_LOAD_AND:
9877     case ISD::ATOMIC_LOAD_OR:
9878     case ISD::ATOMIC_LOAD_XOR:
9879     case ISD::ATOMIC_LOAD_NAND:
9880     case ISD::ATOMIC_LOAD_MIN:
9881     case ISD::ATOMIC_LOAD_MAX:
9882     case ISD::ATOMIC_LOAD_UMIN:
9883     case ISD::ATOMIC_LOAD_UMAX:
9884       return DAG.UpdateNodeOperands(atomic, fence.getOperand(0),
9885                                     atomic.getOperand(1), atomic.getOperand(2));
9886     default:
9887       return SDValue();
9888   }
9889 }
9890
9891 static SDValue PerformZExtCombine(SDNode *N, SelectionDAG &DAG) {
9892   // (i32 zext (and (i8  x86isd::setcc_carry), 1)) ->
9893   //           (and (i32 x86isd::setcc_carry), 1)
9894   // This eliminates the zext. This transformation is necessary because
9895   // ISD::SETCC is always legalized to i8.
9896   DebugLoc dl = N->getDebugLoc();
9897   SDValue N0 = N->getOperand(0);
9898   EVT VT = N->getValueType(0);
9899   if (N0.getOpcode() == ISD::AND &&
9900       N0.hasOneUse() &&
9901       N0.getOperand(0).hasOneUse()) {
9902     SDValue N00 = N0.getOperand(0);
9903     if (N00.getOpcode() != X86ISD::SETCC_CARRY)
9904       return SDValue();
9905     ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
9906     if (!C || C->getZExtValue() != 1)
9907       return SDValue();
9908     return DAG.getNode(ISD::AND, dl, VT,
9909                        DAG.getNode(X86ISD::SETCC_CARRY, dl, VT,
9910                                    N00.getOperand(0), N00.getOperand(1)),
9911                        DAG.getConstant(1, VT));
9912   }
9913
9914   return SDValue();
9915 }
9916
9917 SDValue X86TargetLowering::PerformDAGCombine(SDNode *N,
9918                                              DAGCombinerInfo &DCI) const {
9919   SelectionDAG &DAG = DCI.DAG;
9920   switch (N->getOpcode()) {
9921   default: break;
9922   case ISD::VECTOR_SHUFFLE: return PerformShuffleCombine(N, DAG, *this);
9923   case ISD::EXTRACT_VECTOR_ELT:
9924                         return PerformEXTRACT_VECTOR_ELTCombine(N, DAG, *this);
9925   case ISD::SELECT:         return PerformSELECTCombine(N, DAG, Subtarget);
9926   case X86ISD::CMOV:        return PerformCMOVCombine(N, DAG, DCI);
9927   case ISD::MUL:            return PerformMulCombine(N, DAG, DCI);
9928   case ISD::SHL:
9929   case ISD::SRA:
9930   case ISD::SRL:            return PerformShiftCombine(N, DAG, Subtarget);
9931   case ISD::OR:             return PerformOrCombine(N, DAG, DCI, Subtarget);
9932   case ISD::STORE:          return PerformSTORECombine(N, DAG, Subtarget);
9933   case X86ISD::FXOR:
9934   case X86ISD::FOR:         return PerformFORCombine(N, DAG);
9935   case X86ISD::FAND:        return PerformFANDCombine(N, DAG);
9936   case X86ISD::BT:          return PerformBTCombine(N, DAG, DCI);
9937   case X86ISD::VZEXT_MOVL:  return PerformVZEXT_MOVLCombine(N, DAG);
9938   case ISD::MEMBARRIER:     return PerformMEMBARRIERCombine(N, DAG);
9939   case ISD::ZERO_EXTEND:    return PerformZExtCombine(N, DAG);
9940   }
9941
9942   return SDValue();
9943 }
9944
9945 /// isTypeDesirableForOp - Return true if the target has native support for
9946 /// the specified value type and it is 'desirable' to use the type for the
9947 /// given node type. e.g. On x86 i16 is legal, but undesirable since i16
9948 /// instruction encodings are longer and some i16 instructions are slow.
9949 bool X86TargetLowering::isTypeDesirableForOp(unsigned Opc, EVT VT) const {
9950   if (!isTypeLegal(VT))
9951     return false;
9952   if (VT != MVT::i16)
9953     return true;
9954
9955   switch (Opc) {
9956   default:
9957     return true;
9958   case ISD::LOAD:
9959   case ISD::SIGN_EXTEND:
9960   case ISD::ZERO_EXTEND:
9961   case ISD::ANY_EXTEND:
9962   case ISD::SHL:
9963   case ISD::SRL:
9964   case ISD::SUB:
9965   case ISD::ADD:
9966   case ISD::MUL:
9967   case ISD::AND:
9968   case ISD::OR:
9969   case ISD::XOR:
9970     return false;
9971   }
9972 }
9973
9974 static bool MayFoldLoad(SDValue Op) {
9975   return Op.hasOneUse() && ISD::isNormalLoad(Op.getNode());
9976 }
9977
9978 static bool MayFoldIntoStore(SDValue Op) {
9979   return Op.hasOneUse() && ISD::isNormalStore(*Op.getNode()->use_begin());
9980 }
9981
9982 /// IsDesirableToPromoteOp - This method query the target whether it is
9983 /// beneficial for dag combiner to promote the specified node. If true, it
9984 /// should return the desired promotion type by reference.
9985 bool X86TargetLowering::IsDesirableToPromoteOp(SDValue Op, EVT &PVT) const {
9986   EVT VT = Op.getValueType();
9987   if (VT != MVT::i16)
9988     return false;
9989
9990   bool Promote = false;
9991   bool Commute = false;
9992   switch (Op.getOpcode()) {
9993   default: break;
9994   case ISD::LOAD: {
9995     LoadSDNode *LD = cast<LoadSDNode>(Op);
9996     // If the non-extending load has a single use and it's not live out, then it
9997     // might be folded.
9998     if (LD->getExtensionType() == ISD::NON_EXTLOAD /*&&
9999                                                      Op.hasOneUse()*/) {
10000       for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
10001              UE = Op.getNode()->use_end(); UI != UE; ++UI) {
10002         // The only case where we'd want to promote LOAD (rather then it being
10003         // promoted as an operand is when it's only use is liveout.
10004         if (UI->getOpcode() != ISD::CopyToReg)
10005           return false;
10006       }
10007     }
10008     Promote = true;
10009     break;
10010   }
10011   case ISD::SIGN_EXTEND:
10012   case ISD::ZERO_EXTEND:
10013   case ISD::ANY_EXTEND:
10014     Promote = true;
10015     break;
10016   case ISD::SHL:
10017   case ISD::SRL: {
10018     SDValue N0 = Op.getOperand(0);
10019     // Look out for (store (shl (load), x)).
10020     if (MayFoldLoad(N0) && MayFoldIntoStore(Op))
10021       return false;
10022     Promote = true;
10023     break;
10024   }
10025   case ISD::ADD:
10026   case ISD::MUL:
10027   case ISD::AND:
10028   case ISD::OR:
10029   case ISD::XOR:
10030     Commute = true;
10031     // fallthrough
10032   case ISD::SUB: {
10033     SDValue N0 = Op.getOperand(0);
10034     SDValue N1 = Op.getOperand(1);
10035     if (!Commute && MayFoldLoad(N1))
10036       return false;
10037     // Avoid disabling potential load folding opportunities.
10038     if (MayFoldLoad(N0) && (!isa<ConstantSDNode>(N1) || MayFoldIntoStore(Op)))
10039       return false;
10040     if (MayFoldLoad(N1) && (!isa<ConstantSDNode>(N0) || MayFoldIntoStore(Op)))
10041       return false;
10042     Promote = true;
10043   }
10044   }
10045
10046   PVT = MVT::i32;
10047   return Promote;
10048 }
10049
10050 //===----------------------------------------------------------------------===//
10051 //                           X86 Inline Assembly Support
10052 //===----------------------------------------------------------------------===//
10053
10054 static bool LowerToBSwap(CallInst *CI) {
10055   // FIXME: this should verify that we are targetting a 486 or better.  If not,
10056   // we will turn this bswap into something that will be lowered to logical ops
10057   // instead of emitting the bswap asm.  For now, we don't support 486 or lower
10058   // so don't worry about this.
10059
10060   // Verify this is a simple bswap.
10061   if (CI->getNumOperands() != 2 ||
10062       CI->getType() != CI->getOperand(1)->getType() ||
10063       !CI->getType()->isIntegerTy())
10064     return false;
10065
10066   const IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
10067   if (!Ty || Ty->getBitWidth() % 16 != 0)
10068     return false;
10069
10070   // Okay, we can do this xform, do so now.
10071   const Type *Tys[] = { Ty };
10072   Module *M = CI->getParent()->getParent()->getParent();
10073   Constant *Int = Intrinsic::getDeclaration(M, Intrinsic::bswap, Tys, 1);
10074
10075   Value *Op = CI->getOperand(1);
10076   Op = CallInst::Create(Int, Op, CI->getName(), CI);
10077
10078   CI->replaceAllUsesWith(Op);
10079   CI->eraseFromParent();
10080   return true;
10081 }
10082
10083 bool X86TargetLowering::ExpandInlineAsm(CallInst *CI) const {
10084   InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue());
10085   std::vector<InlineAsm::ConstraintInfo> Constraints = IA->ParseConstraints();
10086
10087   std::string AsmStr = IA->getAsmString();
10088
10089   // TODO: should remove alternatives from the asmstring: "foo {a|b}" -> "foo a"
10090   SmallVector<StringRef, 4> AsmPieces;
10091   SplitString(AsmStr, AsmPieces, "\n");  // ; as separator?
10092
10093   switch (AsmPieces.size()) {
10094   default: return false;
10095   case 1:
10096     AsmStr = AsmPieces[0];
10097     AsmPieces.clear();
10098     SplitString(AsmStr, AsmPieces, " \t");  // Split with whitespace.
10099
10100     // bswap $0
10101     if (AsmPieces.size() == 2 &&
10102         (AsmPieces[0] == "bswap" ||
10103          AsmPieces[0] == "bswapq" ||
10104          AsmPieces[0] == "bswapl") &&
10105         (AsmPieces[1] == "$0" ||
10106          AsmPieces[1] == "${0:q}")) {
10107       // No need to check constraints, nothing other than the equivalent of
10108       // "=r,0" would be valid here.
10109       return LowerToBSwap(CI);
10110     }
10111     // rorw $$8, ${0:w}  -->  llvm.bswap.i16
10112     if (CI->getType()->isIntegerTy(16) &&
10113         AsmPieces.size() == 3 &&
10114         (AsmPieces[0] == "rorw" || AsmPieces[0] == "rolw") &&
10115         AsmPieces[1] == "$$8," &&
10116         AsmPieces[2] == "${0:w}" &&
10117         IA->getConstraintString().compare(0, 5, "=r,0,") == 0) {
10118       AsmPieces.clear();
10119       const std::string &Constraints = IA->getConstraintString();
10120       SplitString(StringRef(Constraints).substr(5), AsmPieces, ",");
10121       std::sort(AsmPieces.begin(), AsmPieces.end());
10122       if (AsmPieces.size() == 4 &&
10123           AsmPieces[0] == "~{cc}" &&
10124           AsmPieces[1] == "~{dirflag}" &&
10125           AsmPieces[2] == "~{flags}" &&
10126           AsmPieces[3] == "~{fpsr}") {
10127         return LowerToBSwap(CI);
10128       }
10129     }
10130     break;
10131   case 3:
10132     if (CI->getType()->isIntegerTy(64) &&
10133         Constraints.size() >= 2 &&
10134         Constraints[0].Codes.size() == 1 && Constraints[0].Codes[0] == "A" &&
10135         Constraints[1].Codes.size() == 1 && Constraints[1].Codes[0] == "0") {
10136       // bswap %eax / bswap %edx / xchgl %eax, %edx  -> llvm.bswap.i64
10137       SmallVector<StringRef, 4> Words;
10138       SplitString(AsmPieces[0], Words, " \t");
10139       if (Words.size() == 2 && Words[0] == "bswap" && Words[1] == "%eax") {
10140         Words.clear();
10141         SplitString(AsmPieces[1], Words, " \t");
10142         if (Words.size() == 2 && Words[0] == "bswap" && Words[1] == "%edx") {
10143           Words.clear();
10144           SplitString(AsmPieces[2], Words, " \t,");
10145           if (Words.size() == 3 && Words[0] == "xchgl" && Words[1] == "%eax" &&
10146               Words[2] == "%edx") {
10147             return LowerToBSwap(CI);
10148           }
10149         }
10150       }
10151     }
10152     break;
10153   }
10154   return false;
10155 }
10156
10157
10158
10159 /// getConstraintType - Given a constraint letter, return the type of
10160 /// constraint it is for this target.
10161 X86TargetLowering::ConstraintType
10162 X86TargetLowering::getConstraintType(const std::string &Constraint) const {
10163   if (Constraint.size() == 1) {
10164     switch (Constraint[0]) {
10165     case 'A':
10166       return C_Register;
10167     case 'f':
10168     case 'r':
10169     case 'R':
10170     case 'l':
10171     case 'q':
10172     case 'Q':
10173     case 'x':
10174     case 'y':
10175     case 'Y':
10176       return C_RegisterClass;
10177     case 'e':
10178     case 'Z':
10179       return C_Other;
10180     default:
10181       break;
10182     }
10183   }
10184   return TargetLowering::getConstraintType(Constraint);
10185 }
10186
10187 /// LowerXConstraint - try to replace an X constraint, which matches anything,
10188 /// with another that has more specific requirements based on the type of the
10189 /// corresponding operand.
10190 const char *X86TargetLowering::
10191 LowerXConstraint(EVT ConstraintVT) const {
10192   // FP X constraints get lowered to SSE1/2 registers if available, otherwise
10193   // 'f' like normal targets.
10194   if (ConstraintVT.isFloatingPoint()) {
10195     if (Subtarget->hasSSE2())
10196       return "Y";
10197     if (Subtarget->hasSSE1())
10198       return "x";
10199   }
10200
10201   return TargetLowering::LowerXConstraint(ConstraintVT);
10202 }
10203
10204 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
10205 /// vector.  If it is invalid, don't add anything to Ops.
10206 void X86TargetLowering::LowerAsmOperandForConstraint(SDValue Op,
10207                                                      char Constraint,
10208                                                      bool hasMemory,
10209                                                      std::vector<SDValue>&Ops,
10210                                                      SelectionDAG &DAG) const {
10211   SDValue Result(0, 0);
10212
10213   switch (Constraint) {
10214   default: break;
10215   case 'I':
10216     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
10217       if (C->getZExtValue() <= 31) {
10218         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
10219         break;
10220       }
10221     }
10222     return;
10223   case 'J':
10224     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
10225       if (C->getZExtValue() <= 63) {
10226         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
10227         break;
10228       }
10229     }
10230     return;
10231   case 'K':
10232     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
10233       if ((int8_t)C->getSExtValue() == C->getSExtValue()) {
10234         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
10235         break;
10236       }
10237     }
10238     return;
10239   case 'N':
10240     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
10241       if (C->getZExtValue() <= 255) {
10242         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
10243         break;
10244       }
10245     }
10246     return;
10247   case 'e': {
10248     // 32-bit signed value
10249     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
10250       const ConstantInt *CI = C->getConstantIntValue();
10251       if (CI->isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
10252                                   C->getSExtValue())) {
10253         // Widen to 64 bits here to get it sign extended.
10254         Result = DAG.getTargetConstant(C->getSExtValue(), MVT::i64);
10255         break;
10256       }
10257     // FIXME gcc accepts some relocatable values here too, but only in certain
10258     // memory models; it's complicated.
10259     }
10260     return;
10261   }
10262   case 'Z': {
10263     // 32-bit unsigned value
10264     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
10265       const ConstantInt *CI = C->getConstantIntValue();
10266       if (CI->isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
10267                                   C->getZExtValue())) {
10268         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
10269         break;
10270       }
10271     }
10272     // FIXME gcc accepts some relocatable values here too, but only in certain
10273     // memory models; it's complicated.
10274     return;
10275   }
10276   case 'i': {
10277     // Literal immediates are always ok.
10278     if (ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op)) {
10279       // Widen to 64 bits here to get it sign extended.
10280       Result = DAG.getTargetConstant(CST->getSExtValue(), MVT::i64);
10281       break;
10282     }
10283
10284     // If we are in non-pic codegen mode, we allow the address of a global (with
10285     // an optional displacement) to be used with 'i'.
10286     GlobalAddressSDNode *GA = 0;
10287     int64_t Offset = 0;
10288
10289     // Match either (GA), (GA+C), (GA+C1+C2), etc.
10290     while (1) {
10291       if ((GA = dyn_cast<GlobalAddressSDNode>(Op))) {
10292         Offset += GA->getOffset();
10293         break;
10294       } else if (Op.getOpcode() == ISD::ADD) {
10295         if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
10296           Offset += C->getZExtValue();
10297           Op = Op.getOperand(0);
10298           continue;
10299         }
10300       } else if (Op.getOpcode() == ISD::SUB) {
10301         if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
10302           Offset += -C->getZExtValue();
10303           Op = Op.getOperand(0);
10304           continue;
10305         }
10306       }
10307
10308       // Otherwise, this isn't something we can handle, reject it.
10309       return;
10310     }
10311
10312     const GlobalValue *GV = GA->getGlobal();
10313     // If we require an extra load to get this address, as in PIC mode, we
10314     // can't accept it.
10315     if (isGlobalStubReference(Subtarget->ClassifyGlobalReference(GV,
10316                                                         getTargetMachine())))
10317       return;
10318
10319     if (hasMemory)
10320       Op = LowerGlobalAddress(GV, Op.getDebugLoc(), Offset, DAG);
10321     else
10322       Op = DAG.getTargetGlobalAddress(GV, GA->getValueType(0), Offset);
10323     Result = Op;
10324     break;
10325   }
10326   }
10327
10328   if (Result.getNode()) {
10329     Ops.push_back(Result);
10330     return;
10331   }
10332   return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, hasMemory,
10333                                                       Ops, DAG);
10334 }
10335
10336 std::vector<unsigned> X86TargetLowering::
10337 getRegClassForInlineAsmConstraint(const std::string &Constraint,
10338                                   EVT VT) const {
10339   if (Constraint.size() == 1) {
10340     // FIXME: not handling fp-stack yet!
10341     switch (Constraint[0]) {      // GCC X86 Constraint Letters
10342     default: break;  // Unknown constraint letter
10343     case 'q':   // GENERAL_REGS in 64-bit mode, Q_REGS in 32-bit mode.
10344       if (Subtarget->is64Bit()) {
10345         if (VT == MVT::i32)
10346           return make_vector<unsigned>(X86::EAX, X86::EDX, X86::ECX, X86::EBX,
10347                                        X86::ESI, X86::EDI, X86::R8D, X86::R9D,
10348                                        X86::R10D,X86::R11D,X86::R12D,
10349                                        X86::R13D,X86::R14D,X86::R15D,
10350                                        X86::EBP, X86::ESP, 0);
10351         else if (VT == MVT::i16)
10352           return make_vector<unsigned>(X86::AX,  X86::DX,  X86::CX, X86::BX,
10353                                        X86::SI,  X86::DI,  X86::R8W,X86::R9W,
10354                                        X86::R10W,X86::R11W,X86::R12W,
10355                                        X86::R13W,X86::R14W,X86::R15W,
10356                                        X86::BP,  X86::SP, 0);
10357         else if (VT == MVT::i8)
10358           return make_vector<unsigned>(X86::AL,  X86::DL,  X86::CL, X86::BL,
10359                                        X86::SIL, X86::DIL, X86::R8B,X86::R9B,
10360                                        X86::R10B,X86::R11B,X86::R12B,
10361                                        X86::R13B,X86::R14B,X86::R15B,
10362                                        X86::BPL, X86::SPL, 0);
10363
10364         else if (VT == MVT::i64)
10365           return make_vector<unsigned>(X86::RAX, X86::RDX, X86::RCX, X86::RBX,
10366                                        X86::RSI, X86::RDI, X86::R8,  X86::R9,
10367                                        X86::R10, X86::R11, X86::R12,
10368                                        X86::R13, X86::R14, X86::R15,
10369                                        X86::RBP, X86::RSP, 0);
10370
10371         break;
10372       }
10373       // 32-bit fallthrough
10374     case 'Q':   // Q_REGS
10375       if (VT == MVT::i32)
10376         return make_vector<unsigned>(X86::EAX, X86::EDX, X86::ECX, X86::EBX, 0);
10377       else if (VT == MVT::i16)
10378         return make_vector<unsigned>(X86::AX, X86::DX, X86::CX, X86::BX, 0);
10379       else if (VT == MVT::i8)
10380         return make_vector<unsigned>(X86::AL, X86::DL, X86::CL, X86::BL, 0);
10381       else if (VT == MVT::i64)
10382         return make_vector<unsigned>(X86::RAX, X86::RDX, X86::RCX, X86::RBX, 0);
10383       break;
10384     }
10385   }
10386
10387   return std::vector<unsigned>();
10388 }
10389
10390 std::pair<unsigned, const TargetRegisterClass*>
10391 X86TargetLowering::getRegForInlineAsmConstraint(const std::string &Constraint,
10392                                                 EVT VT) const {
10393   // First, see if this is a constraint that directly corresponds to an LLVM
10394   // register class.
10395   if (Constraint.size() == 1) {
10396     // GCC Constraint Letters
10397     switch (Constraint[0]) {
10398     default: break;
10399     case 'r':   // GENERAL_REGS
10400     case 'l':   // INDEX_REGS
10401       if (VT == MVT::i8)
10402         return std::make_pair(0U, X86::GR8RegisterClass);
10403       if (VT == MVT::i16)
10404         return std::make_pair(0U, X86::GR16RegisterClass);
10405       if (VT == MVT::i32 || !Subtarget->is64Bit())
10406         return std::make_pair(0U, X86::GR32RegisterClass);
10407       return std::make_pair(0U, X86::GR64RegisterClass);
10408     case 'R':   // LEGACY_REGS
10409       if (VT == MVT::i8)
10410         return std::make_pair(0U, X86::GR8_NOREXRegisterClass);
10411       if (VT == MVT::i16)
10412         return std::make_pair(0U, X86::GR16_NOREXRegisterClass);
10413       if (VT == MVT::i32 || !Subtarget->is64Bit())
10414         return std::make_pair(0U, X86::GR32_NOREXRegisterClass);
10415       return std::make_pair(0U, X86::GR64_NOREXRegisterClass);
10416     case 'f':  // FP Stack registers.
10417       // If SSE is enabled for this VT, use f80 to ensure the isel moves the
10418       // value to the correct fpstack register class.
10419       if (VT == MVT::f32 && !isScalarFPTypeInSSEReg(VT))
10420         return std::make_pair(0U, X86::RFP32RegisterClass);
10421       if (VT == MVT::f64 && !isScalarFPTypeInSSEReg(VT))
10422         return std::make_pair(0U, X86::RFP64RegisterClass);
10423       return std::make_pair(0U, X86::RFP80RegisterClass);
10424     case 'y':   // MMX_REGS if MMX allowed.
10425       if (!Subtarget->hasMMX()) break;
10426       return std::make_pair(0U, X86::VR64RegisterClass);
10427     case 'Y':   // SSE_REGS if SSE2 allowed
10428       if (!Subtarget->hasSSE2()) break;
10429       // FALL THROUGH.
10430     case 'x':   // SSE_REGS if SSE1 allowed
10431       if (!Subtarget->hasSSE1()) break;
10432
10433       switch (VT.getSimpleVT().SimpleTy) {
10434       default: break;
10435       // Scalar SSE types.
10436       case MVT::f32:
10437       case MVT::i32:
10438         return std::make_pair(0U, X86::FR32RegisterClass);
10439       case MVT::f64:
10440       case MVT::i64:
10441         return std::make_pair(0U, X86::FR64RegisterClass);
10442       // Vector types.
10443       case MVT::v16i8:
10444       case MVT::v8i16:
10445       case MVT::v4i32:
10446       case MVT::v2i64:
10447       case MVT::v4f32:
10448       case MVT::v2f64:
10449         return std::make_pair(0U, X86::VR128RegisterClass);
10450       }
10451       break;
10452     }
10453   }
10454
10455   // Use the default implementation in TargetLowering to convert the register
10456   // constraint into a member of a register class.
10457   std::pair<unsigned, const TargetRegisterClass*> Res;
10458   Res = TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
10459
10460   // Not found as a standard register?
10461   if (Res.second == 0) {
10462     // Map st(0) -> st(7) -> ST0
10463     if (Constraint.size() == 7 && Constraint[0] == '{' &&
10464         tolower(Constraint[1]) == 's' &&
10465         tolower(Constraint[2]) == 't' &&
10466         Constraint[3] == '(' &&
10467         (Constraint[4] >= '0' && Constraint[4] <= '7') &&
10468         Constraint[5] == ')' &&
10469         Constraint[6] == '}') {
10470
10471       Res.first = X86::ST0+Constraint[4]-'0';
10472       Res.second = X86::RFP80RegisterClass;
10473       return Res;
10474     }
10475
10476     // GCC allows "st(0)" to be called just plain "st".
10477     if (StringRef("{st}").equals_lower(Constraint)) {
10478       Res.first = X86::ST0;
10479       Res.second = X86::RFP80RegisterClass;
10480       return Res;
10481     }
10482
10483     // flags -> EFLAGS
10484     if (StringRef("{flags}").equals_lower(Constraint)) {
10485       Res.first = X86::EFLAGS;
10486       Res.second = X86::CCRRegisterClass;
10487       return Res;
10488     }
10489
10490     // 'A' means EAX + EDX.
10491     if (Constraint == "A") {
10492       Res.first = X86::EAX;
10493       Res.second = X86::GR32_ADRegisterClass;
10494       return Res;
10495     }
10496     return Res;
10497   }
10498
10499   // Otherwise, check to see if this is a register class of the wrong value
10500   // type.  For example, we want to map "{ax},i32" -> {eax}, we don't want it to
10501   // turn into {ax},{dx}.
10502   if (Res.second->hasType(VT))
10503     return Res;   // Correct type already, nothing to do.
10504
10505   // All of the single-register GCC register classes map their values onto
10506   // 16-bit register pieces "ax","dx","cx","bx","si","di","bp","sp".  If we
10507   // really want an 8-bit or 32-bit register, map to the appropriate register
10508   // class and return the appropriate register.
10509   if (Res.second == X86::GR16RegisterClass) {
10510     if (VT == MVT::i8) {
10511       unsigned DestReg = 0;
10512       switch (Res.first) {
10513       default: break;
10514       case X86::AX: DestReg = X86::AL; break;
10515       case X86::DX: DestReg = X86::DL; break;
10516       case X86::CX: DestReg = X86::CL; break;
10517       case X86::BX: DestReg = X86::BL; break;
10518       }
10519       if (DestReg) {
10520         Res.first = DestReg;
10521         Res.second = X86::GR8RegisterClass;
10522       }
10523     } else if (VT == MVT::i32) {
10524       unsigned DestReg = 0;
10525       switch (Res.first) {
10526       default: break;
10527       case X86::AX: DestReg = X86::EAX; break;
10528       case X86::DX: DestReg = X86::EDX; break;
10529       case X86::CX: DestReg = X86::ECX; break;
10530       case X86::BX: DestReg = X86::EBX; break;
10531       case X86::SI: DestReg = X86::ESI; break;
10532       case X86::DI: DestReg = X86::EDI; break;
10533       case X86::BP: DestReg = X86::EBP; break;
10534       case X86::SP: DestReg = X86::ESP; break;
10535       }
10536       if (DestReg) {
10537         Res.first = DestReg;
10538         Res.second = X86::GR32RegisterClass;
10539       }
10540     } else if (VT == MVT::i64) {
10541       unsigned DestReg = 0;
10542       switch (Res.first) {
10543       default: break;
10544       case X86::AX: DestReg = X86::RAX; break;
10545       case X86::DX: DestReg = X86::RDX; break;
10546       case X86::CX: DestReg = X86::RCX; break;
10547       case X86::BX: DestReg = X86::RBX; break;
10548       case X86::SI: DestReg = X86::RSI; break;
10549       case X86::DI: DestReg = X86::RDI; break;
10550       case X86::BP: DestReg = X86::RBP; break;
10551       case X86::SP: DestReg = X86::RSP; break;
10552       }
10553       if (DestReg) {
10554         Res.first = DestReg;
10555         Res.second = X86::GR64RegisterClass;
10556       }
10557     }
10558   } else if (Res.second == X86::FR32RegisterClass ||
10559              Res.second == X86::FR64RegisterClass ||
10560              Res.second == X86::VR128RegisterClass) {
10561     // Handle references to XMM physical registers that got mapped into the
10562     // wrong class.  This can happen with constraints like {xmm0} where the
10563     // target independent register mapper will just pick the first match it can
10564     // find, ignoring the required type.
10565     if (VT == MVT::f32)
10566       Res.second = X86::FR32RegisterClass;
10567     else if (VT == MVT::f64)
10568       Res.second = X86::FR64RegisterClass;
10569     else if (X86::VR128RegisterClass->hasType(VT))
10570       Res.second = X86::VR128RegisterClass;
10571   }
10572
10573   return Res;
10574 }