Pass callsite return type to TargetLowering::LowerCall and use that to check sibcall...
[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/ErrorHandling.h"
49 #include "llvm/Support/MathExtras.h"
50 #include "llvm/Support/raw_ostream.h"
51 using namespace llvm;
52
53 STATISTIC(NumTailCalls, "Number of tail calls");
54
55 static cl::opt<bool>
56 DisableMMX("disable-mmx", cl::Hidden, cl::desc("Disable use of MMX"));
57
58 // Disable16Bit - 16-bit operations typically have a larger encoding than
59 // corresponding 32-bit instructions, and 16-bit code is slow on some
60 // processors. This is an experimental flag to disable 16-bit operations
61 // (which forces them to be Legalized to 32-bit operations).
62 static cl::opt<bool>
63 Disable16Bit("disable-16bit", cl::Hidden,
64              cl::desc("Disable use of 16-bit instructions"));
65
66 // Forward declarations.
67 static SDValue getMOVL(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
68                        SDValue V2);
69
70 static TargetLoweringObjectFile *createTLOF(X86TargetMachine &TM) {
71   switch (TM.getSubtarget<X86Subtarget>().TargetType) {
72   default: llvm_unreachable("unknown subtarget type");
73   case X86Subtarget::isDarwin:
74     if (TM.getSubtarget<X86Subtarget>().is64Bit())
75       return new X8664_MachoTargetObjectFile();
76     return new X8632_MachoTargetObjectFile();
77   case X86Subtarget::isELF:
78     return new TargetLoweringObjectFileELF();
79   case X86Subtarget::isMingw:
80   case X86Subtarget::isCygwin:
81   case X86Subtarget::isWindows:
82     return new TargetLoweringObjectFileCOFF();
83   }
84
85 }
86
87 X86TargetLowering::X86TargetLowering(X86TargetMachine &TM)
88   : TargetLowering(TM, createTLOF(TM)) {
89   Subtarget = &TM.getSubtarget<X86Subtarget>();
90   X86ScalarSSEf64 = Subtarget->hasSSE2();
91   X86ScalarSSEf32 = Subtarget->hasSSE1();
92   X86StackPtr = Subtarget->is64Bit() ? X86::RSP : X86::ESP;
93
94   RegInfo = TM.getRegisterInfo();
95   TD = getTargetData();
96
97   // Set up the TargetLowering object.
98
99   // X86 is weird, it always uses i8 for shift amounts and setcc results.
100   setShiftAmountType(MVT::i8);
101   setBooleanContents(ZeroOrOneBooleanContent);
102   setSchedulingPreference(SchedulingForRegPressure);
103   setStackPointerRegisterToSaveRestore(X86StackPtr);
104
105   if (Subtarget->isTargetDarwin()) {
106     // Darwin should use _setjmp/_longjmp instead of setjmp/longjmp.
107     setUseUnderscoreSetJmp(false);
108     setUseUnderscoreLongJmp(false);
109   } else if (Subtarget->isTargetMingw()) {
110     // MS runtime is weird: it exports _setjmp, but longjmp!
111     setUseUnderscoreSetJmp(true);
112     setUseUnderscoreLongJmp(false);
113   } else {
114     setUseUnderscoreSetJmp(true);
115     setUseUnderscoreLongJmp(true);
116   }
117
118   // Set up the register classes.
119   addRegisterClass(MVT::i8, X86::GR8RegisterClass);
120   if (!Disable16Bit)
121     addRegisterClass(MVT::i16, X86::GR16RegisterClass);
122   addRegisterClass(MVT::i32, X86::GR32RegisterClass);
123   if (Subtarget->is64Bit())
124     addRegisterClass(MVT::i64, X86::GR64RegisterClass);
125
126   setLoadExtAction(ISD::SEXTLOAD, MVT::i1, Promote);
127
128   // We don't accept any truncstore of integer registers.
129   setTruncStoreAction(MVT::i64, MVT::i32, Expand);
130   if (!Disable16Bit)
131     setTruncStoreAction(MVT::i64, MVT::i16, Expand);
132   setTruncStoreAction(MVT::i64, MVT::i8 , Expand);
133   if (!Disable16Bit)
134     setTruncStoreAction(MVT::i32, MVT::i16, Expand);
135   setTruncStoreAction(MVT::i32, MVT::i8 , Expand);
136   setTruncStoreAction(MVT::i16, MVT::i8,  Expand);
137
138   // SETOEQ and SETUNE require checking two conditions.
139   setCondCodeAction(ISD::SETOEQ, MVT::f32, Expand);
140   setCondCodeAction(ISD::SETOEQ, MVT::f64, Expand);
141   setCondCodeAction(ISD::SETOEQ, MVT::f80, Expand);
142   setCondCodeAction(ISD::SETUNE, MVT::f32, Expand);
143   setCondCodeAction(ISD::SETUNE, MVT::f64, Expand);
144   setCondCodeAction(ISD::SETUNE, MVT::f80, Expand);
145
146   // Promote all UINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have this
147   // operation.
148   setOperationAction(ISD::UINT_TO_FP       , MVT::i1   , Promote);
149   setOperationAction(ISD::UINT_TO_FP       , MVT::i8   , Promote);
150   setOperationAction(ISD::UINT_TO_FP       , MVT::i16  , Promote);
151
152   if (Subtarget->is64Bit()) {
153     setOperationAction(ISD::UINT_TO_FP     , MVT::i32  , Promote);
154     setOperationAction(ISD::UINT_TO_FP     , MVT::i64  , Expand);
155   } else if (!UseSoftFloat) {
156     if (X86ScalarSSEf64) {
157       // We have an impenetrably clever algorithm for ui64->double only.
158       setOperationAction(ISD::UINT_TO_FP   , MVT::i64  , Custom);
159     }
160     // We have an algorithm for SSE2, and we turn this into a 64-bit
161     // FILD for other targets.
162     setOperationAction(ISD::UINT_TO_FP   , MVT::i32  , Custom);
163   }
164
165   // Promote i1/i8 SINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have
166   // this operation.
167   setOperationAction(ISD::SINT_TO_FP       , MVT::i1   , Promote);
168   setOperationAction(ISD::SINT_TO_FP       , MVT::i8   , Promote);
169
170   if (!UseSoftFloat) {
171     // SSE has no i16 to fp conversion, only i32
172     if (X86ScalarSSEf32) {
173       setOperationAction(ISD::SINT_TO_FP     , MVT::i16  , Promote);
174       // f32 and f64 cases are Legal, f80 case is not
175       setOperationAction(ISD::SINT_TO_FP     , MVT::i32  , Custom);
176     } else {
177       setOperationAction(ISD::SINT_TO_FP     , MVT::i16  , Custom);
178       setOperationAction(ISD::SINT_TO_FP     , MVT::i32  , Custom);
179     }
180   } else {
181     setOperationAction(ISD::SINT_TO_FP     , MVT::i16  , Promote);
182     setOperationAction(ISD::SINT_TO_FP     , MVT::i32  , Promote);
183   }
184
185   // In 32-bit mode these are custom lowered.  In 64-bit mode F32 and F64
186   // are Legal, f80 is custom lowered.
187   setOperationAction(ISD::FP_TO_SINT     , MVT::i64  , Custom);
188   setOperationAction(ISD::SINT_TO_FP     , MVT::i64  , Custom);
189
190   // Promote i1/i8 FP_TO_SINT to larger FP_TO_SINTS's, as X86 doesn't have
191   // this operation.
192   setOperationAction(ISD::FP_TO_SINT       , MVT::i1   , Promote);
193   setOperationAction(ISD::FP_TO_SINT       , MVT::i8   , Promote);
194
195   if (X86ScalarSSEf32) {
196     setOperationAction(ISD::FP_TO_SINT     , MVT::i16  , Promote);
197     // f32 and f64 cases are Legal, f80 case is not
198     setOperationAction(ISD::FP_TO_SINT     , MVT::i32  , Custom);
199   } else {
200     setOperationAction(ISD::FP_TO_SINT     , MVT::i16  , Custom);
201     setOperationAction(ISD::FP_TO_SINT     , MVT::i32  , Custom);
202   }
203
204   // Handle FP_TO_UINT by promoting the destination to a larger signed
205   // conversion.
206   setOperationAction(ISD::FP_TO_UINT       , MVT::i1   , Promote);
207   setOperationAction(ISD::FP_TO_UINT       , MVT::i8   , Promote);
208   setOperationAction(ISD::FP_TO_UINT       , MVT::i16  , Promote);
209
210   if (Subtarget->is64Bit()) {
211     setOperationAction(ISD::FP_TO_UINT     , MVT::i64  , Expand);
212     setOperationAction(ISD::FP_TO_UINT     , MVT::i32  , Promote);
213   } else if (!UseSoftFloat) {
214     if (X86ScalarSSEf32 && !Subtarget->hasSSE3())
215       // Expand FP_TO_UINT into a select.
216       // FIXME: We would like to use a Custom expander here eventually to do
217       // the optimal thing for SSE vs. the default expansion in the legalizer.
218       setOperationAction(ISD::FP_TO_UINT   , MVT::i32  , Expand);
219     else
220       // With SSE3 we can use fisttpll to convert to a signed i64; without
221       // SSE, we're stuck with a fistpll.
222       setOperationAction(ISD::FP_TO_UINT   , MVT::i32  , Custom);
223   }
224
225   // TODO: when we have SSE, these could be more efficient, by using movd/movq.
226   if (!X86ScalarSSEf64) {
227     setOperationAction(ISD::BIT_CONVERT      , MVT::f32  , Expand);
228     setOperationAction(ISD::BIT_CONVERT      , MVT::i32  , Expand);
229   }
230
231   // Scalar integer divide and remainder are lowered to use operations that
232   // produce two results, to match the available instructions. This exposes
233   // the two-result form to trivial CSE, which is able to combine x/y and x%y
234   // into a single instruction.
235   //
236   // Scalar integer multiply-high is also lowered to use two-result
237   // operations, to match the available instructions. However, plain multiply
238   // (low) operations are left as Legal, as there are single-result
239   // instructions for this in x86. Using the two-result multiply instructions
240   // when both high and low results are needed must be arranged by dagcombine.
241   setOperationAction(ISD::MULHS           , MVT::i8    , Expand);
242   setOperationAction(ISD::MULHU           , MVT::i8    , Expand);
243   setOperationAction(ISD::SDIV            , MVT::i8    , Expand);
244   setOperationAction(ISD::UDIV            , MVT::i8    , Expand);
245   setOperationAction(ISD::SREM            , MVT::i8    , Expand);
246   setOperationAction(ISD::UREM            , MVT::i8    , Expand);
247   setOperationAction(ISD::MULHS           , MVT::i16   , Expand);
248   setOperationAction(ISD::MULHU           , MVT::i16   , Expand);
249   setOperationAction(ISD::SDIV            , MVT::i16   , Expand);
250   setOperationAction(ISD::UDIV            , MVT::i16   , Expand);
251   setOperationAction(ISD::SREM            , MVT::i16   , Expand);
252   setOperationAction(ISD::UREM            , MVT::i16   , Expand);
253   setOperationAction(ISD::MULHS           , MVT::i32   , Expand);
254   setOperationAction(ISD::MULHU           , MVT::i32   , Expand);
255   setOperationAction(ISD::SDIV            , MVT::i32   , Expand);
256   setOperationAction(ISD::UDIV            , MVT::i32   , Expand);
257   setOperationAction(ISD::SREM            , MVT::i32   , Expand);
258   setOperationAction(ISD::UREM            , MVT::i32   , Expand);
259   setOperationAction(ISD::MULHS           , MVT::i64   , Expand);
260   setOperationAction(ISD::MULHU           , MVT::i64   , Expand);
261   setOperationAction(ISD::SDIV            , MVT::i64   , Expand);
262   setOperationAction(ISD::UDIV            , MVT::i64   , Expand);
263   setOperationAction(ISD::SREM            , MVT::i64   , Expand);
264   setOperationAction(ISD::UREM            , MVT::i64   , Expand);
265
266   setOperationAction(ISD::BR_JT            , MVT::Other, Expand);
267   setOperationAction(ISD::BRCOND           , MVT::Other, Custom);
268   setOperationAction(ISD::BR_CC            , MVT::Other, Expand);
269   setOperationAction(ISD::SELECT_CC        , MVT::Other, Expand);
270   if (Subtarget->is64Bit())
271     setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i32, Legal);
272   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16  , Legal);
273   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8   , Legal);
274   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1   , Expand);
275   setOperationAction(ISD::FP_ROUND_INREG   , MVT::f32  , Expand);
276   setOperationAction(ISD::FREM             , MVT::f32  , Expand);
277   setOperationAction(ISD::FREM             , MVT::f64  , Expand);
278   setOperationAction(ISD::FREM             , MVT::f80  , Expand);
279   setOperationAction(ISD::FLT_ROUNDS_      , MVT::i32  , Custom);
280
281   setOperationAction(ISD::CTPOP            , MVT::i8   , Expand);
282   setOperationAction(ISD::CTTZ             , MVT::i8   , Custom);
283   setOperationAction(ISD::CTLZ             , MVT::i8   , Custom);
284   setOperationAction(ISD::CTPOP            , MVT::i16  , Expand);
285   if (Disable16Bit) {
286     setOperationAction(ISD::CTTZ           , MVT::i16  , Expand);
287     setOperationAction(ISD::CTLZ           , MVT::i16  , Expand);
288   } else {
289     setOperationAction(ISD::CTTZ           , MVT::i16  , Custom);
290     setOperationAction(ISD::CTLZ           , MVT::i16  , Custom);
291   }
292   setOperationAction(ISD::CTPOP            , MVT::i32  , Expand);
293   setOperationAction(ISD::CTTZ             , MVT::i32  , Custom);
294   setOperationAction(ISD::CTLZ             , MVT::i32  , Custom);
295   if (Subtarget->is64Bit()) {
296     setOperationAction(ISD::CTPOP          , MVT::i64  , Expand);
297     setOperationAction(ISD::CTTZ           , MVT::i64  , Custom);
298     setOperationAction(ISD::CTLZ           , MVT::i64  , Custom);
299   }
300
301   setOperationAction(ISD::READCYCLECOUNTER , MVT::i64  , Custom);
302   setOperationAction(ISD::BSWAP            , MVT::i16  , Expand);
303
304   // These should be promoted to a larger select which is supported.
305   setOperationAction(ISD::SELECT          , MVT::i1   , Promote);
306   // X86 wants to expand cmov itself.
307   setOperationAction(ISD::SELECT          , MVT::i8   , Custom);
308   if (Disable16Bit)
309     setOperationAction(ISD::SELECT        , MVT::i16  , Expand);
310   else
311     setOperationAction(ISD::SELECT        , MVT::i16  , Custom);
312   setOperationAction(ISD::SELECT          , MVT::i32  , Custom);
313   setOperationAction(ISD::SELECT          , MVT::f32  , Custom);
314   setOperationAction(ISD::SELECT          , MVT::f64  , Custom);
315   setOperationAction(ISD::SELECT          , MVT::f80  , Custom);
316   setOperationAction(ISD::SETCC           , MVT::i8   , Custom);
317   if (Disable16Bit)
318     setOperationAction(ISD::SETCC         , MVT::i16  , Expand);
319   else
320     setOperationAction(ISD::SETCC         , MVT::i16  , Custom);
321   setOperationAction(ISD::SETCC           , MVT::i32  , Custom);
322   setOperationAction(ISD::SETCC           , MVT::f32  , Custom);
323   setOperationAction(ISD::SETCC           , MVT::f64  , Custom);
324   setOperationAction(ISD::SETCC           , MVT::f80  , Custom);
325   if (Subtarget->is64Bit()) {
326     setOperationAction(ISD::SELECT        , MVT::i64  , Custom);
327     setOperationAction(ISD::SETCC         , MVT::i64  , Custom);
328   }
329   setOperationAction(ISD::EH_RETURN       , MVT::Other, Custom);
330
331   // Darwin ABI issue.
332   setOperationAction(ISD::ConstantPool    , MVT::i32  , Custom);
333   setOperationAction(ISD::JumpTable       , MVT::i32  , Custom);
334   setOperationAction(ISD::GlobalAddress   , MVT::i32  , Custom);
335   setOperationAction(ISD::GlobalTLSAddress, MVT::i32  , Custom);
336   if (Subtarget->is64Bit())
337     setOperationAction(ISD::GlobalTLSAddress, MVT::i64, Custom);
338   setOperationAction(ISD::ExternalSymbol  , MVT::i32  , Custom);
339   setOperationAction(ISD::BlockAddress    , MVT::i32  , Custom);
340   if (Subtarget->is64Bit()) {
341     setOperationAction(ISD::ConstantPool  , MVT::i64  , Custom);
342     setOperationAction(ISD::JumpTable     , MVT::i64  , Custom);
343     setOperationAction(ISD::GlobalAddress , MVT::i64  , Custom);
344     setOperationAction(ISD::ExternalSymbol, MVT::i64  , Custom);
345     setOperationAction(ISD::BlockAddress  , MVT::i64  , Custom);
346   }
347   // 64-bit addm sub, shl, sra, srl (iff 32-bit x86)
348   setOperationAction(ISD::SHL_PARTS       , MVT::i32  , Custom);
349   setOperationAction(ISD::SRA_PARTS       , MVT::i32  , Custom);
350   setOperationAction(ISD::SRL_PARTS       , MVT::i32  , Custom);
351   if (Subtarget->is64Bit()) {
352     setOperationAction(ISD::SHL_PARTS     , MVT::i64  , Custom);
353     setOperationAction(ISD::SRA_PARTS     , MVT::i64  , Custom);
354     setOperationAction(ISD::SRL_PARTS     , MVT::i64  , Custom);
355   }
356
357   if (Subtarget->hasSSE1())
358     setOperationAction(ISD::PREFETCH      , MVT::Other, Legal);
359
360   if (!Subtarget->hasSSE2())
361     setOperationAction(ISD::MEMBARRIER    , MVT::Other, Expand);
362
363   // Expand certain atomics
364   setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i8, Custom);
365   setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i16, Custom);
366   setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i32, Custom);
367   setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i64, Custom);
368
369   setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i8, Custom);
370   setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i16, Custom);
371   setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i32, Custom);
372   setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i64, Custom);
373
374   if (!Subtarget->is64Bit()) {
375     setOperationAction(ISD::ATOMIC_LOAD_ADD, MVT::i64, Custom);
376     setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i64, Custom);
377     setOperationAction(ISD::ATOMIC_LOAD_AND, MVT::i64, Custom);
378     setOperationAction(ISD::ATOMIC_LOAD_OR, MVT::i64, Custom);
379     setOperationAction(ISD::ATOMIC_LOAD_XOR, MVT::i64, Custom);
380     setOperationAction(ISD::ATOMIC_LOAD_NAND, MVT::i64, Custom);
381     setOperationAction(ISD::ATOMIC_SWAP, MVT::i64, Custom);
382   }
383
384   // FIXME - use subtarget debug flags
385   if (!Subtarget->isTargetDarwin() &&
386       !Subtarget->isTargetELF() &&
387       !Subtarget->isTargetCygMing()) {
388     setOperationAction(ISD::EH_LABEL, MVT::Other, Expand);
389   }
390
391   setOperationAction(ISD::EXCEPTIONADDR, MVT::i64, Expand);
392   setOperationAction(ISD::EHSELECTION,   MVT::i64, Expand);
393   setOperationAction(ISD::EXCEPTIONADDR, MVT::i32, Expand);
394   setOperationAction(ISD::EHSELECTION,   MVT::i32, Expand);
395   if (Subtarget->is64Bit()) {
396     setExceptionPointerRegister(X86::RAX);
397     setExceptionSelectorRegister(X86::RDX);
398   } else {
399     setExceptionPointerRegister(X86::EAX);
400     setExceptionSelectorRegister(X86::EDX);
401   }
402   setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i32, Custom);
403   setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i64, Custom);
404
405   setOperationAction(ISD::TRAMPOLINE, MVT::Other, Custom);
406
407   setOperationAction(ISD::TRAP, MVT::Other, Legal);
408
409   // VASTART needs to be custom lowered to use the VarArgsFrameIndex
410   setOperationAction(ISD::VASTART           , MVT::Other, Custom);
411   setOperationAction(ISD::VAEND             , MVT::Other, Expand);
412   if (Subtarget->is64Bit()) {
413     setOperationAction(ISD::VAARG           , MVT::Other, Custom);
414     setOperationAction(ISD::VACOPY          , MVT::Other, Custom);
415   } else {
416     setOperationAction(ISD::VAARG           , MVT::Other, Expand);
417     setOperationAction(ISD::VACOPY          , MVT::Other, Expand);
418   }
419
420   setOperationAction(ISD::STACKSAVE,          MVT::Other, Expand);
421   setOperationAction(ISD::STACKRESTORE,       MVT::Other, Expand);
422   if (Subtarget->is64Bit())
423     setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i64, Expand);
424   if (Subtarget->isTargetCygMing())
425     setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Custom);
426   else
427     setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Expand);
428
429   if (!UseSoftFloat && X86ScalarSSEf64) {
430     // f32 and f64 use SSE.
431     // Set up the FP register classes.
432     addRegisterClass(MVT::f32, X86::FR32RegisterClass);
433     addRegisterClass(MVT::f64, X86::FR64RegisterClass);
434
435     // Use ANDPD to simulate FABS.
436     setOperationAction(ISD::FABS , MVT::f64, Custom);
437     setOperationAction(ISD::FABS , MVT::f32, Custom);
438
439     // Use XORP to simulate FNEG.
440     setOperationAction(ISD::FNEG , MVT::f64, Custom);
441     setOperationAction(ISD::FNEG , MVT::f32, Custom);
442
443     // Use ANDPD and ORPD to simulate FCOPYSIGN.
444     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
445     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
446
447     // We don't support sin/cos/fmod
448     setOperationAction(ISD::FSIN , MVT::f64, Expand);
449     setOperationAction(ISD::FCOS , MVT::f64, Expand);
450     setOperationAction(ISD::FSIN , MVT::f32, Expand);
451     setOperationAction(ISD::FCOS , MVT::f32, Expand);
452
453     // Expand FP immediates into loads from the stack, except for the special
454     // cases we handle.
455     addLegalFPImmediate(APFloat(+0.0)); // xorpd
456     addLegalFPImmediate(APFloat(+0.0f)); // xorps
457   } else if (!UseSoftFloat && X86ScalarSSEf32) {
458     // Use SSE for f32, x87 for f64.
459     // Set up the FP register classes.
460     addRegisterClass(MVT::f32, X86::FR32RegisterClass);
461     addRegisterClass(MVT::f64, X86::RFP64RegisterClass);
462
463     // Use ANDPS to simulate FABS.
464     setOperationAction(ISD::FABS , MVT::f32, Custom);
465
466     // Use XORP to simulate FNEG.
467     setOperationAction(ISD::FNEG , MVT::f32, Custom);
468
469     setOperationAction(ISD::UNDEF,     MVT::f64, Expand);
470
471     // Use ANDPS and ORPS to simulate FCOPYSIGN.
472     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
473     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
474
475     // We don't support sin/cos/fmod
476     setOperationAction(ISD::FSIN , MVT::f32, Expand);
477     setOperationAction(ISD::FCOS , MVT::f32, Expand);
478
479     // Special cases we handle for FP constants.
480     addLegalFPImmediate(APFloat(+0.0f)); // xorps
481     addLegalFPImmediate(APFloat(+0.0)); // FLD0
482     addLegalFPImmediate(APFloat(+1.0)); // FLD1
483     addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
484     addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
485
486     if (!UnsafeFPMath) {
487       setOperationAction(ISD::FSIN           , MVT::f64  , Expand);
488       setOperationAction(ISD::FCOS           , MVT::f64  , Expand);
489     }
490   } else if (!UseSoftFloat) {
491     // f32 and f64 in x87.
492     // Set up the FP register classes.
493     addRegisterClass(MVT::f64, X86::RFP64RegisterClass);
494     addRegisterClass(MVT::f32, X86::RFP32RegisterClass);
495
496     setOperationAction(ISD::UNDEF,     MVT::f64, Expand);
497     setOperationAction(ISD::UNDEF,     MVT::f32, Expand);
498     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
499     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand);
500
501     if (!UnsafeFPMath) {
502       setOperationAction(ISD::FSIN           , MVT::f64  , Expand);
503       setOperationAction(ISD::FCOS           , MVT::f64  , Expand);
504     }
505     addLegalFPImmediate(APFloat(+0.0)); // FLD0
506     addLegalFPImmediate(APFloat(+1.0)); // FLD1
507     addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
508     addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
509     addLegalFPImmediate(APFloat(+0.0f)); // FLD0
510     addLegalFPImmediate(APFloat(+1.0f)); // FLD1
511     addLegalFPImmediate(APFloat(-0.0f)); // FLD0/FCHS
512     addLegalFPImmediate(APFloat(-1.0f)); // FLD1/FCHS
513   }
514
515   // Long double always uses X87.
516   if (!UseSoftFloat) {
517     addRegisterClass(MVT::f80, X86::RFP80RegisterClass);
518     setOperationAction(ISD::UNDEF,     MVT::f80, Expand);
519     setOperationAction(ISD::FCOPYSIGN, MVT::f80, Expand);
520     {
521       bool ignored;
522       APFloat TmpFlt(+0.0);
523       TmpFlt.convert(APFloat::x87DoubleExtended, APFloat::rmNearestTiesToEven,
524                      &ignored);
525       addLegalFPImmediate(TmpFlt);  // FLD0
526       TmpFlt.changeSign();
527       addLegalFPImmediate(TmpFlt);  // FLD0/FCHS
528       APFloat TmpFlt2(+1.0);
529       TmpFlt2.convert(APFloat::x87DoubleExtended, APFloat::rmNearestTiesToEven,
530                       &ignored);
531       addLegalFPImmediate(TmpFlt2);  // FLD1
532       TmpFlt2.changeSign();
533       addLegalFPImmediate(TmpFlt2);  // FLD1/FCHS
534     }
535
536     if (!UnsafeFPMath) {
537       setOperationAction(ISD::FSIN           , MVT::f80  , Expand);
538       setOperationAction(ISD::FCOS           , MVT::f80  , Expand);
539     }
540   }
541
542   // Always use a library call for pow.
543   setOperationAction(ISD::FPOW             , MVT::f32  , Expand);
544   setOperationAction(ISD::FPOW             , MVT::f64  , Expand);
545   setOperationAction(ISD::FPOW             , MVT::f80  , Expand);
546
547   setOperationAction(ISD::FLOG, MVT::f80, Expand);
548   setOperationAction(ISD::FLOG2, MVT::f80, Expand);
549   setOperationAction(ISD::FLOG10, MVT::f80, Expand);
550   setOperationAction(ISD::FEXP, MVT::f80, Expand);
551   setOperationAction(ISD::FEXP2, MVT::f80, Expand);
552
553   // First set operation action for all vector types to either promote
554   // (for widening) or expand (for scalarization). Then we will selectively
555   // turn on ones that can be effectively codegen'd.
556   for (unsigned VT = (unsigned)MVT::FIRST_VECTOR_VALUETYPE;
557        VT <= (unsigned)MVT::LAST_VECTOR_VALUETYPE; ++VT) {
558     setOperationAction(ISD::ADD , (MVT::SimpleValueType)VT, Expand);
559     setOperationAction(ISD::SUB , (MVT::SimpleValueType)VT, Expand);
560     setOperationAction(ISD::FADD, (MVT::SimpleValueType)VT, Expand);
561     setOperationAction(ISD::FNEG, (MVT::SimpleValueType)VT, Expand);
562     setOperationAction(ISD::FSUB, (MVT::SimpleValueType)VT, Expand);
563     setOperationAction(ISD::MUL , (MVT::SimpleValueType)VT, Expand);
564     setOperationAction(ISD::FMUL, (MVT::SimpleValueType)VT, Expand);
565     setOperationAction(ISD::SDIV, (MVT::SimpleValueType)VT, Expand);
566     setOperationAction(ISD::UDIV, (MVT::SimpleValueType)VT, Expand);
567     setOperationAction(ISD::FDIV, (MVT::SimpleValueType)VT, Expand);
568     setOperationAction(ISD::SREM, (MVT::SimpleValueType)VT, Expand);
569     setOperationAction(ISD::UREM, (MVT::SimpleValueType)VT, Expand);
570     setOperationAction(ISD::LOAD, (MVT::SimpleValueType)VT, Expand);
571     setOperationAction(ISD::VECTOR_SHUFFLE, (MVT::SimpleValueType)VT, Expand);
572     setOperationAction(ISD::EXTRACT_VECTOR_ELT,(MVT::SimpleValueType)VT,Expand);
573     setOperationAction(ISD::EXTRACT_SUBVECTOR,(MVT::SimpleValueType)VT,Expand);
574     setOperationAction(ISD::INSERT_VECTOR_ELT,(MVT::SimpleValueType)VT, Expand);
575     setOperationAction(ISD::FABS, (MVT::SimpleValueType)VT, Expand);
576     setOperationAction(ISD::FSIN, (MVT::SimpleValueType)VT, Expand);
577     setOperationAction(ISD::FCOS, (MVT::SimpleValueType)VT, Expand);
578     setOperationAction(ISD::FREM, (MVT::SimpleValueType)VT, Expand);
579     setOperationAction(ISD::FPOWI, (MVT::SimpleValueType)VT, Expand);
580     setOperationAction(ISD::FSQRT, (MVT::SimpleValueType)VT, Expand);
581     setOperationAction(ISD::FCOPYSIGN, (MVT::SimpleValueType)VT, Expand);
582     setOperationAction(ISD::SMUL_LOHI, (MVT::SimpleValueType)VT, Expand);
583     setOperationAction(ISD::UMUL_LOHI, (MVT::SimpleValueType)VT, Expand);
584     setOperationAction(ISD::SDIVREM, (MVT::SimpleValueType)VT, Expand);
585     setOperationAction(ISD::UDIVREM, (MVT::SimpleValueType)VT, Expand);
586     setOperationAction(ISD::FPOW, (MVT::SimpleValueType)VT, Expand);
587     setOperationAction(ISD::CTPOP, (MVT::SimpleValueType)VT, Expand);
588     setOperationAction(ISD::CTTZ, (MVT::SimpleValueType)VT, Expand);
589     setOperationAction(ISD::CTLZ, (MVT::SimpleValueType)VT, Expand);
590     setOperationAction(ISD::SHL, (MVT::SimpleValueType)VT, Expand);
591     setOperationAction(ISD::SRA, (MVT::SimpleValueType)VT, Expand);
592     setOperationAction(ISD::SRL, (MVT::SimpleValueType)VT, Expand);
593     setOperationAction(ISD::ROTL, (MVT::SimpleValueType)VT, Expand);
594     setOperationAction(ISD::ROTR, (MVT::SimpleValueType)VT, Expand);
595     setOperationAction(ISD::BSWAP, (MVT::SimpleValueType)VT, Expand);
596     setOperationAction(ISD::VSETCC, (MVT::SimpleValueType)VT, Expand);
597     setOperationAction(ISD::FLOG, (MVT::SimpleValueType)VT, Expand);
598     setOperationAction(ISD::FLOG2, (MVT::SimpleValueType)VT, Expand);
599     setOperationAction(ISD::FLOG10, (MVT::SimpleValueType)VT, Expand);
600     setOperationAction(ISD::FEXP, (MVT::SimpleValueType)VT, Expand);
601     setOperationAction(ISD::FEXP2, (MVT::SimpleValueType)VT, Expand);
602     setOperationAction(ISD::FP_TO_UINT, (MVT::SimpleValueType)VT, Expand);
603     setOperationAction(ISD::FP_TO_SINT, (MVT::SimpleValueType)VT, Expand);
604     setOperationAction(ISD::UINT_TO_FP, (MVT::SimpleValueType)VT, Expand);
605     setOperationAction(ISD::SINT_TO_FP, (MVT::SimpleValueType)VT, Expand);
606     setOperationAction(ISD::SIGN_EXTEND_INREG, (MVT::SimpleValueType)VT,Expand);
607     setOperationAction(ISD::TRUNCATE,  (MVT::SimpleValueType)VT, Expand);
608     setOperationAction(ISD::SIGN_EXTEND,  (MVT::SimpleValueType)VT, Expand);
609     setOperationAction(ISD::ZERO_EXTEND,  (MVT::SimpleValueType)VT, Expand);
610     setOperationAction(ISD::ANY_EXTEND,  (MVT::SimpleValueType)VT, Expand);
611     for (unsigned InnerVT = (unsigned)MVT::FIRST_VECTOR_VALUETYPE;
612          InnerVT <= (unsigned)MVT::LAST_VECTOR_VALUETYPE; ++InnerVT)
613       setTruncStoreAction((MVT::SimpleValueType)VT,
614                           (MVT::SimpleValueType)InnerVT, Expand);
615     setLoadExtAction(ISD::SEXTLOAD, (MVT::SimpleValueType)VT, Expand);
616     setLoadExtAction(ISD::ZEXTLOAD, (MVT::SimpleValueType)VT, Expand);
617     setLoadExtAction(ISD::EXTLOAD, (MVT::SimpleValueType)VT, Expand);
618   }
619
620   // FIXME: In order to prevent SSE instructions being expanded to MMX ones
621   // with -msoft-float, disable use of MMX as well.
622   if (!UseSoftFloat && !DisableMMX && Subtarget->hasMMX()) {
623     addRegisterClass(MVT::v8i8,  X86::VR64RegisterClass);
624     addRegisterClass(MVT::v4i16, X86::VR64RegisterClass);
625     addRegisterClass(MVT::v2i32, X86::VR64RegisterClass);
626     addRegisterClass(MVT::v2f32, X86::VR64RegisterClass);
627     addRegisterClass(MVT::v1i64, X86::VR64RegisterClass);
628
629     setOperationAction(ISD::ADD,                MVT::v8i8,  Legal);
630     setOperationAction(ISD::ADD,                MVT::v4i16, Legal);
631     setOperationAction(ISD::ADD,                MVT::v2i32, Legal);
632     setOperationAction(ISD::ADD,                MVT::v1i64, Legal);
633
634     setOperationAction(ISD::SUB,                MVT::v8i8,  Legal);
635     setOperationAction(ISD::SUB,                MVT::v4i16, Legal);
636     setOperationAction(ISD::SUB,                MVT::v2i32, Legal);
637     setOperationAction(ISD::SUB,                MVT::v1i64, Legal);
638
639     setOperationAction(ISD::MULHS,              MVT::v4i16, Legal);
640     setOperationAction(ISD::MUL,                MVT::v4i16, Legal);
641
642     setOperationAction(ISD::AND,                MVT::v8i8,  Promote);
643     AddPromotedToType (ISD::AND,                MVT::v8i8,  MVT::v1i64);
644     setOperationAction(ISD::AND,                MVT::v4i16, Promote);
645     AddPromotedToType (ISD::AND,                MVT::v4i16, MVT::v1i64);
646     setOperationAction(ISD::AND,                MVT::v2i32, Promote);
647     AddPromotedToType (ISD::AND,                MVT::v2i32, MVT::v1i64);
648     setOperationAction(ISD::AND,                MVT::v1i64, Legal);
649
650     setOperationAction(ISD::OR,                 MVT::v8i8,  Promote);
651     AddPromotedToType (ISD::OR,                 MVT::v8i8,  MVT::v1i64);
652     setOperationAction(ISD::OR,                 MVT::v4i16, Promote);
653     AddPromotedToType (ISD::OR,                 MVT::v4i16, MVT::v1i64);
654     setOperationAction(ISD::OR,                 MVT::v2i32, Promote);
655     AddPromotedToType (ISD::OR,                 MVT::v2i32, MVT::v1i64);
656     setOperationAction(ISD::OR,                 MVT::v1i64, Legal);
657
658     setOperationAction(ISD::XOR,                MVT::v8i8,  Promote);
659     AddPromotedToType (ISD::XOR,                MVT::v8i8,  MVT::v1i64);
660     setOperationAction(ISD::XOR,                MVT::v4i16, Promote);
661     AddPromotedToType (ISD::XOR,                MVT::v4i16, MVT::v1i64);
662     setOperationAction(ISD::XOR,                MVT::v2i32, Promote);
663     AddPromotedToType (ISD::XOR,                MVT::v2i32, MVT::v1i64);
664     setOperationAction(ISD::XOR,                MVT::v1i64, Legal);
665
666     setOperationAction(ISD::LOAD,               MVT::v8i8,  Promote);
667     AddPromotedToType (ISD::LOAD,               MVT::v8i8,  MVT::v1i64);
668     setOperationAction(ISD::LOAD,               MVT::v4i16, Promote);
669     AddPromotedToType (ISD::LOAD,               MVT::v4i16, MVT::v1i64);
670     setOperationAction(ISD::LOAD,               MVT::v2i32, Promote);
671     AddPromotedToType (ISD::LOAD,               MVT::v2i32, MVT::v1i64);
672     setOperationAction(ISD::LOAD,               MVT::v2f32, Promote);
673     AddPromotedToType (ISD::LOAD,               MVT::v2f32, MVT::v1i64);
674     setOperationAction(ISD::LOAD,               MVT::v1i64, Legal);
675
676     setOperationAction(ISD::BUILD_VECTOR,       MVT::v8i8,  Custom);
677     setOperationAction(ISD::BUILD_VECTOR,       MVT::v4i16, Custom);
678     setOperationAction(ISD::BUILD_VECTOR,       MVT::v2i32, Custom);
679     setOperationAction(ISD::BUILD_VECTOR,       MVT::v2f32, Custom);
680     setOperationAction(ISD::BUILD_VECTOR,       MVT::v1i64, Custom);
681
682     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v8i8,  Custom);
683     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v4i16, Custom);
684     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v2i32, Custom);
685     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v1i64, Custom);
686
687     setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v2f32, Custom);
688     setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v8i8,  Custom);
689     setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v4i16, Custom);
690     setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v1i64, Custom);
691
692     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4i16, Custom);
693
694     setOperationAction(ISD::SELECT,             MVT::v8i8, Promote);
695     setOperationAction(ISD::SELECT,             MVT::v4i16, Promote);
696     setOperationAction(ISD::SELECT,             MVT::v2i32, Promote);
697     setOperationAction(ISD::SELECT,             MVT::v1i64, Custom);
698     setOperationAction(ISD::VSETCC,             MVT::v8i8, Custom);
699     setOperationAction(ISD::VSETCC,             MVT::v4i16, Custom);
700     setOperationAction(ISD::VSETCC,             MVT::v2i32, Custom);
701   }
702
703   if (!UseSoftFloat && Subtarget->hasSSE1()) {
704     addRegisterClass(MVT::v4f32, X86::VR128RegisterClass);
705
706     setOperationAction(ISD::FADD,               MVT::v4f32, Legal);
707     setOperationAction(ISD::FSUB,               MVT::v4f32, Legal);
708     setOperationAction(ISD::FMUL,               MVT::v4f32, Legal);
709     setOperationAction(ISD::FDIV,               MVT::v4f32, Legal);
710     setOperationAction(ISD::FSQRT,              MVT::v4f32, Legal);
711     setOperationAction(ISD::FNEG,               MVT::v4f32, Custom);
712     setOperationAction(ISD::LOAD,               MVT::v4f32, Legal);
713     setOperationAction(ISD::BUILD_VECTOR,       MVT::v4f32, Custom);
714     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v4f32, Custom);
715     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
716     setOperationAction(ISD::SELECT,             MVT::v4f32, Custom);
717     setOperationAction(ISD::VSETCC,             MVT::v4f32, Custom);
718   }
719
720   if (!UseSoftFloat && Subtarget->hasSSE2()) {
721     addRegisterClass(MVT::v2f64, X86::VR128RegisterClass);
722
723     // FIXME: Unfortunately -soft-float and -no-implicit-float means XMM
724     // registers cannot be used even for integer operations.
725     addRegisterClass(MVT::v16i8, X86::VR128RegisterClass);
726     addRegisterClass(MVT::v8i16, X86::VR128RegisterClass);
727     addRegisterClass(MVT::v4i32, X86::VR128RegisterClass);
728     addRegisterClass(MVT::v2i64, X86::VR128RegisterClass);
729
730     setOperationAction(ISD::ADD,                MVT::v16i8, Legal);
731     setOperationAction(ISD::ADD,                MVT::v8i16, Legal);
732     setOperationAction(ISD::ADD,                MVT::v4i32, Legal);
733     setOperationAction(ISD::ADD,                MVT::v2i64, Legal);
734     setOperationAction(ISD::MUL,                MVT::v2i64, Custom);
735     setOperationAction(ISD::SUB,                MVT::v16i8, Legal);
736     setOperationAction(ISD::SUB,                MVT::v8i16, Legal);
737     setOperationAction(ISD::SUB,                MVT::v4i32, Legal);
738     setOperationAction(ISD::SUB,                MVT::v2i64, Legal);
739     setOperationAction(ISD::MUL,                MVT::v8i16, Legal);
740     setOperationAction(ISD::FADD,               MVT::v2f64, Legal);
741     setOperationAction(ISD::FSUB,               MVT::v2f64, Legal);
742     setOperationAction(ISD::FMUL,               MVT::v2f64, Legal);
743     setOperationAction(ISD::FDIV,               MVT::v2f64, Legal);
744     setOperationAction(ISD::FSQRT,              MVT::v2f64, Legal);
745     setOperationAction(ISD::FNEG,               MVT::v2f64, Custom);
746
747     setOperationAction(ISD::VSETCC,             MVT::v2f64, Custom);
748     setOperationAction(ISD::VSETCC,             MVT::v16i8, Custom);
749     setOperationAction(ISD::VSETCC,             MVT::v8i16, Custom);
750     setOperationAction(ISD::VSETCC,             MVT::v4i32, Custom);
751
752     setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v16i8, Custom);
753     setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v8i16, Custom);
754     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v8i16, Custom);
755     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4i32, Custom);
756     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4f32, Custom);
757
758     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v2f64, Custom);
759     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v2i64, Custom);
760     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v16i8, Custom);
761     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v8i16, Custom);
762     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v4i32, Custom);
763
764     // Custom lower build_vector, vector_shuffle, and extract_vector_elt.
765     for (unsigned i = (unsigned)MVT::v16i8; i != (unsigned)MVT::v2i64; ++i) {
766       EVT VT = (MVT::SimpleValueType)i;
767       // Do not attempt to custom lower non-power-of-2 vectors
768       if (!isPowerOf2_32(VT.getVectorNumElements()))
769         continue;
770       // Do not attempt to custom lower non-128-bit vectors
771       if (!VT.is128BitVector())
772         continue;
773       setOperationAction(ISD::BUILD_VECTOR,
774                          VT.getSimpleVT().SimpleTy, Custom);
775       setOperationAction(ISD::VECTOR_SHUFFLE,
776                          VT.getSimpleVT().SimpleTy, Custom);
777       setOperationAction(ISD::EXTRACT_VECTOR_ELT,
778                          VT.getSimpleVT().SimpleTy, Custom);
779     }
780
781     setOperationAction(ISD::BUILD_VECTOR,       MVT::v2f64, Custom);
782     setOperationAction(ISD::BUILD_VECTOR,       MVT::v2i64, Custom);
783     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v2f64, Custom);
784     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v2i64, Custom);
785     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2f64, Custom);
786     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Custom);
787
788     if (Subtarget->is64Bit()) {
789       setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2i64, Custom);
790       setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
791     }
792
793     // Promote v16i8, v8i16, v4i32 load, select, and, or, xor to v2i64.
794     for (unsigned i = (unsigned)MVT::v16i8; i != (unsigned)MVT::v2i64; i++) {
795       MVT::SimpleValueType SVT = (MVT::SimpleValueType)i;
796       EVT VT = SVT;
797
798       // Do not attempt to promote non-128-bit vectors
799       if (!VT.is128BitVector()) {
800         continue;
801       }
802       setOperationAction(ISD::AND,    SVT, Promote);
803       AddPromotedToType (ISD::AND,    SVT, MVT::v2i64);
804       setOperationAction(ISD::OR,     SVT, Promote);
805       AddPromotedToType (ISD::OR,     SVT, MVT::v2i64);
806       setOperationAction(ISD::XOR,    SVT, Promote);
807       AddPromotedToType (ISD::XOR,    SVT, MVT::v2i64);
808       setOperationAction(ISD::LOAD,   SVT, Promote);
809       AddPromotedToType (ISD::LOAD,   SVT, MVT::v2i64);
810       setOperationAction(ISD::SELECT, SVT, Promote);
811       AddPromotedToType (ISD::SELECT, SVT, MVT::v2i64);
812     }
813
814     setTruncStoreAction(MVT::f64, MVT::f32, Expand);
815
816     // Custom lower v2i64 and v2f64 selects.
817     setOperationAction(ISD::LOAD,               MVT::v2f64, Legal);
818     setOperationAction(ISD::LOAD,               MVT::v2i64, Legal);
819     setOperationAction(ISD::SELECT,             MVT::v2f64, Custom);
820     setOperationAction(ISD::SELECT,             MVT::v2i64, Custom);
821
822     setOperationAction(ISD::FP_TO_SINT,         MVT::v4i32, Legal);
823     setOperationAction(ISD::SINT_TO_FP,         MVT::v4i32, Legal);
824     if (!DisableMMX && Subtarget->hasMMX()) {
825       setOperationAction(ISD::FP_TO_SINT,         MVT::v2i32, Custom);
826       setOperationAction(ISD::SINT_TO_FP,         MVT::v2i32, Custom);
827     }
828   }
829
830   if (Subtarget->hasSSE41()) {
831     // FIXME: Do we need to handle scalar-to-vector here?
832     setOperationAction(ISD::MUL,                MVT::v4i32, Legal);
833
834     // i8 and i16 vectors are custom , because the source register and source
835     // source memory operand types are not the same width.  f32 vectors are
836     // custom since the immediate controlling the insert encodes additional
837     // information.
838     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v16i8, Custom);
839     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v8i16, Custom);
840     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4i32, Custom);
841     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4f32, Custom);
842
843     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i8, Custom);
844     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i16, Custom);
845     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i32, Custom);
846     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
847
848     if (Subtarget->is64Bit()) {
849       setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2i64, Legal);
850       setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Legal);
851     }
852   }
853
854   if (Subtarget->hasSSE42()) {
855     setOperationAction(ISD::VSETCC,             MVT::v2i64, Custom);
856   }
857
858   if (!UseSoftFloat && Subtarget->hasAVX()) {
859     addRegisterClass(MVT::v8f32, X86::VR256RegisterClass);
860     addRegisterClass(MVT::v4f64, X86::VR256RegisterClass);
861     addRegisterClass(MVT::v8i32, X86::VR256RegisterClass);
862     addRegisterClass(MVT::v4i64, X86::VR256RegisterClass);
863
864     setOperationAction(ISD::LOAD,               MVT::v8f32, Legal);
865     setOperationAction(ISD::LOAD,               MVT::v8i32, Legal);
866     setOperationAction(ISD::LOAD,               MVT::v4f64, Legal);
867     setOperationAction(ISD::LOAD,               MVT::v4i64, Legal);
868     setOperationAction(ISD::FADD,               MVT::v8f32, Legal);
869     setOperationAction(ISD::FSUB,               MVT::v8f32, Legal);
870     setOperationAction(ISD::FMUL,               MVT::v8f32, Legal);
871     setOperationAction(ISD::FDIV,               MVT::v8f32, Legal);
872     setOperationAction(ISD::FSQRT,              MVT::v8f32, Legal);
873     setOperationAction(ISD::FNEG,               MVT::v8f32, Custom);
874     //setOperationAction(ISD::BUILD_VECTOR,       MVT::v8f32, Custom);
875     //setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v8f32, Custom);
876     //setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8f32, Custom);
877     //setOperationAction(ISD::SELECT,             MVT::v8f32, Custom);
878     //setOperationAction(ISD::VSETCC,             MVT::v8f32, Custom);
879
880     // Operations to consider commented out -v16i16 v32i8
881     //setOperationAction(ISD::ADD,                MVT::v16i16, Legal);
882     setOperationAction(ISD::ADD,                MVT::v8i32, Custom);
883     setOperationAction(ISD::ADD,                MVT::v4i64, Custom);
884     //setOperationAction(ISD::SUB,                MVT::v32i8, Legal);
885     //setOperationAction(ISD::SUB,                MVT::v16i16, Legal);
886     setOperationAction(ISD::SUB,                MVT::v8i32, Custom);
887     setOperationAction(ISD::SUB,                MVT::v4i64, Custom);
888     //setOperationAction(ISD::MUL,                MVT::v16i16, Legal);
889     setOperationAction(ISD::FADD,               MVT::v4f64, Legal);
890     setOperationAction(ISD::FSUB,               MVT::v4f64, Legal);
891     setOperationAction(ISD::FMUL,               MVT::v4f64, Legal);
892     setOperationAction(ISD::FDIV,               MVT::v4f64, Legal);
893     setOperationAction(ISD::FSQRT,              MVT::v4f64, Legal);
894     setOperationAction(ISD::FNEG,               MVT::v4f64, Custom);
895
896     setOperationAction(ISD::VSETCC,             MVT::v4f64, Custom);
897     // setOperationAction(ISD::VSETCC,             MVT::v32i8, Custom);
898     // setOperationAction(ISD::VSETCC,             MVT::v16i16, Custom);
899     setOperationAction(ISD::VSETCC,             MVT::v8i32, Custom);
900
901     // setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v32i8, Custom);
902     // setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v16i16, Custom);
903     // setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v16i16, Custom);
904     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v8i32, Custom);
905     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v8f32, Custom);
906
907     setOperationAction(ISD::BUILD_VECTOR,       MVT::v4f64, Custom);
908     setOperationAction(ISD::BUILD_VECTOR,       MVT::v4i64, Custom);
909     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v4f64, Custom);
910     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v4i64, Custom);
911     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4f64, Custom);
912     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f64, Custom);
913
914 #if 0
915     // Not sure we want to do this since there are no 256-bit integer
916     // operations in AVX
917
918     // Custom lower build_vector, vector_shuffle, and extract_vector_elt.
919     // This includes 256-bit vectors
920     for (unsigned i = (unsigned)MVT::v16i8; i != (unsigned)MVT::v4i64; ++i) {
921       EVT VT = (MVT::SimpleValueType)i;
922
923       // Do not attempt to custom lower non-power-of-2 vectors
924       if (!isPowerOf2_32(VT.getVectorNumElements()))
925         continue;
926
927       setOperationAction(ISD::BUILD_VECTOR,       VT, Custom);
928       setOperationAction(ISD::VECTOR_SHUFFLE,     VT, Custom);
929       setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
930     }
931
932     if (Subtarget->is64Bit()) {
933       setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4i64, Custom);
934       setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i64, Custom);
935     }
936 #endif
937
938 #if 0
939     // Not sure we want to do this since there are no 256-bit integer
940     // operations in AVX
941
942     // Promote v32i8, v16i16, v8i32 load, select, and, or, xor to v4i64.
943     // Including 256-bit vectors
944     for (unsigned i = (unsigned)MVT::v16i8; i != (unsigned)MVT::v4i64; i++) {
945       EVT VT = (MVT::SimpleValueType)i;
946
947       if (!VT.is256BitVector()) {
948         continue;
949       }
950       setOperationAction(ISD::AND,    VT, Promote);
951       AddPromotedToType (ISD::AND,    VT, MVT::v4i64);
952       setOperationAction(ISD::OR,     VT, Promote);
953       AddPromotedToType (ISD::OR,     VT, MVT::v4i64);
954       setOperationAction(ISD::XOR,    VT, Promote);
955       AddPromotedToType (ISD::XOR,    VT, MVT::v4i64);
956       setOperationAction(ISD::LOAD,   VT, Promote);
957       AddPromotedToType (ISD::LOAD,   VT, MVT::v4i64);
958       setOperationAction(ISD::SELECT, VT, Promote);
959       AddPromotedToType (ISD::SELECT, VT, MVT::v4i64);
960     }
961
962     setTruncStoreAction(MVT::f64, MVT::f32, Expand);
963 #endif
964   }
965
966   // We want to custom lower some of our intrinsics.
967   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
968
969   // Add/Sub/Mul with overflow operations are custom lowered.
970   setOperationAction(ISD::SADDO, MVT::i32, Custom);
971   setOperationAction(ISD::SADDO, MVT::i64, Custom);
972   setOperationAction(ISD::UADDO, MVT::i32, Custom);
973   setOperationAction(ISD::UADDO, MVT::i64, Custom);
974   setOperationAction(ISD::SSUBO, MVT::i32, Custom);
975   setOperationAction(ISD::SSUBO, MVT::i64, Custom);
976   setOperationAction(ISD::USUBO, MVT::i32, Custom);
977   setOperationAction(ISD::USUBO, MVT::i64, Custom);
978   setOperationAction(ISD::SMULO, MVT::i32, Custom);
979   setOperationAction(ISD::SMULO, MVT::i64, Custom);
980
981   if (!Subtarget->is64Bit()) {
982     // These libcalls are not available in 32-bit.
983     setLibcallName(RTLIB::SHL_I128, 0);
984     setLibcallName(RTLIB::SRL_I128, 0);
985     setLibcallName(RTLIB::SRA_I128, 0);
986   }
987
988   // We have target-specific dag combine patterns for the following nodes:
989   setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
990   setTargetDAGCombine(ISD::BUILD_VECTOR);
991   setTargetDAGCombine(ISD::SELECT);
992   setTargetDAGCombine(ISD::SHL);
993   setTargetDAGCombine(ISD::SRA);
994   setTargetDAGCombine(ISD::SRL);
995   setTargetDAGCombine(ISD::OR);
996   setTargetDAGCombine(ISD::STORE);
997   setTargetDAGCombine(ISD::MEMBARRIER);
998   setTargetDAGCombine(ISD::ZERO_EXTEND);
999   if (Subtarget->is64Bit())
1000     setTargetDAGCombine(ISD::MUL);
1001
1002   computeRegisterProperties();
1003
1004   // Divide and reminder operations have no vector equivalent and can
1005   // trap. Do a custom widening for these operations in which we never
1006   // generate more divides/remainder than the original vector width.
1007   for (unsigned VT = (unsigned)MVT::FIRST_VECTOR_VALUETYPE;
1008        VT <= (unsigned)MVT::LAST_VECTOR_VALUETYPE; ++VT) {
1009     if (!isTypeLegal((MVT::SimpleValueType)VT)) {
1010       setOperationAction(ISD::SDIV, (MVT::SimpleValueType) VT, Custom);
1011       setOperationAction(ISD::UDIV, (MVT::SimpleValueType) VT, Custom);
1012       setOperationAction(ISD::SREM, (MVT::SimpleValueType) VT, Custom);
1013       setOperationAction(ISD::UREM, (MVT::SimpleValueType) VT, Custom);
1014     }
1015   }
1016
1017   // FIXME: These should be based on subtarget info. Plus, the values should
1018   // be smaller when we are in optimizing for size mode.
1019   maxStoresPerMemset = 16; // For @llvm.memset -> sequence of stores
1020   maxStoresPerMemcpy = 16; // For @llvm.memcpy -> sequence of stores
1021   maxStoresPerMemmove = 3; // For @llvm.memmove -> sequence of stores
1022   setPrefLoopAlignment(16);
1023   benefitFromCodePlacementOpt = true;
1024 }
1025
1026
1027 MVT::SimpleValueType X86TargetLowering::getSetCCResultType(EVT VT) const {
1028   return MVT::i8;
1029 }
1030
1031
1032 /// getMaxByValAlign - Helper for getByValTypeAlignment to determine
1033 /// the desired ByVal argument alignment.
1034 static void getMaxByValAlign(const Type *Ty, unsigned &MaxAlign) {
1035   if (MaxAlign == 16)
1036     return;
1037   if (const VectorType *VTy = dyn_cast<VectorType>(Ty)) {
1038     if (VTy->getBitWidth() == 128)
1039       MaxAlign = 16;
1040   } else if (const ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
1041     unsigned EltAlign = 0;
1042     getMaxByValAlign(ATy->getElementType(), EltAlign);
1043     if (EltAlign > MaxAlign)
1044       MaxAlign = EltAlign;
1045   } else if (const StructType *STy = dyn_cast<StructType>(Ty)) {
1046     for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
1047       unsigned EltAlign = 0;
1048       getMaxByValAlign(STy->getElementType(i), EltAlign);
1049       if (EltAlign > MaxAlign)
1050         MaxAlign = EltAlign;
1051       if (MaxAlign == 16)
1052         break;
1053     }
1054   }
1055   return;
1056 }
1057
1058 /// getByValTypeAlignment - Return the desired alignment for ByVal aggregate
1059 /// function arguments in the caller parameter area. For X86, aggregates
1060 /// that contain SSE vectors are placed at 16-byte boundaries while the rest
1061 /// are at 4-byte boundaries.
1062 unsigned X86TargetLowering::getByValTypeAlignment(const Type *Ty) const {
1063   if (Subtarget->is64Bit()) {
1064     // Max of 8 and alignment of type.
1065     unsigned TyAlign = TD->getABITypeAlignment(Ty);
1066     if (TyAlign > 8)
1067       return TyAlign;
1068     return 8;
1069   }
1070
1071   unsigned Align = 4;
1072   if (Subtarget->hasSSE1())
1073     getMaxByValAlign(Ty, Align);
1074   return Align;
1075 }
1076
1077 /// getOptimalMemOpType - Returns the target specific optimal type for load
1078 /// and store operations as a result of memset, memcpy, and memmove
1079 /// lowering. It returns MVT::iAny if SelectionDAG should be responsible for
1080 /// determining it.
1081 EVT
1082 X86TargetLowering::getOptimalMemOpType(uint64_t Size, unsigned Align,
1083                                        bool isSrcConst, bool isSrcStr,
1084                                        SelectionDAG &DAG) const {
1085   // FIXME: This turns off use of xmm stores for memset/memcpy on targets like
1086   // linux.  This is because the stack realignment code can't handle certain
1087   // cases like PR2962.  This should be removed when PR2962 is fixed.
1088   const Function *F = DAG.getMachineFunction().getFunction();
1089   bool NoImplicitFloatOps = F->hasFnAttr(Attribute::NoImplicitFloat);
1090   if (!NoImplicitFloatOps && Subtarget->getStackAlignment() >= 16) {
1091     if ((isSrcConst || isSrcStr) && Subtarget->hasSSE2() && Size >= 16)
1092       return MVT::v4i32;
1093     if ((isSrcConst || isSrcStr) && Subtarget->hasSSE1() && Size >= 16)
1094       return MVT::v4f32;
1095   }
1096   if (Subtarget->is64Bit() && Size >= 8)
1097     return MVT::i64;
1098   return MVT::i32;
1099 }
1100
1101 /// getJumpTableEncoding - Return the entry encoding for a jump table in the
1102 /// current function.  The returned value is a member of the
1103 /// MachineJumpTableInfo::JTEntryKind enum.
1104 unsigned X86TargetLowering::getJumpTableEncoding() const {
1105   // In GOT pic mode, each entry in the jump table is emitted as a @GOTOFF
1106   // symbol.
1107   if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1108       Subtarget->isPICStyleGOT())
1109     return MachineJumpTableInfo::EK_Custom32;
1110   
1111   // Otherwise, use the normal jump table encoding heuristics.
1112   return TargetLowering::getJumpTableEncoding();
1113 }
1114
1115 /// getPICBaseSymbol - Return the X86-32 PIC base.
1116 MCSymbol *
1117 X86TargetLowering::getPICBaseSymbol(const MachineFunction *MF,
1118                                     MCContext &Ctx) const {
1119   const MCAsmInfo &MAI = *getTargetMachine().getMCAsmInfo();
1120   return Ctx.GetOrCreateSymbol(Twine(MAI.getPrivateGlobalPrefix())+
1121                                Twine(MF->getFunctionNumber())+"$pb");
1122 }
1123
1124
1125 const MCExpr *
1126 X86TargetLowering::LowerCustomJumpTableEntry(const MachineJumpTableInfo *MJTI,
1127                                              const MachineBasicBlock *MBB,
1128                                              unsigned uid,MCContext &Ctx) const{
1129   assert(getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1130          Subtarget->isPICStyleGOT());
1131   // In 32-bit ELF systems, our jump table entries are formed with @GOTOFF
1132   // entries.
1133
1134   // FIXME: @GOTOFF should be a property of MCSymbolRefExpr not in the MCSymbol.
1135   std::string Name = MBB->getSymbol(Ctx)->getName() + "@GOTOFF";
1136   return MCSymbolRefExpr::Create(Ctx.GetOrCreateSymbol(StringRef(Name)), Ctx);
1137 }
1138
1139 /// getPICJumpTableRelocaBase - Returns relocation base for the given PIC
1140 /// jumptable.
1141 SDValue X86TargetLowering::getPICJumpTableRelocBase(SDValue Table,
1142                                                     SelectionDAG &DAG) const {
1143   if (!Subtarget->is64Bit())
1144     // This doesn't have DebugLoc associated with it, but is not really the
1145     // same as a Register.
1146     return DAG.getNode(X86ISD::GlobalBaseReg, DebugLoc::getUnknownLoc(),
1147                        getPointerTy());
1148   return Table;
1149 }
1150
1151 /// getPICJumpTableRelocBaseExpr - This returns the relocation base for the
1152 /// given PIC jumptable, the same as getPICJumpTableRelocBase, but as an
1153 /// MCExpr.
1154 const MCExpr *X86TargetLowering::
1155 getPICJumpTableRelocBaseExpr(const MachineFunction *MF, unsigned JTI,
1156                              MCContext &Ctx) const {
1157   // X86-64 uses RIP relative addressing based on the jump table label.
1158   if (Subtarget->isPICStyleRIPRel())
1159     return TargetLowering::getPICJumpTableRelocBaseExpr(MF, JTI, Ctx);
1160
1161   // Otherwise, the reference is relative to the PIC base.
1162   return MCSymbolRefExpr::Create(getPICBaseSymbol(MF, Ctx), Ctx);
1163 }
1164
1165 /// getFunctionAlignment - Return the Log2 alignment of this function.
1166 unsigned X86TargetLowering::getFunctionAlignment(const Function *F) const {
1167   return F->hasFnAttr(Attribute::OptimizeForSize) ? 0 : 4;
1168 }
1169
1170 //===----------------------------------------------------------------------===//
1171 //               Return Value Calling Convention Implementation
1172 //===----------------------------------------------------------------------===//
1173
1174 #include "X86GenCallingConv.inc"
1175
1176 bool 
1177 X86TargetLowering::CanLowerReturn(CallingConv::ID CallConv, bool isVarArg,
1178                         const SmallVectorImpl<EVT> &OutTys,
1179                         const SmallVectorImpl<ISD::ArgFlagsTy> &ArgsFlags,
1180                         SelectionDAG &DAG) {
1181   SmallVector<CCValAssign, 16> RVLocs;
1182   CCState CCInfo(CallConv, isVarArg, getTargetMachine(),
1183                  RVLocs, *DAG.getContext());
1184   return CCInfo.CheckReturn(OutTys, ArgsFlags, RetCC_X86);
1185 }
1186
1187 SDValue
1188 X86TargetLowering::LowerReturn(SDValue Chain,
1189                                CallingConv::ID CallConv, bool isVarArg,
1190                                const SmallVectorImpl<ISD::OutputArg> &Outs,
1191                                DebugLoc dl, SelectionDAG &DAG) {
1192
1193   SmallVector<CCValAssign, 16> RVLocs;
1194   CCState CCInfo(CallConv, isVarArg, getTargetMachine(),
1195                  RVLocs, *DAG.getContext());
1196   CCInfo.AnalyzeReturn(Outs, RetCC_X86);
1197
1198   // If this is the first return lowered for this function, add the regs to the
1199   // liveout set for the function.
1200   if (DAG.getMachineFunction().getRegInfo().liveout_empty()) {
1201     for (unsigned i = 0; i != RVLocs.size(); ++i)
1202       if (RVLocs[i].isRegLoc())
1203         DAG.getMachineFunction().getRegInfo().addLiveOut(RVLocs[i].getLocReg());
1204   }
1205
1206   SDValue Flag;
1207
1208   SmallVector<SDValue, 6> RetOps;
1209   RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
1210   // Operand #1 = Bytes To Pop
1211   RetOps.push_back(DAG.getTargetConstant(getBytesToPopOnReturn(), MVT::i16));
1212
1213   // Copy the result values into the output registers.
1214   for (unsigned i = 0; i != RVLocs.size(); ++i) {
1215     CCValAssign &VA = RVLocs[i];
1216     assert(VA.isRegLoc() && "Can only return in registers!");
1217     SDValue ValToCopy = Outs[i].Val;
1218
1219     // Returns in ST0/ST1 are handled specially: these are pushed as operands to
1220     // the RET instruction and handled by the FP Stackifier.
1221     if (VA.getLocReg() == X86::ST0 ||
1222         VA.getLocReg() == X86::ST1) {
1223       // If this is a copy from an xmm register to ST(0), use an FPExtend to
1224       // change the value to the FP stack register class.
1225       if (isScalarFPTypeInSSEReg(VA.getValVT()))
1226         ValToCopy = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f80, ValToCopy);
1227       RetOps.push_back(ValToCopy);
1228       // Don't emit a copytoreg.
1229       continue;
1230     }
1231
1232     // 64-bit vector (MMX) values are returned in XMM0 / XMM1 except for v1i64
1233     // which is returned in RAX / RDX.
1234     if (Subtarget->is64Bit()) {
1235       EVT ValVT = ValToCopy.getValueType();
1236       if (ValVT.isVector() && ValVT.getSizeInBits() == 64) {
1237         ValToCopy = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::i64, ValToCopy);
1238         if (VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1)
1239           ValToCopy = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64, ValToCopy);
1240       }
1241     }
1242
1243     Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), ValToCopy, Flag);
1244     Flag = Chain.getValue(1);
1245   }
1246
1247   // The x86-64 ABI for returning structs by value requires that we copy
1248   // the sret argument into %rax for the return. We saved the argument into
1249   // a virtual register in the entry block, so now we copy the value out
1250   // and into %rax.
1251   if (Subtarget->is64Bit() &&
1252       DAG.getMachineFunction().getFunction()->hasStructRetAttr()) {
1253     MachineFunction &MF = DAG.getMachineFunction();
1254     X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1255     unsigned Reg = FuncInfo->getSRetReturnReg();
1256     if (!Reg) {
1257       Reg = MF.getRegInfo().createVirtualRegister(getRegClassFor(MVT::i64));
1258       FuncInfo->setSRetReturnReg(Reg);
1259     }
1260     SDValue Val = DAG.getCopyFromReg(Chain, dl, Reg, getPointerTy());
1261
1262     Chain = DAG.getCopyToReg(Chain, dl, X86::RAX, Val, Flag);
1263     Flag = Chain.getValue(1);
1264
1265     // RAX now acts like a return value.
1266     MF.getRegInfo().addLiveOut(X86::RAX);
1267   }
1268
1269   RetOps[0] = Chain;  // Update chain.
1270
1271   // Add the flag if we have it.
1272   if (Flag.getNode())
1273     RetOps.push_back(Flag);
1274
1275   return DAG.getNode(X86ISD::RET_FLAG, dl,
1276                      MVT::Other, &RetOps[0], RetOps.size());
1277 }
1278
1279 /// LowerCallResult - Lower the result values of a call into the
1280 /// appropriate copies out of appropriate physical registers.
1281 ///
1282 SDValue
1283 X86TargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
1284                                    CallingConv::ID CallConv, bool isVarArg,
1285                                    const SmallVectorImpl<ISD::InputArg> &Ins,
1286                                    DebugLoc dl, SelectionDAG &DAG,
1287                                    SmallVectorImpl<SDValue> &InVals) {
1288
1289   // Assign locations to each value returned by this call.
1290   SmallVector<CCValAssign, 16> RVLocs;
1291   bool Is64Bit = Subtarget->is64Bit();
1292   CCState CCInfo(CallConv, isVarArg, getTargetMachine(),
1293                  RVLocs, *DAG.getContext());
1294   CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
1295
1296   // Copy all of the result registers out of their specified physreg.
1297   for (unsigned i = 0; i != RVLocs.size(); ++i) {
1298     CCValAssign &VA = RVLocs[i];
1299     EVT CopyVT = VA.getValVT();
1300
1301     // If this is x86-64, and we disabled SSE, we can't return FP values
1302     if ((CopyVT == MVT::f32 || CopyVT == MVT::f64) &&
1303         ((Is64Bit || Ins[i].Flags.isInReg()) && !Subtarget->hasSSE1())) {
1304       llvm_report_error("SSE register return with SSE disabled");
1305     }
1306
1307     // If this is a call to a function that returns an fp value on the floating
1308     // point stack, but where we prefer to use the value in xmm registers, copy
1309     // it out as F80 and use a truncate to move it from fp stack reg to xmm reg.
1310     if ((VA.getLocReg() == X86::ST0 ||
1311          VA.getLocReg() == X86::ST1) &&
1312         isScalarFPTypeInSSEReg(VA.getValVT())) {
1313       CopyVT = MVT::f80;
1314     }
1315
1316     SDValue Val;
1317     if (Is64Bit && CopyVT.isVector() && CopyVT.getSizeInBits() == 64) {
1318       // For x86-64, MMX values are returned in XMM0 / XMM1 except for v1i64.
1319       if (VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) {
1320         Chain = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(),
1321                                    MVT::v2i64, InFlag).getValue(1);
1322         Val = Chain.getValue(0);
1323         Val = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i64,
1324                           Val, DAG.getConstant(0, MVT::i64));
1325       } else {
1326         Chain = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(),
1327                                    MVT::i64, InFlag).getValue(1);
1328         Val = Chain.getValue(0);
1329       }
1330       Val = DAG.getNode(ISD::BIT_CONVERT, dl, CopyVT, Val);
1331     } else {
1332       Chain = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(),
1333                                  CopyVT, InFlag).getValue(1);
1334       Val = Chain.getValue(0);
1335     }
1336     InFlag = Chain.getValue(2);
1337
1338     if (CopyVT != VA.getValVT()) {
1339       // Round the F80 the right size, which also moves to the appropriate xmm
1340       // register.
1341       Val = DAG.getNode(ISD::FP_ROUND, dl, VA.getValVT(), Val,
1342                         // This truncation won't change the value.
1343                         DAG.getIntPtrConstant(1));
1344     }
1345
1346     InVals.push_back(Val);
1347   }
1348
1349   return Chain;
1350 }
1351
1352
1353 //===----------------------------------------------------------------------===//
1354 //                C & StdCall & Fast Calling Convention implementation
1355 //===----------------------------------------------------------------------===//
1356 //  StdCall calling convention seems to be standard for many Windows' API
1357 //  routines and around. It differs from C calling convention just a little:
1358 //  callee should clean up the stack, not caller. Symbols should be also
1359 //  decorated in some fancy way :) It doesn't support any vector arguments.
1360 //  For info on fast calling convention see Fast Calling Convention (tail call)
1361 //  implementation LowerX86_32FastCCCallTo.
1362
1363 /// CallIsStructReturn - Determines whether a call uses struct return
1364 /// semantics.
1365 static bool CallIsStructReturn(const SmallVectorImpl<ISD::OutputArg> &Outs) {
1366   if (Outs.empty())
1367     return false;
1368
1369   return Outs[0].Flags.isSRet();
1370 }
1371
1372 /// ArgsAreStructReturn - Determines whether a function uses struct
1373 /// return semantics.
1374 static bool
1375 ArgsAreStructReturn(const SmallVectorImpl<ISD::InputArg> &Ins) {
1376   if (Ins.empty())
1377     return false;
1378
1379   return Ins[0].Flags.isSRet();
1380 }
1381
1382 /// IsCalleePop - Determines whether the callee is required to pop its
1383 /// own arguments. Callee pop is necessary to support tail calls.
1384 bool X86TargetLowering::IsCalleePop(bool IsVarArg, CallingConv::ID CallingConv){
1385   if (IsVarArg)
1386     return false;
1387
1388   switch (CallingConv) {
1389   default:
1390     return false;
1391   case CallingConv::X86_StdCall:
1392     return !Subtarget->is64Bit();
1393   case CallingConv::X86_FastCall:
1394     return !Subtarget->is64Bit();
1395   case CallingConv::Fast:
1396     return PerformTailCallOpt;
1397   }
1398 }
1399
1400 /// CCAssignFnForNode - Selects the correct CCAssignFn for a the
1401 /// given CallingConvention value.
1402 CCAssignFn *X86TargetLowering::CCAssignFnForNode(CallingConv::ID CC) const {
1403   if (Subtarget->is64Bit()) {
1404     if (Subtarget->isTargetWin64())
1405       return CC_X86_Win64_C;
1406     else
1407       return CC_X86_64_C;
1408   }
1409
1410   if (CC == CallingConv::X86_FastCall)
1411     return CC_X86_32_FastCall;
1412   else if (CC == CallingConv::Fast)
1413     return CC_X86_32_FastCC;
1414   else
1415     return CC_X86_32_C;
1416 }
1417
1418 /// NameDecorationForCallConv - Selects the appropriate decoration to
1419 /// apply to a MachineFunction containing a given calling convention.
1420 NameDecorationStyle
1421 X86TargetLowering::NameDecorationForCallConv(CallingConv::ID CallConv) {
1422   if (CallConv == CallingConv::X86_FastCall)
1423     return FastCall;
1424   else if (CallConv == CallingConv::X86_StdCall)
1425     return StdCall;
1426   return None;
1427 }
1428
1429
1430 /// CreateCopyOfByValArgument - Make a copy of an aggregate at address specified
1431 /// by "Src" to address "Dst" with size and alignment information specified by
1432 /// the specific parameter attribute. The copy will be passed as a byval
1433 /// function parameter.
1434 static SDValue
1435 CreateCopyOfByValArgument(SDValue Src, SDValue Dst, SDValue Chain,
1436                           ISD::ArgFlagsTy Flags, SelectionDAG &DAG,
1437                           DebugLoc dl) {
1438   SDValue SizeNode     = DAG.getConstant(Flags.getByValSize(), MVT::i32);
1439   return DAG.getMemcpy(Chain, dl, Dst, Src, SizeNode, Flags.getByValAlign(),
1440                        /*AlwaysInline=*/true, NULL, 0, NULL, 0);
1441 }
1442
1443 /// FuncIsMadeTailCallSafe - Return true if the function is being made into
1444 /// a tailcall target by changing its ABI.
1445 static bool FuncIsMadeTailCallSafe(CallingConv::ID CC) {
1446   return PerformTailCallOpt && CC == CallingConv::Fast;
1447 }
1448
1449 SDValue
1450 X86TargetLowering::LowerMemArgument(SDValue Chain,
1451                                     CallingConv::ID CallConv,
1452                                     const SmallVectorImpl<ISD::InputArg> &Ins,
1453                                     DebugLoc dl, SelectionDAG &DAG,
1454                                     const CCValAssign &VA,
1455                                     MachineFrameInfo *MFI,
1456                                     unsigned i) {
1457   // Create the nodes corresponding to a load from this parameter slot.
1458   ISD::ArgFlagsTy Flags = Ins[i].Flags;
1459   bool AlwaysUseMutable = FuncIsMadeTailCallSafe(CallConv);
1460   bool isImmutable = !AlwaysUseMutable && !Flags.isByVal();
1461   EVT ValVT;
1462
1463   // If value is passed by pointer we have address passed instead of the value
1464   // itself.
1465   if (VA.getLocInfo() == CCValAssign::Indirect)
1466     ValVT = VA.getLocVT();
1467   else
1468     ValVT = VA.getValVT();
1469
1470   // FIXME: For now, all byval parameter objects are marked mutable. This can be
1471   // changed with more analysis.
1472   // In case of tail call optimization mark all arguments mutable. Since they
1473   // could be overwritten by lowering of arguments in case of a tail call.
1474   int FI = MFI->CreateFixedObject(ValVT.getSizeInBits()/8,
1475                                   VA.getLocMemOffset(), isImmutable, false);
1476   SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
1477   if (Flags.isByVal())
1478     return FIN;
1479   return DAG.getLoad(ValVT, dl, Chain, FIN,
1480                      PseudoSourceValue::getFixedStack(FI), 0);
1481 }
1482
1483 SDValue
1484 X86TargetLowering::LowerFormalArguments(SDValue Chain,
1485                                         CallingConv::ID CallConv,
1486                                         bool isVarArg,
1487                                       const SmallVectorImpl<ISD::InputArg> &Ins,
1488                                         DebugLoc dl,
1489                                         SelectionDAG &DAG,
1490                                         SmallVectorImpl<SDValue> &InVals) {
1491
1492   MachineFunction &MF = DAG.getMachineFunction();
1493   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1494
1495   const Function* Fn = MF.getFunction();
1496   if (Fn->hasExternalLinkage() &&
1497       Subtarget->isTargetCygMing() &&
1498       Fn->getName() == "main")
1499     FuncInfo->setForceFramePointer(true);
1500
1501   // Decorate the function name.
1502   FuncInfo->setDecorationStyle(NameDecorationForCallConv(CallConv));
1503
1504   MachineFrameInfo *MFI = MF.getFrameInfo();
1505   bool Is64Bit = Subtarget->is64Bit();
1506   bool IsWin64 = Subtarget->isTargetWin64();
1507
1508   assert(!(isVarArg && CallConv == CallingConv::Fast) &&
1509          "Var args not supported with calling convention fastcc");
1510
1511   // Assign locations to all of the incoming arguments.
1512   SmallVector<CCValAssign, 16> ArgLocs;
1513   CCState CCInfo(CallConv, isVarArg, getTargetMachine(),
1514                  ArgLocs, *DAG.getContext());
1515   CCInfo.AnalyzeFormalArguments(Ins, CCAssignFnForNode(CallConv));
1516
1517   unsigned LastVal = ~0U;
1518   SDValue ArgValue;
1519   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
1520     CCValAssign &VA = ArgLocs[i];
1521     // TODO: If an arg is passed in two places (e.g. reg and stack), skip later
1522     // places.
1523     assert(VA.getValNo() != LastVal &&
1524            "Don't support value assigned to multiple locs yet");
1525     LastVal = VA.getValNo();
1526
1527     if (VA.isRegLoc()) {
1528       EVT RegVT = VA.getLocVT();
1529       TargetRegisterClass *RC = NULL;
1530       if (RegVT == MVT::i32)
1531         RC = X86::GR32RegisterClass;
1532       else if (Is64Bit && RegVT == MVT::i64)
1533         RC = X86::GR64RegisterClass;
1534       else if (RegVT == MVT::f32)
1535         RC = X86::FR32RegisterClass;
1536       else if (RegVT == MVT::f64)
1537         RC = X86::FR64RegisterClass;
1538       else if (RegVT.isVector() && RegVT.getSizeInBits() == 128)
1539         RC = X86::VR128RegisterClass;
1540       else if (RegVT.isVector() && RegVT.getSizeInBits() == 64)
1541         RC = X86::VR64RegisterClass;
1542       else
1543         llvm_unreachable("Unknown argument type!");
1544
1545       unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
1546       ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
1547
1548       // If this is an 8 or 16-bit value, it is really passed promoted to 32
1549       // bits.  Insert an assert[sz]ext to capture this, then truncate to the
1550       // right size.
1551       if (VA.getLocInfo() == CCValAssign::SExt)
1552         ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
1553                                DAG.getValueType(VA.getValVT()));
1554       else if (VA.getLocInfo() == CCValAssign::ZExt)
1555         ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
1556                                DAG.getValueType(VA.getValVT()));
1557       else if (VA.getLocInfo() == CCValAssign::BCvt)
1558         ArgValue = DAG.getNode(ISD::BIT_CONVERT, dl, VA.getValVT(), ArgValue);
1559
1560       if (VA.isExtInLoc()) {
1561         // Handle MMX values passed in XMM regs.
1562         if (RegVT.isVector()) {
1563           ArgValue = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i64,
1564                                  ArgValue, DAG.getConstant(0, MVT::i64));
1565           ArgValue = DAG.getNode(ISD::BIT_CONVERT, dl, VA.getValVT(), ArgValue);
1566         } else
1567           ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
1568       }
1569     } else {
1570       assert(VA.isMemLoc());
1571       ArgValue = LowerMemArgument(Chain, CallConv, Ins, dl, DAG, VA, MFI, i);
1572     }
1573
1574     // If value is passed via pointer - do a load.
1575     if (VA.getLocInfo() == CCValAssign::Indirect)
1576       ArgValue = DAG.getLoad(VA.getValVT(), dl, Chain, ArgValue, NULL, 0);
1577
1578     InVals.push_back(ArgValue);
1579   }
1580
1581   // The x86-64 ABI for returning structs by value requires that we copy
1582   // the sret argument into %rax for the return. Save the argument into
1583   // a virtual register so that we can access it from the return points.
1584   if (Is64Bit && MF.getFunction()->hasStructRetAttr()) {
1585     X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1586     unsigned Reg = FuncInfo->getSRetReturnReg();
1587     if (!Reg) {
1588       Reg = MF.getRegInfo().createVirtualRegister(getRegClassFor(MVT::i64));
1589       FuncInfo->setSRetReturnReg(Reg);
1590     }
1591     SDValue Copy = DAG.getCopyToReg(DAG.getEntryNode(), dl, Reg, InVals[0]);
1592     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Copy, Chain);
1593   }
1594
1595   unsigned StackSize = CCInfo.getNextStackOffset();
1596   // Align stack specially for tail calls.
1597   if (FuncIsMadeTailCallSafe(CallConv))
1598     StackSize = GetAlignedArgumentStackSize(StackSize, DAG);
1599
1600   // If the function takes variable number of arguments, make a frame index for
1601   // the start of the first vararg value... for expansion of llvm.va_start.
1602   if (isVarArg) {
1603     if (Is64Bit || CallConv != CallingConv::X86_FastCall) {
1604       VarArgsFrameIndex = MFI->CreateFixedObject(1, StackSize, true, false);
1605     }
1606     if (Is64Bit) {
1607       unsigned TotalNumIntRegs = 0, TotalNumXMMRegs = 0;
1608
1609       // FIXME: We should really autogenerate these arrays
1610       static const unsigned GPR64ArgRegsWin64[] = {
1611         X86::RCX, X86::RDX, X86::R8,  X86::R9
1612       };
1613       static const unsigned XMMArgRegsWin64[] = {
1614         X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3
1615       };
1616       static const unsigned GPR64ArgRegs64Bit[] = {
1617         X86::RDI, X86::RSI, X86::RDX, X86::RCX, X86::R8, X86::R9
1618       };
1619       static const unsigned XMMArgRegs64Bit[] = {
1620         X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
1621         X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
1622       };
1623       const unsigned *GPR64ArgRegs, *XMMArgRegs;
1624
1625       if (IsWin64) {
1626         TotalNumIntRegs = 4; TotalNumXMMRegs = 4;
1627         GPR64ArgRegs = GPR64ArgRegsWin64;
1628         XMMArgRegs = XMMArgRegsWin64;
1629       } else {
1630         TotalNumIntRegs = 6; TotalNumXMMRegs = 8;
1631         GPR64ArgRegs = GPR64ArgRegs64Bit;
1632         XMMArgRegs = XMMArgRegs64Bit;
1633       }
1634       unsigned NumIntRegs = CCInfo.getFirstUnallocated(GPR64ArgRegs,
1635                                                        TotalNumIntRegs);
1636       unsigned NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs,
1637                                                        TotalNumXMMRegs);
1638
1639       bool NoImplicitFloatOps = Fn->hasFnAttr(Attribute::NoImplicitFloat);
1640       assert(!(NumXMMRegs && !Subtarget->hasSSE1()) &&
1641              "SSE register cannot be used when SSE is disabled!");
1642       assert(!(NumXMMRegs && UseSoftFloat && NoImplicitFloatOps) &&
1643              "SSE register cannot be used when SSE is disabled!");
1644       if (UseSoftFloat || NoImplicitFloatOps || !Subtarget->hasSSE1())
1645         // Kernel mode asks for SSE to be disabled, so don't push them
1646         // on the stack.
1647         TotalNumXMMRegs = 0;
1648
1649       // For X86-64, if there are vararg parameters that are passed via
1650       // registers, then we must store them to their spots on the stack so they
1651       // may be loaded by deferencing the result of va_next.
1652       VarArgsGPOffset = NumIntRegs * 8;
1653       VarArgsFPOffset = TotalNumIntRegs * 8 + NumXMMRegs * 16;
1654       RegSaveFrameIndex = MFI->CreateStackObject(TotalNumIntRegs * 8 +
1655                                                  TotalNumXMMRegs * 16, 16,
1656                                                  false);
1657
1658       // Store the integer parameter registers.
1659       SmallVector<SDValue, 8> MemOps;
1660       SDValue RSFIN = DAG.getFrameIndex(RegSaveFrameIndex, getPointerTy());
1661       unsigned Offset = VarArgsGPOffset;
1662       for (; NumIntRegs != TotalNumIntRegs; ++NumIntRegs) {
1663         SDValue FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(), RSFIN,
1664                                   DAG.getIntPtrConstant(Offset));
1665         unsigned VReg = MF.addLiveIn(GPR64ArgRegs[NumIntRegs],
1666                                      X86::GR64RegisterClass);
1667         SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
1668         SDValue Store =
1669           DAG.getStore(Val.getValue(1), dl, Val, FIN,
1670                        PseudoSourceValue::getFixedStack(RegSaveFrameIndex),
1671                        Offset);
1672         MemOps.push_back(Store);
1673         Offset += 8;
1674       }
1675
1676       if (TotalNumXMMRegs != 0 && NumXMMRegs != TotalNumXMMRegs) {
1677         // Now store the XMM (fp + vector) parameter registers.
1678         SmallVector<SDValue, 11> SaveXMMOps;
1679         SaveXMMOps.push_back(Chain);
1680
1681         unsigned AL = MF.addLiveIn(X86::AL, X86::GR8RegisterClass);
1682         SDValue ALVal = DAG.getCopyFromReg(DAG.getEntryNode(), dl, AL, MVT::i8);
1683         SaveXMMOps.push_back(ALVal);
1684
1685         SaveXMMOps.push_back(DAG.getIntPtrConstant(RegSaveFrameIndex));
1686         SaveXMMOps.push_back(DAG.getIntPtrConstant(VarArgsFPOffset));
1687
1688         for (; NumXMMRegs != TotalNumXMMRegs; ++NumXMMRegs) {
1689           unsigned VReg = MF.addLiveIn(XMMArgRegs[NumXMMRegs],
1690                                        X86::VR128RegisterClass);
1691           SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::v4f32);
1692           SaveXMMOps.push_back(Val);
1693         }
1694         MemOps.push_back(DAG.getNode(X86ISD::VASTART_SAVE_XMM_REGS, dl,
1695                                      MVT::Other,
1696                                      &SaveXMMOps[0], SaveXMMOps.size()));
1697       }
1698
1699       if (!MemOps.empty())
1700         Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
1701                             &MemOps[0], MemOps.size());
1702     }
1703   }
1704
1705   // Some CCs need callee pop.
1706   if (IsCalleePop(isVarArg, CallConv)) {
1707     BytesToPopOnReturn  = StackSize; // Callee pops everything.
1708   } else {
1709     BytesToPopOnReturn  = 0; // Callee pops nothing.
1710     // If this is an sret function, the return should pop the hidden pointer.
1711     if (!Is64Bit && CallConv != CallingConv::Fast && ArgsAreStructReturn(Ins))
1712       BytesToPopOnReturn = 4;
1713   }
1714
1715   if (!Is64Bit) {
1716     RegSaveFrameIndex = 0xAAAAAAA;   // RegSaveFrameIndex is X86-64 only.
1717     if (CallConv == CallingConv::X86_FastCall)
1718       VarArgsFrameIndex = 0xAAAAAAA;   // fastcc functions can't have varargs.
1719   }
1720
1721   FuncInfo->setBytesToPopOnReturn(BytesToPopOnReturn);
1722
1723   return Chain;
1724 }
1725
1726 SDValue
1727 X86TargetLowering::LowerMemOpCallTo(SDValue Chain,
1728                                     SDValue StackPtr, SDValue Arg,
1729                                     DebugLoc dl, SelectionDAG &DAG,
1730                                     const CCValAssign &VA,
1731                                     ISD::ArgFlagsTy Flags) {
1732   const unsigned FirstStackArgOffset = (Subtarget->isTargetWin64() ? 32 : 0);
1733   unsigned LocMemOffset = FirstStackArgOffset + VA.getLocMemOffset();
1734   SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset);
1735   PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, PtrOff);
1736   if (Flags.isByVal()) {
1737     return CreateCopyOfByValArgument(Arg, PtrOff, Chain, Flags, DAG, dl);
1738   }
1739   return DAG.getStore(Chain, dl, Arg, PtrOff,
1740                       PseudoSourceValue::getStack(), LocMemOffset);
1741 }
1742
1743 /// EmitTailCallLoadRetAddr - Emit a load of return address if tail call
1744 /// optimization is performed and it is required.
1745 SDValue
1746 X86TargetLowering::EmitTailCallLoadRetAddr(SelectionDAG &DAG,
1747                                            SDValue &OutRetAddr, SDValue Chain,
1748                                            bool IsTailCall, bool Is64Bit,
1749                                            int FPDiff, DebugLoc dl) {
1750   if (!IsTailCall || FPDiff==0) return Chain;
1751
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);
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, true,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   return Chain;
1778 }
1779
1780 SDValue
1781 X86TargetLowering::LowerCall(SDValue Chain, SDValue Callee, const Type *RetTy,
1782                              CallingConv::ID CallConv, bool isVarArg,
1783                              bool &isTailCall,
1784                              const SmallVectorImpl<ISD::OutputArg> &Outs,
1785                              const SmallVectorImpl<ISD::InputArg> &Ins,
1786                              DebugLoc dl, SelectionDAG &DAG,
1787                              SmallVectorImpl<SDValue> &InVals) {
1788   MachineFunction &MF = DAG.getMachineFunction();
1789   bool Is64Bit        = Subtarget->is64Bit();
1790   bool IsStructRet    = CallIsStructReturn(Outs);
1791
1792   if (isTailCall)
1793     // Check if it's really possible to do a tail call.
1794     isTailCall = IsEligibleForTailCallOptimization(Callee, RetTy, CallConv,
1795                                                    isVarArg, Outs, Ins, DAG);
1796
1797   assert(!(isVarArg && CallConv == CallingConv::Fast) &&
1798          "Var args not supported with calling convention fastcc");
1799
1800   // Analyze operands of the call, assigning locations to each operand.
1801   SmallVector<CCValAssign, 16> ArgLocs;
1802   CCState CCInfo(CallConv, isVarArg, getTargetMachine(),
1803                  ArgLocs, *DAG.getContext());
1804   CCInfo.AnalyzeCallOperands(Outs, CCAssignFnForNode(CallConv));
1805
1806   // Get a count of how many bytes are to be pushed on the stack.
1807   unsigned NumBytes = CCInfo.getNextStackOffset();
1808   if (FuncIsMadeTailCallSafe(CallConv))
1809     NumBytes = GetAlignedArgumentStackSize(NumBytes, DAG);
1810   else if (isTailCall && !PerformTailCallOpt)
1811     // This is a sibcall. The memory operands are available in caller's
1812     // own caller's stack.
1813     NumBytes = 0;
1814
1815   int FPDiff = 0;
1816   if (isTailCall) {
1817     ++NumTailCalls;
1818
1819     // Lower arguments at fp - stackoffset + fpdiff.
1820     unsigned NumBytesCallerPushed =
1821       MF.getInfo<X86MachineFunctionInfo>()->getBytesToPopOnReturn();
1822     FPDiff = NumBytesCallerPushed - NumBytes;
1823
1824     // Set the delta of movement of the returnaddr stackslot.
1825     // But only set if delta is greater than previous delta.
1826     if (FPDiff < (MF.getInfo<X86MachineFunctionInfo>()->getTCReturnAddrDelta()))
1827       MF.getInfo<X86MachineFunctionInfo>()->setTCReturnAddrDelta(FPDiff);
1828   }
1829
1830   Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes, true));
1831
1832   SDValue RetAddrFrIdx;
1833   // Load return adress for tail calls.
1834   Chain = EmitTailCallLoadRetAddr(DAG, RetAddrFrIdx, Chain, isTailCall, Is64Bit,
1835                                   FPDiff, dl);
1836
1837   SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
1838   SmallVector<SDValue, 8> MemOpChains;
1839   SDValue StackPtr;
1840
1841   // Walk the register/memloc assignments, inserting copies/loads.  In the case
1842   // of tail call optimization arguments are handle later.
1843   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
1844     CCValAssign &VA = ArgLocs[i];
1845     EVT RegVT = VA.getLocVT();
1846     SDValue Arg = Outs[i].Val;
1847     ISD::ArgFlagsTy Flags = Outs[i].Flags;
1848     bool isByVal = Flags.isByVal();
1849
1850     // Promote the value if needed.
1851     switch (VA.getLocInfo()) {
1852     default: llvm_unreachable("Unknown loc info!");
1853     case CCValAssign::Full: break;
1854     case CCValAssign::SExt:
1855       Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, RegVT, Arg);
1856       break;
1857     case CCValAssign::ZExt:
1858       Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, RegVT, Arg);
1859       break;
1860     case CCValAssign::AExt:
1861       if (RegVT.isVector() && RegVT.getSizeInBits() == 128) {
1862         // Special case: passing MMX values in XMM registers.
1863         Arg = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::i64, Arg);
1864         Arg = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64, Arg);
1865         Arg = getMOVL(DAG, dl, MVT::v2i64, DAG.getUNDEF(MVT::v2i64), Arg);
1866       } else
1867         Arg = DAG.getNode(ISD::ANY_EXTEND, dl, RegVT, Arg);
1868       break;
1869     case CCValAssign::BCvt:
1870       Arg = DAG.getNode(ISD::BIT_CONVERT, dl, RegVT, Arg);
1871       break;
1872     case CCValAssign::Indirect: {
1873       // Store the argument.
1874       SDValue SpillSlot = DAG.CreateStackTemporary(VA.getValVT());
1875       int FI = cast<FrameIndexSDNode>(SpillSlot)->getIndex();
1876       Chain = DAG.getStore(Chain, dl, Arg, SpillSlot,
1877                            PseudoSourceValue::getFixedStack(FI), 0);
1878       Arg = SpillSlot;
1879       break;
1880     }
1881     }
1882
1883     if (VA.isRegLoc()) {
1884       RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
1885     } else {
1886       if (!isTailCall || (isTailCall && isByVal)) {
1887         assert(VA.isMemLoc());
1888         if (StackPtr.getNode() == 0)
1889           StackPtr = DAG.getCopyFromReg(Chain, dl, X86StackPtr, getPointerTy());
1890
1891         MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg,
1892                                                dl, DAG, VA, Flags));
1893       }
1894     }
1895   }
1896
1897   if (!MemOpChains.empty())
1898     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
1899                         &MemOpChains[0], MemOpChains.size());
1900
1901   // Build a sequence of copy-to-reg nodes chained together with token chain
1902   // and flag operands which copy the outgoing args into registers.
1903   SDValue InFlag;
1904   // Tail call byval lowering might overwrite argument registers so in case of
1905   // tail call optimization the copies to registers are lowered later.
1906   if (!isTailCall)
1907     for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
1908       Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
1909                                RegsToPass[i].second, InFlag);
1910       InFlag = Chain.getValue(1);
1911     }
1912
1913
1914   if (Subtarget->isPICStyleGOT()) {
1915     // ELF / PIC requires GOT in the EBX register before function calls via PLT
1916     // GOT pointer.
1917     if (!isTailCall) {
1918       Chain = DAG.getCopyToReg(Chain, dl, X86::EBX,
1919                                DAG.getNode(X86ISD::GlobalBaseReg,
1920                                            DebugLoc::getUnknownLoc(),
1921                                            getPointerTy()),
1922                                InFlag);
1923       InFlag = Chain.getValue(1);
1924     } else {
1925       // If we are tail calling and generating PIC/GOT style code load the
1926       // address of the callee into ECX. The value in ecx is used as target of
1927       // the tail jump. This is done to circumvent the ebx/callee-saved problem
1928       // for tail calls on PIC/GOT architectures. Normally we would just put the
1929       // address of GOT into ebx and then call target@PLT. But for tail calls
1930       // ebx would be restored (since ebx is callee saved) before jumping to the
1931       // target@PLT.
1932
1933       // Note: The actual moving to ECX is done further down.
1934       GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee);
1935       if (G && !G->getGlobal()->hasHiddenVisibility() &&
1936           !G->getGlobal()->hasProtectedVisibility())
1937         Callee = LowerGlobalAddress(Callee, DAG);
1938       else if (isa<ExternalSymbolSDNode>(Callee))
1939         Callee = LowerExternalSymbol(Callee, DAG);
1940     }
1941   }
1942
1943   if (Is64Bit && isVarArg) {
1944     // From AMD64 ABI document:
1945     // For calls that may call functions that use varargs or stdargs
1946     // (prototype-less calls or calls to functions containing ellipsis (...) in
1947     // the declaration) %al is used as hidden argument to specify the number
1948     // of SSE registers used. The contents of %al do not need to match exactly
1949     // the number of registers, but must be an ubound on the number of SSE
1950     // registers used and is in the range 0 - 8 inclusive.
1951
1952     // FIXME: Verify this on Win64
1953     // Count the number of XMM registers allocated.
1954     static const unsigned XMMArgRegs[] = {
1955       X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
1956       X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
1957     };
1958     unsigned NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs, 8);
1959     assert((Subtarget->hasSSE1() || !NumXMMRegs)
1960            && "SSE registers cannot be used when SSE is disabled");
1961
1962     Chain = DAG.getCopyToReg(Chain, dl, X86::AL,
1963                              DAG.getConstant(NumXMMRegs, MVT::i8), InFlag);
1964     InFlag = Chain.getValue(1);
1965   }
1966
1967
1968   // For tail calls lower the arguments to the 'real' stack slot.
1969   if (isTailCall) {
1970     // Force all the incoming stack arguments to be loaded from the stack
1971     // before any new outgoing arguments are stored to the stack, because the
1972     // outgoing stack slots may alias the incoming argument stack slots, and
1973     // the alias isn't otherwise explicit. This is slightly more conservative
1974     // than necessary, because it means that each store effectively depends
1975     // on every argument instead of just those arguments it would clobber.
1976     SDValue ArgChain = DAG.getStackArgumentTokenFactor(Chain);
1977
1978     SmallVector<SDValue, 8> MemOpChains2;
1979     SDValue FIN;
1980     int FI = 0;
1981     // Do not flag preceeding copytoreg stuff together with the following stuff.
1982     InFlag = SDValue();
1983     if (PerformTailCallOpt) {
1984       for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
1985         CCValAssign &VA = ArgLocs[i];
1986         if (VA.isRegLoc())
1987           continue;
1988         assert(VA.isMemLoc());
1989         SDValue Arg = Outs[i].Val;
1990         ISD::ArgFlagsTy Flags = Outs[i].Flags;
1991         // Create frame index.
1992         int32_t Offset = VA.getLocMemOffset()+FPDiff;
1993         uint32_t OpSize = (VA.getLocVT().getSizeInBits()+7)/8;
1994         FI = MF.getFrameInfo()->CreateFixedObject(OpSize, Offset, true, false);
1995         FIN = DAG.getFrameIndex(FI, getPointerTy());
1996
1997         if (Flags.isByVal()) {
1998           // Copy relative to framepointer.
1999           SDValue Source = DAG.getIntPtrConstant(VA.getLocMemOffset());
2000           if (StackPtr.getNode() == 0)
2001             StackPtr = DAG.getCopyFromReg(Chain, dl, X86StackPtr,
2002                                           getPointerTy());
2003           Source = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, Source);
2004
2005           MemOpChains2.push_back(CreateCopyOfByValArgument(Source, FIN,
2006                                                            ArgChain,
2007                                                            Flags, DAG, dl));
2008         } else {
2009           // Store relative to framepointer.
2010           MemOpChains2.push_back(
2011             DAG.getStore(ArgChain, dl, Arg, FIN,
2012                          PseudoSourceValue::getFixedStack(FI), 0));
2013         }
2014       }
2015     }
2016
2017     if (!MemOpChains2.empty())
2018       Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
2019                           &MemOpChains2[0], MemOpChains2.size());
2020
2021     // Copy arguments to their registers.
2022     for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
2023       Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
2024                                RegsToPass[i].second, InFlag);
2025       InFlag = Chain.getValue(1);
2026     }
2027     InFlag =SDValue();
2028
2029     // Store the return address to the appropriate stack slot.
2030     Chain = EmitTailCallStoreRetAddr(DAG, MF, Chain, RetAddrFrIdx, Is64Bit,
2031                                      FPDiff, dl);
2032   }
2033
2034   bool WasGlobalOrExternal = false;
2035   if (getTargetMachine().getCodeModel() == CodeModel::Large) {
2036     assert(Is64Bit && "Large code model is only legal in 64-bit mode.");
2037     // In the 64-bit large code model, we have to make all calls
2038     // through a register, since the call instruction's 32-bit
2039     // pc-relative offset may not be large enough to hold the whole
2040     // address.
2041   } else if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
2042     WasGlobalOrExternal = true;
2043     // If the callee is a GlobalAddress node (quite common, every direct call
2044     // is) turn it into a TargetGlobalAddress node so that legalize doesn't hack
2045     // it.
2046
2047     // We should use extra load for direct calls to dllimported functions in
2048     // non-JIT mode.
2049     GlobalValue *GV = G->getGlobal();
2050     if (!GV->hasDLLImportLinkage()) {
2051       unsigned char OpFlags = 0;
2052
2053       // On ELF targets, in both X86-64 and X86-32 mode, direct calls to
2054       // external symbols most go through the PLT in PIC mode.  If the symbol
2055       // has hidden or protected visibility, or if it is static or local, then
2056       // we don't need to use the PLT - we can directly call it.
2057       if (Subtarget->isTargetELF() &&
2058           getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
2059           GV->hasDefaultVisibility() && !GV->hasLocalLinkage()) {
2060         OpFlags = X86II::MO_PLT;
2061       } else if (Subtarget->isPICStyleStubAny() &&
2062                (GV->isDeclaration() || GV->isWeakForLinker()) &&
2063                Subtarget->getDarwinVers() < 9) {
2064         // PC-relative references to external symbols should go through $stub,
2065         // unless we're building with the leopard linker or later, which
2066         // automatically synthesizes these stubs.
2067         OpFlags = X86II::MO_DARWIN_STUB;
2068       }
2069
2070       Callee = DAG.getTargetGlobalAddress(GV, getPointerTy(),
2071                                           G->getOffset(), OpFlags);
2072     }
2073   } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
2074     WasGlobalOrExternal = true;
2075     unsigned char OpFlags = 0;
2076
2077     // On ELF targets, in either X86-64 or X86-32 mode, direct calls to external
2078     // symbols should go through the PLT.
2079     if (Subtarget->isTargetELF() &&
2080         getTargetMachine().getRelocationModel() == Reloc::PIC_) {
2081       OpFlags = X86II::MO_PLT;
2082     } else if (Subtarget->isPICStyleStubAny() &&
2083              Subtarget->getDarwinVers() < 9) {
2084       // PC-relative references to external symbols should go through $stub,
2085       // unless we're building with the leopard linker or later, which
2086       // automatically synthesizes these stubs.
2087       OpFlags = X86II::MO_DARWIN_STUB;
2088     }
2089
2090     Callee = DAG.getTargetExternalSymbol(S->getSymbol(), getPointerTy(),
2091                                          OpFlags);
2092   }
2093
2094   if (isTailCall && !WasGlobalOrExternal) {
2095     unsigned Opc = Is64Bit ? X86::R11 : X86::EAX;
2096
2097     Chain = DAG.getCopyToReg(Chain,  dl,
2098                              DAG.getRegister(Opc, getPointerTy()),
2099                              Callee,InFlag);
2100     Callee = DAG.getRegister(Opc, getPointerTy());
2101     // Add register as live out.
2102     MF.getRegInfo().addLiveOut(Opc);
2103   }
2104
2105   // Returns a chain & a flag for retval copy to use.
2106   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Flag);
2107   SmallVector<SDValue, 8> Ops;
2108
2109   if (isTailCall) {
2110     Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, true),
2111                            DAG.getIntPtrConstant(0, true), InFlag);
2112     InFlag = Chain.getValue(1);
2113   }
2114
2115   Ops.push_back(Chain);
2116   Ops.push_back(Callee);
2117
2118   if (isTailCall)
2119     Ops.push_back(DAG.getConstant(FPDiff, MVT::i32));
2120
2121   // Add argument registers to the end of the list so that they are known live
2122   // into the call.
2123   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
2124     Ops.push_back(DAG.getRegister(RegsToPass[i].first,
2125                                   RegsToPass[i].second.getValueType()));
2126
2127   // Add an implicit use GOT pointer in EBX.
2128   if (!isTailCall && Subtarget->isPICStyleGOT())
2129     Ops.push_back(DAG.getRegister(X86::EBX, getPointerTy()));
2130
2131   // Add an implicit use of AL for x86 vararg functions.
2132   if (Is64Bit && isVarArg)
2133     Ops.push_back(DAG.getRegister(X86::AL, MVT::i8));
2134
2135   if (InFlag.getNode())
2136     Ops.push_back(InFlag);
2137
2138   if (isTailCall) {
2139     // If this is the first return lowered for this function, add the regs
2140     // to the liveout set for the function.
2141     if (MF.getRegInfo().liveout_empty()) {
2142       SmallVector<CCValAssign, 16> RVLocs;
2143       CCState CCInfo(CallConv, isVarArg, getTargetMachine(), RVLocs,
2144                      *DAG.getContext());
2145       CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
2146       for (unsigned i = 0; i != RVLocs.size(); ++i)
2147         if (RVLocs[i].isRegLoc())
2148           MF.getRegInfo().addLiveOut(RVLocs[i].getLocReg());
2149     }
2150
2151     assert(((Callee.getOpcode() == ISD::Register &&
2152                (cast<RegisterSDNode>(Callee)->getReg() == X86::EAX ||
2153                 cast<RegisterSDNode>(Callee)->getReg() == X86::R11)) ||
2154               Callee.getOpcode() == ISD::TargetExternalSymbol ||
2155               Callee.getOpcode() == ISD::TargetGlobalAddress) &&
2156            "Expecting a global address, external symbol, or scratch register");
2157
2158     return DAG.getNode(X86ISD::TC_RETURN, dl,
2159                        NodeTys, &Ops[0], Ops.size());
2160   }
2161
2162   Chain = DAG.getNode(X86ISD::CALL, dl, NodeTys, &Ops[0], Ops.size());
2163   InFlag = Chain.getValue(1);
2164
2165   // Create the CALLSEQ_END node.
2166   unsigned NumBytesForCalleeToPush;
2167   if (IsCalleePop(isVarArg, CallConv))
2168     NumBytesForCalleeToPush = NumBytes;    // Callee pops everything
2169   else if (!Is64Bit && CallConv != CallingConv::Fast && IsStructRet)
2170     // If this is is a call to a struct-return function, the callee
2171     // pops the hidden struct pointer, so we have to push it back.
2172     // This is common for Darwin/X86, Linux & Mingw32 targets.
2173     NumBytesForCalleeToPush = 4;
2174   else
2175     NumBytesForCalleeToPush = 0;  // Callee pops nothing.
2176
2177   // Returns a flag for retval copy to use.
2178   Chain = DAG.getCALLSEQ_END(Chain,
2179                              DAG.getIntPtrConstant(NumBytes, true),
2180                              DAG.getIntPtrConstant(NumBytesForCalleeToPush,
2181                                                    true),
2182                              InFlag);
2183   InFlag = Chain.getValue(1);
2184
2185   // Handle result values, copying them out of physregs into vregs that we
2186   // return.
2187   return LowerCallResult(Chain, InFlag, CallConv, isVarArg,
2188                          Ins, dl, DAG, InVals);
2189 }
2190
2191
2192 //===----------------------------------------------------------------------===//
2193 //                Fast Calling Convention (tail call) implementation
2194 //===----------------------------------------------------------------------===//
2195
2196 //  Like std call, callee cleans arguments, convention except that ECX is
2197 //  reserved for storing the tail called function address. Only 2 registers are
2198 //  free for argument passing (inreg). Tail call optimization is performed
2199 //  provided:
2200 //                * tailcallopt is enabled
2201 //                * caller/callee are fastcc
2202 //  On X86_64 architecture with GOT-style position independent code only local
2203 //  (within module) calls are supported at the moment.
2204 //  To keep the stack aligned according to platform abi the function
2205 //  GetAlignedArgumentStackSize ensures that argument delta is always multiples
2206 //  of stack alignment. (Dynamic linkers need this - darwin's dyld for example)
2207 //  If a tail called function callee has more arguments than the caller the
2208 //  caller needs to make sure that there is room to move the RETADDR to. This is
2209 //  achieved by reserving an area the size of the argument delta right after the
2210 //  original REtADDR, but before the saved framepointer or the spilled registers
2211 //  e.g. caller(arg1, arg2) calls callee(arg1, arg2,arg3,arg4)
2212 //  stack layout:
2213 //    arg1
2214 //    arg2
2215 //    RETADDR
2216 //    [ new RETADDR
2217 //      move area ]
2218 //    (possible EBP)
2219 //    ESI
2220 //    EDI
2221 //    local1 ..
2222
2223 /// GetAlignedArgumentStackSize - Make the stack size align e.g 16n + 12 aligned
2224 /// for a 16 byte align requirement.
2225 unsigned X86TargetLowering::GetAlignedArgumentStackSize(unsigned StackSize,
2226                                                         SelectionDAG& DAG) {
2227   MachineFunction &MF = DAG.getMachineFunction();
2228   const TargetMachine &TM = MF.getTarget();
2229   const TargetFrameInfo &TFI = *TM.getFrameInfo();
2230   unsigned StackAlignment = TFI.getStackAlignment();
2231   uint64_t AlignMask = StackAlignment - 1;
2232   int64_t Offset = StackSize;
2233   uint64_t SlotSize = TD->getPointerSize();
2234   if ( (Offset & AlignMask) <= (StackAlignment - SlotSize) ) {
2235     // Number smaller than 12 so just add the difference.
2236     Offset += ((StackAlignment - SlotSize) - (Offset & AlignMask));
2237   } else {
2238     // Mask out lower bits, add stackalignment once plus the 12 bytes.
2239     Offset = ((~AlignMask) & Offset) + StackAlignment +
2240       (StackAlignment-SlotSize);
2241   }
2242   return Offset;
2243 }
2244
2245 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
2246 /// for tail call optimization. Targets which want to do tail call
2247 /// optimization should implement this function.
2248 bool
2249 X86TargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
2250                                                      const Type *RetTy,
2251                                                      CallingConv::ID CalleeCC,
2252                                                      bool isVarArg,
2253                                     const SmallVectorImpl<ISD::OutputArg> &Outs,
2254                                     const SmallVectorImpl<ISD::InputArg> &Ins,
2255                                                      SelectionDAG& DAG) const {
2256   if (CalleeCC != CallingConv::Fast &&
2257       CalleeCC != CallingConv::C)
2258     return false;
2259
2260   // If -tailcallopt is specified, make fastcc functions tail-callable.
2261   const Function *CallerF = DAG.getMachineFunction().getFunction();
2262   if (PerformTailCallOpt) {
2263     if (CalleeCC == CallingConv::Fast &&
2264         CallerF->getCallingConv() == CalleeCC)
2265       return true;
2266     return false;
2267   }
2268
2269
2270   // Look for obvious safe cases to perform tail call optimization that does not
2271   // requite ABI changes. This is what gcc calls sibcall.
2272
2273   // Do not tail call optimize vararg calls for now.
2274   if (isVarArg)
2275     return false;
2276
2277   // If the callee takes no arguments then go on to check the results of the
2278   // call.
2279   if (!Outs.empty()) {
2280     // Check if stack adjustment is needed. For now, do not do this if any
2281     // argument is passed on the stack.
2282     SmallVector<CCValAssign, 16> ArgLocs;
2283     CCState CCInfo(CalleeCC, isVarArg, getTargetMachine(),
2284                    ArgLocs, *DAG.getContext());
2285     CCInfo.AnalyzeCallOperands(Outs, CCAssignFnForNode(CalleeCC));
2286     if (CCInfo.getNextStackOffset()) {
2287       MachineFunction &MF = DAG.getMachineFunction();
2288       if (MF.getInfo<X86MachineFunctionInfo>()->getBytesToPopOnReturn())
2289         return false;
2290       if (Subtarget->isTargetWin64())
2291         // Win64 ABI has additional complications.
2292         return false;
2293
2294       // Check if the arguments are already laid out in the right way as
2295       // the caller's fixed stack objects.
2296       MachineFrameInfo *MFI = MF.getFrameInfo();
2297       for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2298         CCValAssign &VA = ArgLocs[i];
2299         EVT RegVT = VA.getLocVT();
2300         SDValue Arg = Outs[i].Val;
2301         ISD::ArgFlagsTy Flags = Outs[i].Flags;
2302         if (Flags.isByVal())
2303           return false; // TODO
2304         if (VA.getLocInfo() == CCValAssign::Indirect)
2305           return false;
2306         if (!VA.isRegLoc()) {
2307           LoadSDNode *Ld = dyn_cast<LoadSDNode>(Arg);
2308           if (!Ld)
2309             return false;
2310           SDValue Ptr = Ld->getBasePtr();
2311           FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr);
2312           if (!FINode)
2313             return false;
2314           int FI = FINode->getIndex();
2315           if (!MFI->isFixedObjectIndex(FI))
2316             return false;
2317           if (VA.getLocMemOffset() != MFI->getObjectOffset(FI))
2318             return false;
2319         }
2320       }
2321     }
2322   }
2323
2324   // If the caller does not return a value, then this is obviously safe.
2325   // This is one case where it's safe to perform this optimization even
2326   // if the return types do not match.
2327   const Type *CallerRetTy = CallerF->getReturnType();
2328   if (CallerRetTy->isVoidTy())
2329     return true;
2330
2331   // If the return types match, then it's safe.
2332   return CallerRetTy == RetTy;
2333 }
2334
2335 FastISel *
2336 X86TargetLowering::createFastISel(MachineFunction &mf, MachineModuleInfo *mmo,
2337                             DwarfWriter *dw,
2338                             DenseMap<const Value *, unsigned> &vm,
2339                             DenseMap<const BasicBlock*, MachineBasicBlock*> &bm,
2340                             DenseMap<const AllocaInst *, int> &am
2341 #ifndef NDEBUG
2342                           , SmallSet<Instruction*, 8> &cil
2343 #endif
2344                                   ) {
2345   return X86::createFastISel(mf, mmo, dw, vm, bm, am
2346 #ifndef NDEBUG
2347                              , cil
2348 #endif
2349                              );
2350 }
2351
2352
2353 //===----------------------------------------------------------------------===//
2354 //                           Other Lowering Hooks
2355 //===----------------------------------------------------------------------===//
2356
2357
2358 SDValue X86TargetLowering::getReturnAddressFrameIndex(SelectionDAG &DAG) {
2359   MachineFunction &MF = DAG.getMachineFunction();
2360   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
2361   int ReturnAddrIndex = FuncInfo->getRAIndex();
2362
2363   if (ReturnAddrIndex == 0) {
2364     // Set up a frame object for the return address.
2365     uint64_t SlotSize = TD->getPointerSize();
2366     ReturnAddrIndex = MF.getFrameInfo()->CreateFixedObject(SlotSize, -SlotSize,
2367                                                            true, false);
2368     FuncInfo->setRAIndex(ReturnAddrIndex);
2369   }
2370
2371   return DAG.getFrameIndex(ReturnAddrIndex, getPointerTy());
2372 }
2373
2374
2375 bool X86::isOffsetSuitableForCodeModel(int64_t Offset, CodeModel::Model M,
2376                                        bool hasSymbolicDisplacement) {
2377   // Offset should fit into 32 bit immediate field.
2378   if (!isInt32(Offset))
2379     return false;
2380
2381   // If we don't have a symbolic displacement - we don't have any extra
2382   // restrictions.
2383   if (!hasSymbolicDisplacement)
2384     return true;
2385
2386   // FIXME: Some tweaks might be needed for medium code model.
2387   if (M != CodeModel::Small && M != CodeModel::Kernel)
2388     return false;
2389
2390   // For small code model we assume that latest object is 16MB before end of 31
2391   // bits boundary. We may also accept pretty large negative constants knowing
2392   // that all objects are in the positive half of address space.
2393   if (M == CodeModel::Small && Offset < 16*1024*1024)
2394     return true;
2395
2396   // For kernel code model we know that all object resist in the negative half
2397   // of 32bits address space. We may not accept negative offsets, since they may
2398   // be just off and we may accept pretty large positive ones.
2399   if (M == CodeModel::Kernel && Offset > 0)
2400     return true;
2401
2402   return false;
2403 }
2404
2405 /// TranslateX86CC - do a one to one translation of a ISD::CondCode to the X86
2406 /// specific condition code, returning the condition code and the LHS/RHS of the
2407 /// comparison to make.
2408 static unsigned TranslateX86CC(ISD::CondCode SetCCOpcode, bool isFP,
2409                                SDValue &LHS, SDValue &RHS, SelectionDAG &DAG) {
2410   if (!isFP) {
2411     if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) {
2412       if (SetCCOpcode == ISD::SETGT && RHSC->isAllOnesValue()) {
2413         // X > -1   -> X == 0, jump !sign.
2414         RHS = DAG.getConstant(0, RHS.getValueType());
2415         return X86::COND_NS;
2416       } else if (SetCCOpcode == ISD::SETLT && RHSC->isNullValue()) {
2417         // X < 0   -> X == 0, jump on sign.
2418         return X86::COND_S;
2419       } else if (SetCCOpcode == ISD::SETLT && RHSC->getZExtValue() == 1) {
2420         // X < 1   -> X <= 0
2421         RHS = DAG.getConstant(0, RHS.getValueType());
2422         return X86::COND_LE;
2423       }
2424     }
2425
2426     switch (SetCCOpcode) {
2427     default: llvm_unreachable("Invalid integer condition!");
2428     case ISD::SETEQ:  return X86::COND_E;
2429     case ISD::SETGT:  return X86::COND_G;
2430     case ISD::SETGE:  return X86::COND_GE;
2431     case ISD::SETLT:  return X86::COND_L;
2432     case ISD::SETLE:  return X86::COND_LE;
2433     case ISD::SETNE:  return X86::COND_NE;
2434     case ISD::SETULT: return X86::COND_B;
2435     case ISD::SETUGT: return X86::COND_A;
2436     case ISD::SETULE: return X86::COND_BE;
2437     case ISD::SETUGE: return X86::COND_AE;
2438     }
2439   }
2440
2441   // First determine if it is required or is profitable to flip the operands.
2442
2443   // If LHS is a foldable load, but RHS is not, flip the condition.
2444   if ((ISD::isNON_EXTLoad(LHS.getNode()) && LHS.hasOneUse()) &&
2445       !(ISD::isNON_EXTLoad(RHS.getNode()) && RHS.hasOneUse())) {
2446     SetCCOpcode = getSetCCSwappedOperands(SetCCOpcode);
2447     std::swap(LHS, RHS);
2448   }
2449
2450   switch (SetCCOpcode) {
2451   default: break;
2452   case ISD::SETOLT:
2453   case ISD::SETOLE:
2454   case ISD::SETUGT:
2455   case ISD::SETUGE:
2456     std::swap(LHS, RHS);
2457     break;
2458   }
2459
2460   // On a floating point condition, the flags are set as follows:
2461   // ZF  PF  CF   op
2462   //  0 | 0 | 0 | X > Y
2463   //  0 | 0 | 1 | X < Y
2464   //  1 | 0 | 0 | X == Y
2465   //  1 | 1 | 1 | unordered
2466   switch (SetCCOpcode) {
2467   default: llvm_unreachable("Condcode should be pre-legalized away");
2468   case ISD::SETUEQ:
2469   case ISD::SETEQ:   return X86::COND_E;
2470   case ISD::SETOLT:              // flipped
2471   case ISD::SETOGT:
2472   case ISD::SETGT:   return X86::COND_A;
2473   case ISD::SETOLE:              // flipped
2474   case ISD::SETOGE:
2475   case ISD::SETGE:   return X86::COND_AE;
2476   case ISD::SETUGT:              // flipped
2477   case ISD::SETULT:
2478   case ISD::SETLT:   return X86::COND_B;
2479   case ISD::SETUGE:              // flipped
2480   case ISD::SETULE:
2481   case ISD::SETLE:   return X86::COND_BE;
2482   case ISD::SETONE:
2483   case ISD::SETNE:   return X86::COND_NE;
2484   case ISD::SETUO:   return X86::COND_P;
2485   case ISD::SETO:    return X86::COND_NP;
2486   case ISD::SETOEQ:
2487   case ISD::SETUNE:  return X86::COND_INVALID;
2488   }
2489 }
2490
2491 /// hasFPCMov - is there a floating point cmov for the specific X86 condition
2492 /// code. Current x86 isa includes the following FP cmov instructions:
2493 /// fcmovb, fcomvbe, fcomve, fcmovu, fcmovae, fcmova, fcmovne, fcmovnu.
2494 static bool hasFPCMov(unsigned X86CC) {
2495   switch (X86CC) {
2496   default:
2497     return false;
2498   case X86::COND_B:
2499   case X86::COND_BE:
2500   case X86::COND_E:
2501   case X86::COND_P:
2502   case X86::COND_A:
2503   case X86::COND_AE:
2504   case X86::COND_NE:
2505   case X86::COND_NP:
2506     return true;
2507   }
2508 }
2509
2510 /// isFPImmLegal - Returns true if the target can instruction select the
2511 /// specified FP immediate natively. If false, the legalizer will
2512 /// materialize the FP immediate as a load from a constant pool.
2513 bool X86TargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
2514   for (unsigned i = 0, e = LegalFPImmediates.size(); i != e; ++i) {
2515     if (Imm.bitwiseIsEqual(LegalFPImmediates[i]))
2516       return true;
2517   }
2518   return false;
2519 }
2520
2521 /// isUndefOrInRange - Return true if Val is undef or if its value falls within
2522 /// the specified range (L, H].
2523 static bool isUndefOrInRange(int Val, int Low, int Hi) {
2524   return (Val < 0) || (Val >= Low && Val < Hi);
2525 }
2526
2527 /// isUndefOrEqual - Val is either less than zero (undef) or equal to the
2528 /// specified value.
2529 static bool isUndefOrEqual(int Val, int CmpVal) {
2530   if (Val < 0 || Val == CmpVal)
2531     return true;
2532   return false;
2533 }
2534
2535 /// isPSHUFDMask - Return true if the node specifies a shuffle of elements that
2536 /// is suitable for input to PSHUFD or PSHUFW.  That is, it doesn't reference
2537 /// the second operand.
2538 static bool isPSHUFDMask(const SmallVectorImpl<int> &Mask, EVT VT) {
2539   if (VT == MVT::v4f32 || VT == MVT::v4i32 || VT == MVT::v4i16)
2540     return (Mask[0] < 4 && Mask[1] < 4 && Mask[2] < 4 && Mask[3] < 4);
2541   if (VT == MVT::v2f64 || VT == MVT::v2i64)
2542     return (Mask[0] < 2 && Mask[1] < 2);
2543   return false;
2544 }
2545
2546 bool X86::isPSHUFDMask(ShuffleVectorSDNode *N) {
2547   SmallVector<int, 8> M;
2548   N->getMask(M);
2549   return ::isPSHUFDMask(M, N->getValueType(0));
2550 }
2551
2552 /// isPSHUFHWMask - Return true if the node specifies a shuffle of elements that
2553 /// is suitable for input to PSHUFHW.
2554 static bool isPSHUFHWMask(const SmallVectorImpl<int> &Mask, EVT VT) {
2555   if (VT != MVT::v8i16)
2556     return false;
2557
2558   // Lower quadword copied in order or undef.
2559   for (int i = 0; i != 4; ++i)
2560     if (Mask[i] >= 0 && Mask[i] != i)
2561       return false;
2562
2563   // Upper quadword shuffled.
2564   for (int i = 4; i != 8; ++i)
2565     if (Mask[i] >= 0 && (Mask[i] < 4 || Mask[i] > 7))
2566       return false;
2567
2568   return true;
2569 }
2570
2571 bool X86::isPSHUFHWMask(ShuffleVectorSDNode *N) {
2572   SmallVector<int, 8> M;
2573   N->getMask(M);
2574   return ::isPSHUFHWMask(M, N->getValueType(0));
2575 }
2576
2577 /// isPSHUFLWMask - Return true if the node specifies a shuffle of elements that
2578 /// is suitable for input to PSHUFLW.
2579 static bool isPSHUFLWMask(const SmallVectorImpl<int> &Mask, EVT VT) {
2580   if (VT != MVT::v8i16)
2581     return false;
2582
2583   // Upper quadword copied in order.
2584   for (int i = 4; i != 8; ++i)
2585     if (Mask[i] >= 0 && Mask[i] != i)
2586       return false;
2587
2588   // Lower quadword shuffled.
2589   for (int i = 0; i != 4; ++i)
2590     if (Mask[i] >= 4)
2591       return false;
2592
2593   return true;
2594 }
2595
2596 bool X86::isPSHUFLWMask(ShuffleVectorSDNode *N) {
2597   SmallVector<int, 8> M;
2598   N->getMask(M);
2599   return ::isPSHUFLWMask(M, N->getValueType(0));
2600 }
2601
2602 /// isPALIGNRMask - Return true if the node specifies a shuffle of elements that
2603 /// is suitable for input to PALIGNR.
2604 static bool isPALIGNRMask(const SmallVectorImpl<int> &Mask, EVT VT,
2605                           bool hasSSSE3) {
2606   int i, e = VT.getVectorNumElements();
2607   
2608   // Do not handle v2i64 / v2f64 shuffles with palignr.
2609   if (e < 4 || !hasSSSE3)
2610     return false;
2611   
2612   for (i = 0; i != e; ++i)
2613     if (Mask[i] >= 0)
2614       break;
2615   
2616   // All undef, not a palignr.
2617   if (i == e)
2618     return false;
2619
2620   // Determine if it's ok to perform a palignr with only the LHS, since we
2621   // don't have access to the actual shuffle elements to see if RHS is undef.
2622   bool Unary = Mask[i] < (int)e;
2623   bool NeedsUnary = false;
2624
2625   int s = Mask[i] - i;
2626   
2627   // Check the rest of the elements to see if they are consecutive.
2628   for (++i; i != e; ++i) {
2629     int m = Mask[i];
2630     if (m < 0) 
2631       continue;
2632     
2633     Unary = Unary && (m < (int)e);
2634     NeedsUnary = NeedsUnary || (m < s);
2635
2636     if (NeedsUnary && !Unary)
2637       return false;
2638     if (Unary && m != ((s+i) & (e-1)))
2639       return false;
2640     if (!Unary && m != (s+i))
2641       return false;
2642   }
2643   return true;
2644 }
2645
2646 bool X86::isPALIGNRMask(ShuffleVectorSDNode *N) {
2647   SmallVector<int, 8> M;
2648   N->getMask(M);
2649   return ::isPALIGNRMask(M, N->getValueType(0), true);
2650 }
2651
2652 /// isSHUFPMask - Return true if the specified VECTOR_SHUFFLE operand
2653 /// specifies a shuffle of elements that is suitable for input to SHUFP*.
2654 static bool isSHUFPMask(const SmallVectorImpl<int> &Mask, EVT VT) {
2655   int NumElems = VT.getVectorNumElements();
2656   if (NumElems != 2 && NumElems != 4)
2657     return false;
2658
2659   int Half = NumElems / 2;
2660   for (int i = 0; i < Half; ++i)
2661     if (!isUndefOrInRange(Mask[i], 0, NumElems))
2662       return false;
2663   for (int i = Half; i < NumElems; ++i)
2664     if (!isUndefOrInRange(Mask[i], NumElems, NumElems*2))
2665       return false;
2666
2667   return true;
2668 }
2669
2670 bool X86::isSHUFPMask(ShuffleVectorSDNode *N) {
2671   SmallVector<int, 8> M;
2672   N->getMask(M);
2673   return ::isSHUFPMask(M, N->getValueType(0));
2674 }
2675
2676 /// isCommutedSHUFP - Returns true if the shuffle mask is exactly
2677 /// the reverse of what x86 shuffles want. x86 shuffles requires the lower
2678 /// half elements to come from vector 1 (which would equal the dest.) and
2679 /// the upper half to come from vector 2.
2680 static bool isCommutedSHUFPMask(const SmallVectorImpl<int> &Mask, EVT VT) {
2681   int NumElems = VT.getVectorNumElements();
2682
2683   if (NumElems != 2 && NumElems != 4)
2684     return false;
2685
2686   int Half = NumElems / 2;
2687   for (int i = 0; i < Half; ++i)
2688     if (!isUndefOrInRange(Mask[i], NumElems, NumElems*2))
2689       return false;
2690   for (int i = Half; i < NumElems; ++i)
2691     if (!isUndefOrInRange(Mask[i], 0, NumElems))
2692       return false;
2693   return true;
2694 }
2695
2696 static bool isCommutedSHUFP(ShuffleVectorSDNode *N) {
2697   SmallVector<int, 8> M;
2698   N->getMask(M);
2699   return isCommutedSHUFPMask(M, N->getValueType(0));
2700 }
2701
2702 /// isMOVHLPSMask - Return true if the specified VECTOR_SHUFFLE operand
2703 /// specifies a shuffle of elements that is suitable for input to MOVHLPS.
2704 bool X86::isMOVHLPSMask(ShuffleVectorSDNode *N) {
2705   if (N->getValueType(0).getVectorNumElements() != 4)
2706     return false;
2707
2708   // Expect bit0 == 6, bit1 == 7, bit2 == 2, bit3 == 3
2709   return isUndefOrEqual(N->getMaskElt(0), 6) &&
2710          isUndefOrEqual(N->getMaskElt(1), 7) &&
2711          isUndefOrEqual(N->getMaskElt(2), 2) &&
2712          isUndefOrEqual(N->getMaskElt(3), 3);
2713 }
2714
2715 /// isMOVHLPS_v_undef_Mask - Special case of isMOVHLPSMask for canonical form
2716 /// of vector_shuffle v, v, <2, 3, 2, 3>, i.e. vector_shuffle v, undef,
2717 /// <2, 3, 2, 3>
2718 bool X86::isMOVHLPS_v_undef_Mask(ShuffleVectorSDNode *N) {
2719   unsigned NumElems = N->getValueType(0).getVectorNumElements();
2720   
2721   if (NumElems != 4)
2722     return false;
2723   
2724   return isUndefOrEqual(N->getMaskElt(0), 2) &&
2725   isUndefOrEqual(N->getMaskElt(1), 3) &&
2726   isUndefOrEqual(N->getMaskElt(2), 2) &&
2727   isUndefOrEqual(N->getMaskElt(3), 3);
2728 }
2729
2730 /// isMOVLPMask - Return true if the specified VECTOR_SHUFFLE operand
2731 /// specifies a shuffle of elements that is suitable for input to MOVLP{S|D}.
2732 bool X86::isMOVLPMask(ShuffleVectorSDNode *N) {
2733   unsigned NumElems = N->getValueType(0).getVectorNumElements();
2734
2735   if (NumElems != 2 && NumElems != 4)
2736     return false;
2737
2738   for (unsigned i = 0; i < NumElems/2; ++i)
2739     if (!isUndefOrEqual(N->getMaskElt(i), i + NumElems))
2740       return false;
2741
2742   for (unsigned i = NumElems/2; i < NumElems; ++i)
2743     if (!isUndefOrEqual(N->getMaskElt(i), i))
2744       return false;
2745
2746   return true;
2747 }
2748
2749 /// isMOVLHPSMask - Return true if the specified VECTOR_SHUFFLE operand
2750 /// specifies a shuffle of elements that is suitable for input to MOVLHPS.
2751 bool X86::isMOVLHPSMask(ShuffleVectorSDNode *N) {
2752   unsigned NumElems = N->getValueType(0).getVectorNumElements();
2753
2754   if (NumElems != 2 && NumElems != 4)
2755     return false;
2756
2757   for (unsigned i = 0; i < NumElems/2; ++i)
2758     if (!isUndefOrEqual(N->getMaskElt(i), i))
2759       return false;
2760
2761   for (unsigned i = 0; i < NumElems/2; ++i)
2762     if (!isUndefOrEqual(N->getMaskElt(i + NumElems/2), i + NumElems))
2763       return false;
2764
2765   return true;
2766 }
2767
2768 /// isUNPCKLMask - Return true if the specified VECTOR_SHUFFLE operand
2769 /// specifies a shuffle of elements that is suitable for input to UNPCKL.
2770 static bool isUNPCKLMask(const SmallVectorImpl<int> &Mask, EVT VT,
2771                          bool V2IsSplat = false) {
2772   int NumElts = VT.getVectorNumElements();
2773   if (NumElts != 2 && NumElts != 4 && NumElts != 8 && NumElts != 16)
2774     return false;
2775
2776   for (int i = 0, j = 0; i != NumElts; i += 2, ++j) {
2777     int BitI  = Mask[i];
2778     int BitI1 = Mask[i+1];
2779     if (!isUndefOrEqual(BitI, j))
2780       return false;
2781     if (V2IsSplat) {
2782       if (!isUndefOrEqual(BitI1, NumElts))
2783         return false;
2784     } else {
2785       if (!isUndefOrEqual(BitI1, j + NumElts))
2786         return false;
2787     }
2788   }
2789   return true;
2790 }
2791
2792 bool X86::isUNPCKLMask(ShuffleVectorSDNode *N, bool V2IsSplat) {
2793   SmallVector<int, 8> M;
2794   N->getMask(M);
2795   return ::isUNPCKLMask(M, N->getValueType(0), V2IsSplat);
2796 }
2797
2798 /// isUNPCKHMask - Return true if the specified VECTOR_SHUFFLE operand
2799 /// specifies a shuffle of elements that is suitable for input to UNPCKH.
2800 static bool isUNPCKHMask(const SmallVectorImpl<int> &Mask, EVT VT,
2801                          bool V2IsSplat = false) {
2802   int NumElts = VT.getVectorNumElements();
2803   if (NumElts != 2 && NumElts != 4 && NumElts != 8 && NumElts != 16)
2804     return false;
2805
2806   for (int i = 0, j = 0; i != NumElts; i += 2, ++j) {
2807     int BitI  = Mask[i];
2808     int BitI1 = Mask[i+1];
2809     if (!isUndefOrEqual(BitI, j + NumElts/2))
2810       return false;
2811     if (V2IsSplat) {
2812       if (isUndefOrEqual(BitI1, NumElts))
2813         return false;
2814     } else {
2815       if (!isUndefOrEqual(BitI1, j + NumElts/2 + NumElts))
2816         return false;
2817     }
2818   }
2819   return true;
2820 }
2821
2822 bool X86::isUNPCKHMask(ShuffleVectorSDNode *N, bool V2IsSplat) {
2823   SmallVector<int, 8> M;
2824   N->getMask(M);
2825   return ::isUNPCKHMask(M, N->getValueType(0), V2IsSplat);
2826 }
2827
2828 /// isUNPCKL_v_undef_Mask - Special case of isUNPCKLMask for canonical form
2829 /// of vector_shuffle v, v, <0, 4, 1, 5>, i.e. vector_shuffle v, undef,
2830 /// <0, 0, 1, 1>
2831 static bool isUNPCKL_v_undef_Mask(const SmallVectorImpl<int> &Mask, EVT VT) {
2832   int NumElems = VT.getVectorNumElements();
2833   if (NumElems != 2 && NumElems != 4 && NumElems != 8 && NumElems != 16)
2834     return false;
2835
2836   for (int i = 0, j = 0; i != NumElems; i += 2, ++j) {
2837     int BitI  = Mask[i];
2838     int BitI1 = Mask[i+1];
2839     if (!isUndefOrEqual(BitI, j))
2840       return false;
2841     if (!isUndefOrEqual(BitI1, j))
2842       return false;
2843   }
2844   return true;
2845 }
2846
2847 bool X86::isUNPCKL_v_undef_Mask(ShuffleVectorSDNode *N) {
2848   SmallVector<int, 8> M;
2849   N->getMask(M);
2850   return ::isUNPCKL_v_undef_Mask(M, N->getValueType(0));
2851 }
2852
2853 /// isUNPCKH_v_undef_Mask - Special case of isUNPCKHMask for canonical form
2854 /// of vector_shuffle v, v, <2, 6, 3, 7>, i.e. vector_shuffle v, undef,
2855 /// <2, 2, 3, 3>
2856 static bool isUNPCKH_v_undef_Mask(const SmallVectorImpl<int> &Mask, EVT VT) {
2857   int NumElems = VT.getVectorNumElements();
2858   if (NumElems != 2 && NumElems != 4 && NumElems != 8 && NumElems != 16)
2859     return false;
2860
2861   for (int i = 0, j = NumElems / 2; i != NumElems; i += 2, ++j) {
2862     int BitI  = Mask[i];
2863     int BitI1 = Mask[i+1];
2864     if (!isUndefOrEqual(BitI, j))
2865       return false;
2866     if (!isUndefOrEqual(BitI1, j))
2867       return false;
2868   }
2869   return true;
2870 }
2871
2872 bool X86::isUNPCKH_v_undef_Mask(ShuffleVectorSDNode *N) {
2873   SmallVector<int, 8> M;
2874   N->getMask(M);
2875   return ::isUNPCKH_v_undef_Mask(M, N->getValueType(0));
2876 }
2877
2878 /// isMOVLMask - Return true if the specified VECTOR_SHUFFLE operand
2879 /// specifies a shuffle of elements that is suitable for input to MOVSS,
2880 /// MOVSD, and MOVD, i.e. setting the lowest element.
2881 static bool isMOVLMask(const SmallVectorImpl<int> &Mask, EVT VT) {
2882   if (VT.getVectorElementType().getSizeInBits() < 32)
2883     return false;
2884
2885   int NumElts = VT.getVectorNumElements();
2886
2887   if (!isUndefOrEqual(Mask[0], NumElts))
2888     return false;
2889
2890   for (int i = 1; i < NumElts; ++i)
2891     if (!isUndefOrEqual(Mask[i], i))
2892       return false;
2893
2894   return true;
2895 }
2896
2897 bool X86::isMOVLMask(ShuffleVectorSDNode *N) {
2898   SmallVector<int, 8> M;
2899   N->getMask(M);
2900   return ::isMOVLMask(M, N->getValueType(0));
2901 }
2902
2903 /// isCommutedMOVL - Returns true if the shuffle mask is except the reverse
2904 /// of what x86 movss want. X86 movs requires the lowest  element to be lowest
2905 /// element of vector 2 and the other elements to come from vector 1 in order.
2906 static bool isCommutedMOVLMask(const SmallVectorImpl<int> &Mask, EVT VT,
2907                                bool V2IsSplat = false, bool V2IsUndef = false) {
2908   int NumOps = VT.getVectorNumElements();
2909   if (NumOps != 2 && NumOps != 4 && NumOps != 8 && NumOps != 16)
2910     return false;
2911
2912   if (!isUndefOrEqual(Mask[0], 0))
2913     return false;
2914
2915   for (int i = 1; i < NumOps; ++i)
2916     if (!(isUndefOrEqual(Mask[i], i+NumOps) ||
2917           (V2IsUndef && isUndefOrInRange(Mask[i], NumOps, NumOps*2)) ||
2918           (V2IsSplat && isUndefOrEqual(Mask[i], NumOps))))
2919       return false;
2920
2921   return true;
2922 }
2923
2924 static bool isCommutedMOVL(ShuffleVectorSDNode *N, bool V2IsSplat = false,
2925                            bool V2IsUndef = false) {
2926   SmallVector<int, 8> M;
2927   N->getMask(M);
2928   return isCommutedMOVLMask(M, N->getValueType(0), V2IsSplat, V2IsUndef);
2929 }
2930
2931 /// isMOVSHDUPMask - Return true if the specified VECTOR_SHUFFLE operand
2932 /// specifies a shuffle of elements that is suitable for input to MOVSHDUP.
2933 bool X86::isMOVSHDUPMask(ShuffleVectorSDNode *N) {
2934   if (N->getValueType(0).getVectorNumElements() != 4)
2935     return false;
2936
2937   // Expect 1, 1, 3, 3
2938   for (unsigned i = 0; i < 2; ++i) {
2939     int Elt = N->getMaskElt(i);
2940     if (Elt >= 0 && Elt != 1)
2941       return false;
2942   }
2943
2944   bool HasHi = false;
2945   for (unsigned i = 2; i < 4; ++i) {
2946     int Elt = N->getMaskElt(i);
2947     if (Elt >= 0 && Elt != 3)
2948       return false;
2949     if (Elt == 3)
2950       HasHi = true;
2951   }
2952   // Don't use movshdup if it can be done with a shufps.
2953   // FIXME: verify that matching u, u, 3, 3 is what we want.
2954   return HasHi;
2955 }
2956
2957 /// isMOVSLDUPMask - Return true if the specified VECTOR_SHUFFLE operand
2958 /// specifies a shuffle of elements that is suitable for input to MOVSLDUP.
2959 bool X86::isMOVSLDUPMask(ShuffleVectorSDNode *N) {
2960   if (N->getValueType(0).getVectorNumElements() != 4)
2961     return false;
2962
2963   // Expect 0, 0, 2, 2
2964   for (unsigned i = 0; i < 2; ++i)
2965     if (N->getMaskElt(i) > 0)
2966       return false;
2967
2968   bool HasHi = false;
2969   for (unsigned i = 2; i < 4; ++i) {
2970     int Elt = N->getMaskElt(i);
2971     if (Elt >= 0 && Elt != 2)
2972       return false;
2973     if (Elt == 2)
2974       HasHi = true;
2975   }
2976   // Don't use movsldup if it can be done with a shufps.
2977   return HasHi;
2978 }
2979
2980 /// isMOVDDUPMask - Return true if the specified VECTOR_SHUFFLE operand
2981 /// specifies a shuffle of elements that is suitable for input to MOVDDUP.
2982 bool X86::isMOVDDUPMask(ShuffleVectorSDNode *N) {
2983   int e = N->getValueType(0).getVectorNumElements() / 2;
2984
2985   for (int i = 0; i < e; ++i)
2986     if (!isUndefOrEqual(N->getMaskElt(i), i))
2987       return false;
2988   for (int i = 0; i < e; ++i)
2989     if (!isUndefOrEqual(N->getMaskElt(e+i), i))
2990       return false;
2991   return true;
2992 }
2993
2994 /// getShuffleSHUFImmediate - Return the appropriate immediate to shuffle
2995 /// the specified VECTOR_SHUFFLE mask with PSHUF* and SHUFP* instructions.
2996 unsigned X86::getShuffleSHUFImmediate(SDNode *N) {
2997   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
2998   int NumOperands = SVOp->getValueType(0).getVectorNumElements();
2999
3000   unsigned Shift = (NumOperands == 4) ? 2 : 1;
3001   unsigned Mask = 0;
3002   for (int i = 0; i < NumOperands; ++i) {
3003     int Val = SVOp->getMaskElt(NumOperands-i-1);
3004     if (Val < 0) Val = 0;
3005     if (Val >= NumOperands) Val -= NumOperands;
3006     Mask |= Val;
3007     if (i != NumOperands - 1)
3008       Mask <<= Shift;
3009   }
3010   return Mask;
3011 }
3012
3013 /// getShufflePSHUFHWImmediate - Return the appropriate immediate to shuffle
3014 /// the specified VECTOR_SHUFFLE mask with the PSHUFHW instruction.
3015 unsigned X86::getShufflePSHUFHWImmediate(SDNode *N) {
3016   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
3017   unsigned Mask = 0;
3018   // 8 nodes, but we only care about the last 4.
3019   for (unsigned i = 7; i >= 4; --i) {
3020     int Val = SVOp->getMaskElt(i);
3021     if (Val >= 0)
3022       Mask |= (Val - 4);
3023     if (i != 4)
3024       Mask <<= 2;
3025   }
3026   return Mask;
3027 }
3028
3029 /// getShufflePSHUFLWImmediate - Return the appropriate immediate to shuffle
3030 /// the specified VECTOR_SHUFFLE mask with the PSHUFLW instruction.
3031 unsigned X86::getShufflePSHUFLWImmediate(SDNode *N) {
3032   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
3033   unsigned Mask = 0;
3034   // 8 nodes, but we only care about the first 4.
3035   for (int i = 3; i >= 0; --i) {
3036     int Val = SVOp->getMaskElt(i);
3037     if (Val >= 0)
3038       Mask |= Val;
3039     if (i != 0)
3040       Mask <<= 2;
3041   }
3042   return Mask;
3043 }
3044
3045 /// getShufflePALIGNRImmediate - Return the appropriate immediate to shuffle
3046 /// the specified VECTOR_SHUFFLE mask with the PALIGNR instruction.
3047 unsigned X86::getShufflePALIGNRImmediate(SDNode *N) {
3048   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
3049   EVT VVT = N->getValueType(0);
3050   unsigned EltSize = VVT.getVectorElementType().getSizeInBits() >> 3;
3051   int Val = 0;
3052
3053   unsigned i, e;
3054   for (i = 0, e = VVT.getVectorNumElements(); i != e; ++i) {
3055     Val = SVOp->getMaskElt(i);
3056     if (Val >= 0)
3057       break;
3058   }
3059   return (Val - i) * EltSize;
3060 }
3061
3062 /// isZeroNode - Returns true if Elt is a constant zero or a floating point
3063 /// constant +0.0.
3064 bool X86::isZeroNode(SDValue Elt) {
3065   return ((isa<ConstantSDNode>(Elt) &&
3066            cast<ConstantSDNode>(Elt)->getZExtValue() == 0) ||
3067           (isa<ConstantFPSDNode>(Elt) &&
3068            cast<ConstantFPSDNode>(Elt)->getValueAPF().isPosZero()));
3069 }
3070
3071 /// CommuteVectorShuffle - Swap vector_shuffle operands as well as values in
3072 /// their permute mask.
3073 static SDValue CommuteVectorShuffle(ShuffleVectorSDNode *SVOp,
3074                                     SelectionDAG &DAG) {
3075   EVT VT = SVOp->getValueType(0);
3076   unsigned NumElems = VT.getVectorNumElements();
3077   SmallVector<int, 8> MaskVec;
3078
3079   for (unsigned i = 0; i != NumElems; ++i) {
3080     int idx = SVOp->getMaskElt(i);
3081     if (idx < 0)
3082       MaskVec.push_back(idx);
3083     else if (idx < (int)NumElems)
3084       MaskVec.push_back(idx + NumElems);
3085     else
3086       MaskVec.push_back(idx - NumElems);
3087   }
3088   return DAG.getVectorShuffle(VT, SVOp->getDebugLoc(), SVOp->getOperand(1),
3089                               SVOp->getOperand(0), &MaskVec[0]);
3090 }
3091
3092 /// CommuteVectorShuffleMask - Change values in a shuffle permute mask assuming
3093 /// the two vector operands have swapped position.
3094 static void CommuteVectorShuffleMask(SmallVectorImpl<int> &Mask, EVT VT) {
3095   unsigned NumElems = VT.getVectorNumElements();
3096   for (unsigned i = 0; i != NumElems; ++i) {
3097     int idx = Mask[i];
3098     if (idx < 0)
3099       continue;
3100     else if (idx < (int)NumElems)
3101       Mask[i] = idx + NumElems;
3102     else
3103       Mask[i] = idx - NumElems;
3104   }
3105 }
3106
3107 /// ShouldXformToMOVHLPS - Return true if the node should be transformed to
3108 /// match movhlps. The lower half elements should come from upper half of
3109 /// V1 (and in order), and the upper half elements should come from the upper
3110 /// half of V2 (and in order).
3111 static bool ShouldXformToMOVHLPS(ShuffleVectorSDNode *Op) {
3112   if (Op->getValueType(0).getVectorNumElements() != 4)
3113     return false;
3114   for (unsigned i = 0, e = 2; i != e; ++i)
3115     if (!isUndefOrEqual(Op->getMaskElt(i), i+2))
3116       return false;
3117   for (unsigned i = 2; i != 4; ++i)
3118     if (!isUndefOrEqual(Op->getMaskElt(i), i+4))
3119       return false;
3120   return true;
3121 }
3122
3123 /// isScalarLoadToVector - Returns true if the node is a scalar load that
3124 /// is promoted to a vector. It also returns the LoadSDNode by reference if
3125 /// required.
3126 static bool isScalarLoadToVector(SDNode *N, LoadSDNode **LD = NULL) {
3127   if (N->getOpcode() != ISD::SCALAR_TO_VECTOR)
3128     return false;
3129   N = N->getOperand(0).getNode();
3130   if (!ISD::isNON_EXTLoad(N))
3131     return false;
3132   if (LD)
3133     *LD = cast<LoadSDNode>(N);
3134   return true;
3135 }
3136
3137 /// ShouldXformToMOVLP{S|D} - Return true if the node should be transformed to
3138 /// match movlp{s|d}. The lower half elements should come from lower half of
3139 /// V1 (and in order), and the upper half elements should come from the upper
3140 /// half of V2 (and in order). And since V1 will become the source of the
3141 /// MOVLP, it must be either a vector load or a scalar load to vector.
3142 static bool ShouldXformToMOVLP(SDNode *V1, SDNode *V2,
3143                                ShuffleVectorSDNode *Op) {
3144   if (!ISD::isNON_EXTLoad(V1) && !isScalarLoadToVector(V1))
3145     return false;
3146   // Is V2 is a vector load, don't do this transformation. We will try to use
3147   // load folding shufps op.
3148   if (ISD::isNON_EXTLoad(V2))
3149     return false;
3150
3151   unsigned NumElems = Op->getValueType(0).getVectorNumElements();
3152
3153   if (NumElems != 2 && NumElems != 4)
3154     return false;
3155   for (unsigned i = 0, e = NumElems/2; i != e; ++i)
3156     if (!isUndefOrEqual(Op->getMaskElt(i), i))
3157       return false;
3158   for (unsigned i = NumElems/2; i != NumElems; ++i)
3159     if (!isUndefOrEqual(Op->getMaskElt(i), i+NumElems))
3160       return false;
3161   return true;
3162 }
3163
3164 /// isSplatVector - Returns true if N is a BUILD_VECTOR node whose elements are
3165 /// all the same.
3166 static bool isSplatVector(SDNode *N) {
3167   if (N->getOpcode() != ISD::BUILD_VECTOR)
3168     return false;
3169
3170   SDValue SplatValue = N->getOperand(0);
3171   for (unsigned i = 1, e = N->getNumOperands(); i != e; ++i)
3172     if (N->getOperand(i) != SplatValue)
3173       return false;
3174   return true;
3175 }
3176
3177 /// isZeroShuffle - Returns true if N is a VECTOR_SHUFFLE that can be resolved
3178 /// to an zero vector.
3179 /// FIXME: move to dag combiner / method on ShuffleVectorSDNode
3180 static bool isZeroShuffle(ShuffleVectorSDNode *N) {
3181   SDValue V1 = N->getOperand(0);
3182   SDValue V2 = N->getOperand(1);
3183   unsigned NumElems = N->getValueType(0).getVectorNumElements();
3184   for (unsigned i = 0; i != NumElems; ++i) {
3185     int Idx = N->getMaskElt(i);
3186     if (Idx >= (int)NumElems) {
3187       unsigned Opc = V2.getOpcode();
3188       if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V2.getNode()))
3189         continue;
3190       if (Opc != ISD::BUILD_VECTOR ||
3191           !X86::isZeroNode(V2.getOperand(Idx-NumElems)))
3192         return false;
3193     } else if (Idx >= 0) {
3194       unsigned Opc = V1.getOpcode();
3195       if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V1.getNode()))
3196         continue;
3197       if (Opc != ISD::BUILD_VECTOR ||
3198           !X86::isZeroNode(V1.getOperand(Idx)))
3199         return false;
3200     }
3201   }
3202   return true;
3203 }
3204
3205 /// getZeroVector - Returns a vector of specified type with all zero elements.
3206 ///
3207 static SDValue getZeroVector(EVT VT, bool HasSSE2, SelectionDAG &DAG,
3208                              DebugLoc dl) {
3209   assert(VT.isVector() && "Expected a vector type");
3210
3211   // Always build zero vectors as <4 x i32> or <2 x i32> bitcasted to their dest
3212   // type.  This ensures they get CSE'd.
3213   SDValue Vec;
3214   if (VT.getSizeInBits() == 64) { // MMX
3215     SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
3216     Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v2i32, Cst, Cst);
3217   } else if (HasSSE2) {  // SSE2
3218     SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
3219     Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
3220   } else { // SSE1
3221     SDValue Cst = DAG.getTargetConstantFP(+0.0, MVT::f32);
3222     Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4f32, Cst, Cst, Cst, Cst);
3223   }
3224   return DAG.getNode(ISD::BIT_CONVERT, dl, VT, Vec);
3225 }
3226
3227 /// getOnesVector - Returns a vector of specified type with all bits set.
3228 ///
3229 static SDValue getOnesVector(EVT VT, SelectionDAG &DAG, DebugLoc dl) {
3230   assert(VT.isVector() && "Expected a vector type");
3231
3232   // Always build ones vectors as <4 x i32> or <2 x i32> bitcasted to their dest
3233   // type.  This ensures they get CSE'd.
3234   SDValue Cst = DAG.getTargetConstant(~0U, MVT::i32);
3235   SDValue Vec;
3236   if (VT.getSizeInBits() == 64)  // MMX
3237     Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v2i32, Cst, Cst);
3238   else                                              // SSE
3239     Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
3240   return DAG.getNode(ISD::BIT_CONVERT, dl, VT, Vec);
3241 }
3242
3243
3244 /// NormalizeMask - V2 is a splat, modify the mask (if needed) so all elements
3245 /// that point to V2 points to its first element.
3246 static SDValue NormalizeMask(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
3247   EVT VT = SVOp->getValueType(0);
3248   unsigned NumElems = VT.getVectorNumElements();
3249
3250   bool Changed = false;
3251   SmallVector<int, 8> MaskVec;
3252   SVOp->getMask(MaskVec);
3253
3254   for (unsigned i = 0; i != NumElems; ++i) {
3255     if (MaskVec[i] > (int)NumElems) {
3256       MaskVec[i] = NumElems;
3257       Changed = true;
3258     }
3259   }
3260   if (Changed)
3261     return DAG.getVectorShuffle(VT, SVOp->getDebugLoc(), SVOp->getOperand(0),
3262                                 SVOp->getOperand(1), &MaskVec[0]);
3263   return SDValue(SVOp, 0);
3264 }
3265
3266 /// getMOVLMask - Returns a vector_shuffle mask for an movs{s|d}, movd
3267 /// operation of specified width.
3268 static SDValue getMOVL(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
3269                        SDValue V2) {
3270   unsigned NumElems = VT.getVectorNumElements();
3271   SmallVector<int, 8> Mask;
3272   Mask.push_back(NumElems);
3273   for (unsigned i = 1; i != NumElems; ++i)
3274     Mask.push_back(i);
3275   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
3276 }
3277
3278 /// getUnpackl - Returns a vector_shuffle node for an unpackl operation.
3279 static SDValue getUnpackl(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
3280                           SDValue V2) {
3281   unsigned NumElems = VT.getVectorNumElements();
3282   SmallVector<int, 8> Mask;
3283   for (unsigned i = 0, e = NumElems/2; i != e; ++i) {
3284     Mask.push_back(i);
3285     Mask.push_back(i + NumElems);
3286   }
3287   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
3288 }
3289
3290 /// getUnpackhMask - Returns a vector_shuffle node for an unpackh operation.
3291 static SDValue getUnpackh(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
3292                           SDValue V2) {
3293   unsigned NumElems = VT.getVectorNumElements();
3294   unsigned Half = NumElems/2;
3295   SmallVector<int, 8> Mask;
3296   for (unsigned i = 0; i != Half; ++i) {
3297     Mask.push_back(i + Half);
3298     Mask.push_back(i + NumElems + Half);
3299   }
3300   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
3301 }
3302
3303 /// PromoteSplat - Promote a splat of v4f32, v8i16 or v16i8 to v4i32.
3304 static SDValue PromoteSplat(ShuffleVectorSDNode *SV, SelectionDAG &DAG,
3305                             bool HasSSE2) {
3306   if (SV->getValueType(0).getVectorNumElements() <= 4)
3307     return SDValue(SV, 0);
3308
3309   EVT PVT = MVT::v4f32;
3310   EVT VT = SV->getValueType(0);
3311   DebugLoc dl = SV->getDebugLoc();
3312   SDValue V1 = SV->getOperand(0);
3313   int NumElems = VT.getVectorNumElements();
3314   int EltNo = SV->getSplatIndex();
3315
3316   // unpack elements to the correct location
3317   while (NumElems > 4) {
3318     if (EltNo < NumElems/2) {
3319       V1 = getUnpackl(DAG, dl, VT, V1, V1);
3320     } else {
3321       V1 = getUnpackh(DAG, dl, VT, V1, V1);
3322       EltNo -= NumElems/2;
3323     }
3324     NumElems >>= 1;
3325   }
3326
3327   // Perform the splat.
3328   int SplatMask[4] = { EltNo, EltNo, EltNo, EltNo };
3329   V1 = DAG.getNode(ISD::BIT_CONVERT, dl, PVT, V1);
3330   V1 = DAG.getVectorShuffle(PVT, dl, V1, DAG.getUNDEF(PVT), &SplatMask[0]);
3331   return DAG.getNode(ISD::BIT_CONVERT, dl, VT, V1);
3332 }
3333
3334 /// getShuffleVectorZeroOrUndef - Return a vector_shuffle of the specified
3335 /// vector of zero or undef vector.  This produces a shuffle where the low
3336 /// element of V2 is swizzled into the zero/undef vector, landing at element
3337 /// Idx.  This produces a shuffle mask like 4,1,2,3 (idx=0) or  0,1,2,4 (idx=3).
3338 static SDValue getShuffleVectorZeroOrUndef(SDValue V2, unsigned Idx,
3339                                              bool isZero, bool HasSSE2,
3340                                              SelectionDAG &DAG) {
3341   EVT VT = V2.getValueType();
3342   SDValue V1 = isZero
3343     ? getZeroVector(VT, HasSSE2, DAG, V2.getDebugLoc()) : DAG.getUNDEF(VT);
3344   unsigned NumElems = VT.getVectorNumElements();
3345   SmallVector<int, 16> MaskVec;
3346   for (unsigned i = 0; i != NumElems; ++i)
3347     // If this is the insertion idx, put the low elt of V2 here.
3348     MaskVec.push_back(i == Idx ? NumElems : i);
3349   return DAG.getVectorShuffle(VT, V2.getDebugLoc(), V1, V2, &MaskVec[0]);
3350 }
3351
3352 /// getNumOfConsecutiveZeros - Return the number of elements in a result of
3353 /// a shuffle that is zero.
3354 static
3355 unsigned getNumOfConsecutiveZeros(ShuffleVectorSDNode *SVOp, int NumElems,
3356                                   bool Low, SelectionDAG &DAG) {
3357   unsigned NumZeros = 0;
3358   for (int i = 0; i < NumElems; ++i) {
3359     unsigned Index = Low ? i : NumElems-i-1;
3360     int Idx = SVOp->getMaskElt(Index);
3361     if (Idx < 0) {
3362       ++NumZeros;
3363       continue;
3364     }
3365     SDValue Elt = DAG.getShuffleScalarElt(SVOp, Index);
3366     if (Elt.getNode() && X86::isZeroNode(Elt))
3367       ++NumZeros;
3368     else
3369       break;
3370   }
3371   return NumZeros;
3372 }
3373
3374 /// isVectorShift - Returns true if the shuffle can be implemented as a
3375 /// logical left or right shift of a vector.
3376 /// FIXME: split into pslldqi, psrldqi, palignr variants.
3377 static bool isVectorShift(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
3378                           bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
3379   int NumElems = SVOp->getValueType(0).getVectorNumElements();
3380
3381   isLeft = true;
3382   unsigned NumZeros = getNumOfConsecutiveZeros(SVOp, NumElems, true, DAG);
3383   if (!NumZeros) {
3384     isLeft = false;
3385     NumZeros = getNumOfConsecutiveZeros(SVOp, NumElems, false, DAG);
3386     if (!NumZeros)
3387       return false;
3388   }
3389   bool SeenV1 = false;
3390   bool SeenV2 = false;
3391   for (int i = NumZeros; i < NumElems; ++i) {
3392     int Val = isLeft ? (i - NumZeros) : i;
3393     int Idx = SVOp->getMaskElt(isLeft ? i : (i - NumZeros));
3394     if (Idx < 0)
3395       continue;
3396     if (Idx < NumElems)
3397       SeenV1 = true;
3398     else {
3399       Idx -= NumElems;
3400       SeenV2 = true;
3401     }
3402     if (Idx != Val)
3403       return false;
3404   }
3405   if (SeenV1 && SeenV2)
3406     return false;
3407
3408   ShVal = SeenV1 ? SVOp->getOperand(0) : SVOp->getOperand(1);
3409   ShAmt = NumZeros;
3410   return true;
3411 }
3412
3413
3414 /// LowerBuildVectorv16i8 - Custom lower build_vector of v16i8.
3415 ///
3416 static SDValue LowerBuildVectorv16i8(SDValue Op, unsigned NonZeros,
3417                                        unsigned NumNonZero, unsigned NumZero,
3418                                        SelectionDAG &DAG, TargetLowering &TLI) {
3419   if (NumNonZero > 8)
3420     return SDValue();
3421
3422   DebugLoc dl = Op.getDebugLoc();
3423   SDValue V(0, 0);
3424   bool First = true;
3425   for (unsigned i = 0; i < 16; ++i) {
3426     bool ThisIsNonZero = (NonZeros & (1 << i)) != 0;
3427     if (ThisIsNonZero && First) {
3428       if (NumZero)
3429         V = getZeroVector(MVT::v8i16, true, DAG, dl);
3430       else
3431         V = DAG.getUNDEF(MVT::v8i16);
3432       First = false;
3433     }
3434
3435     if ((i & 1) != 0) {
3436       SDValue ThisElt(0, 0), LastElt(0, 0);
3437       bool LastIsNonZero = (NonZeros & (1 << (i-1))) != 0;
3438       if (LastIsNonZero) {
3439         LastElt = DAG.getNode(ISD::ZERO_EXTEND, dl,
3440                               MVT::i16, Op.getOperand(i-1));
3441       }
3442       if (ThisIsNonZero) {
3443         ThisElt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i16, Op.getOperand(i));
3444         ThisElt = DAG.getNode(ISD::SHL, dl, MVT::i16,
3445                               ThisElt, DAG.getConstant(8, MVT::i8));
3446         if (LastIsNonZero)
3447           ThisElt = DAG.getNode(ISD::OR, dl, MVT::i16, ThisElt, LastElt);
3448       } else
3449         ThisElt = LastElt;
3450
3451       if (ThisElt.getNode())
3452         V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, V, ThisElt,
3453                         DAG.getIntPtrConstant(i/2));
3454     }
3455   }
3456
3457   return DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v16i8, V);
3458 }
3459
3460 /// LowerBuildVectorv8i16 - Custom lower build_vector of v8i16.
3461 ///
3462 static SDValue LowerBuildVectorv8i16(SDValue Op, unsigned NonZeros,
3463                                        unsigned NumNonZero, unsigned NumZero,
3464                                        SelectionDAG &DAG, TargetLowering &TLI) {
3465   if (NumNonZero > 4)
3466     return SDValue();
3467
3468   DebugLoc dl = Op.getDebugLoc();
3469   SDValue V(0, 0);
3470   bool First = true;
3471   for (unsigned i = 0; i < 8; ++i) {
3472     bool isNonZero = (NonZeros & (1 << i)) != 0;
3473     if (isNonZero) {
3474       if (First) {
3475         if (NumZero)
3476           V = getZeroVector(MVT::v8i16, true, DAG, dl);
3477         else
3478           V = DAG.getUNDEF(MVT::v8i16);
3479         First = false;
3480       }
3481       V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl,
3482                       MVT::v8i16, V, Op.getOperand(i),
3483                       DAG.getIntPtrConstant(i));
3484     }
3485   }
3486
3487   return V;
3488 }
3489
3490 /// getVShift - Return a vector logical shift node.
3491 ///
3492 static SDValue getVShift(bool isLeft, EVT VT, SDValue SrcOp,
3493                          unsigned NumBits, SelectionDAG &DAG,
3494                          const TargetLowering &TLI, DebugLoc dl) {
3495   bool isMMX = VT.getSizeInBits() == 64;
3496   EVT ShVT = isMMX ? MVT::v1i64 : MVT::v2i64;
3497   unsigned Opc = isLeft ? X86ISD::VSHL : X86ISD::VSRL;
3498   SrcOp = DAG.getNode(ISD::BIT_CONVERT, dl, ShVT, SrcOp);
3499   return DAG.getNode(ISD::BIT_CONVERT, dl, VT,
3500                      DAG.getNode(Opc, dl, ShVT, SrcOp,
3501                              DAG.getConstant(NumBits, TLI.getShiftAmountTy())));
3502 }
3503
3504 SDValue
3505 X86TargetLowering::LowerAsSplatVectorLoad(SDValue SrcOp, EVT VT, DebugLoc dl,
3506                                           SelectionDAG &DAG) {
3507   
3508   // Check if the scalar load can be widened into a vector load. And if
3509   // the address is "base + cst" see if the cst can be "absorbed" into
3510   // the shuffle mask.
3511   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(SrcOp)) {
3512     SDValue Ptr = LD->getBasePtr();
3513     if (!ISD::isNormalLoad(LD) || LD->isVolatile())
3514       return SDValue();
3515     EVT PVT = LD->getValueType(0);
3516     if (PVT != MVT::i32 && PVT != MVT::f32)
3517       return SDValue();
3518
3519     int FI = -1;
3520     int64_t Offset = 0;
3521     if (FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr)) {
3522       FI = FINode->getIndex();
3523       Offset = 0;
3524     } else if (Ptr.getOpcode() == ISD::ADD &&
3525                isa<ConstantSDNode>(Ptr.getOperand(1)) &&
3526                isa<FrameIndexSDNode>(Ptr.getOperand(0))) {
3527       FI = cast<FrameIndexSDNode>(Ptr.getOperand(0))->getIndex();
3528       Offset = Ptr.getConstantOperandVal(1);
3529       Ptr = Ptr.getOperand(0);
3530     } else {
3531       return SDValue();
3532     }
3533
3534     SDValue Chain = LD->getChain();
3535     // Make sure the stack object alignment is at least 16.
3536     MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
3537     if (DAG.InferPtrAlignment(Ptr) < 16) {
3538       if (MFI->isFixedObjectIndex(FI)) {
3539         // Can't change the alignment. FIXME: It's possible to compute
3540         // the exact stack offset and reference FI + adjust offset instead.
3541         // If someone *really* cares about this. That's the way to implement it.
3542         return SDValue();
3543       } else {
3544         MFI->setObjectAlignment(FI, 16);
3545       }
3546     }
3547
3548     // (Offset % 16) must be multiple of 4. Then address is then
3549     // Ptr + (Offset & ~15).
3550     if (Offset < 0)
3551       return SDValue();
3552     if ((Offset % 16) & 3)
3553       return SDValue();
3554     int64_t StartOffset = Offset & ~15;
3555     if (StartOffset)
3556       Ptr = DAG.getNode(ISD::ADD, Ptr.getDebugLoc(), Ptr.getValueType(),
3557                         Ptr,DAG.getConstant(StartOffset, Ptr.getValueType()));
3558
3559     int EltNo = (Offset - StartOffset) >> 2;
3560     int Mask[4] = { EltNo, EltNo, EltNo, EltNo };
3561     EVT VT = (PVT == MVT::i32) ? MVT::v4i32 : MVT::v4f32;
3562     SDValue V1 = DAG.getLoad(VT, dl, Chain, Ptr,LD->getSrcValue(),0);
3563     // Canonicalize it to a v4i32 shuffle.
3564     V1 = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v4i32, V1);
3565     return DAG.getNode(ISD::BIT_CONVERT, dl, VT,
3566                        DAG.getVectorShuffle(MVT::v4i32, dl, V1,
3567                                             DAG.getUNDEF(MVT::v4i32), &Mask[0]));
3568   }
3569
3570   return SDValue();
3571 }
3572
3573 SDValue
3574 X86TargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG) {
3575   DebugLoc dl = Op.getDebugLoc();
3576   // All zero's are handled with pxor, all one's are handled with pcmpeqd.
3577   if (ISD::isBuildVectorAllZeros(Op.getNode())
3578       || ISD::isBuildVectorAllOnes(Op.getNode())) {
3579     // Canonicalize this to either <4 x i32> or <2 x i32> (SSE vs MMX) to
3580     // 1) ensure the zero vectors are CSE'd, and 2) ensure that i64 scalars are
3581     // eliminated on x86-32 hosts.
3582     if (Op.getValueType() == MVT::v4i32 || Op.getValueType() == MVT::v2i32)
3583       return Op;
3584
3585     if (ISD::isBuildVectorAllOnes(Op.getNode()))
3586       return getOnesVector(Op.getValueType(), DAG, dl);
3587     return getZeroVector(Op.getValueType(), Subtarget->hasSSE2(), DAG, dl);
3588   }
3589
3590   EVT VT = Op.getValueType();
3591   EVT ExtVT = VT.getVectorElementType();
3592   unsigned EVTBits = ExtVT.getSizeInBits();
3593
3594   unsigned NumElems = Op.getNumOperands();
3595   unsigned NumZero  = 0;
3596   unsigned NumNonZero = 0;
3597   unsigned NonZeros = 0;
3598   bool IsAllConstants = true;
3599   SmallSet<SDValue, 8> Values;
3600   for (unsigned i = 0; i < NumElems; ++i) {
3601     SDValue Elt = Op.getOperand(i);
3602     if (Elt.getOpcode() == ISD::UNDEF)
3603       continue;
3604     Values.insert(Elt);
3605     if (Elt.getOpcode() != ISD::Constant &&
3606         Elt.getOpcode() != ISD::ConstantFP)
3607       IsAllConstants = false;
3608     if (X86::isZeroNode(Elt))
3609       NumZero++;
3610     else {
3611       NonZeros |= (1 << i);
3612       NumNonZero++;
3613     }
3614   }
3615
3616   if (NumNonZero == 0) {
3617     // All undef vector. Return an UNDEF.  All zero vectors were handled above.
3618     return DAG.getUNDEF(VT);
3619   }
3620
3621   // Special case for single non-zero, non-undef, element.
3622   if (NumNonZero == 1) {
3623     unsigned Idx = CountTrailingZeros_32(NonZeros);
3624     SDValue Item = Op.getOperand(Idx);
3625
3626     // If this is an insertion of an i64 value on x86-32, and if the top bits of
3627     // the value are obviously zero, truncate the value to i32 and do the
3628     // insertion that way.  Only do this if the value is non-constant or if the
3629     // value is a constant being inserted into element 0.  It is cheaper to do
3630     // a constant pool load than it is to do a movd + shuffle.
3631     if (ExtVT == MVT::i64 && !Subtarget->is64Bit() &&
3632         (!IsAllConstants || Idx == 0)) {
3633       if (DAG.MaskedValueIsZero(Item, APInt::getBitsSet(64, 32, 64))) {
3634         // Handle MMX and SSE both.
3635         EVT VecVT = VT == MVT::v2i64 ? MVT::v4i32 : MVT::v2i32;
3636         unsigned VecElts = VT == MVT::v2i64 ? 4 : 2;
3637
3638         // Truncate the value (which may itself be a constant) to i32, and
3639         // convert it to a vector with movd (S2V+shuffle to zero extend).
3640         Item = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Item);
3641         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VecVT, Item);
3642         Item = getShuffleVectorZeroOrUndef(Item, 0, true,
3643                                            Subtarget->hasSSE2(), DAG);
3644
3645         // Now we have our 32-bit value zero extended in the low element of
3646         // a vector.  If Idx != 0, swizzle it into place.
3647         if (Idx != 0) {
3648           SmallVector<int, 4> Mask;
3649           Mask.push_back(Idx);
3650           for (unsigned i = 1; i != VecElts; ++i)
3651             Mask.push_back(i);
3652           Item = DAG.getVectorShuffle(VecVT, dl, Item,
3653                                       DAG.getUNDEF(Item.getValueType()),
3654                                       &Mask[0]);
3655         }
3656         return DAG.getNode(ISD::BIT_CONVERT, dl, Op.getValueType(), Item);
3657       }
3658     }
3659
3660     // If we have a constant or non-constant insertion into the low element of
3661     // a vector, we can do this with SCALAR_TO_VECTOR + shuffle of zero into
3662     // the rest of the elements.  This will be matched as movd/movq/movss/movsd
3663     // depending on what the source datatype is.
3664     if (Idx == 0) {
3665       if (NumZero == 0) {
3666         return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
3667       } else if (ExtVT == MVT::i32 || ExtVT == MVT::f32 || ExtVT == MVT::f64 ||
3668           (ExtVT == MVT::i64 && Subtarget->is64Bit())) {
3669         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
3670         // Turn it into a MOVL (i.e. movss, movsd, or movd) to a zero vector.
3671         return getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget->hasSSE2(),
3672                                            DAG);
3673       } else if (ExtVT == MVT::i16 || ExtVT == MVT::i8) {
3674         Item = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, Item);
3675         EVT MiddleVT = VT.getSizeInBits() == 64 ? MVT::v2i32 : MVT::v4i32;
3676         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MiddleVT, Item);
3677         Item = getShuffleVectorZeroOrUndef(Item, 0, true,
3678                                            Subtarget->hasSSE2(), DAG);
3679         return DAG.getNode(ISD::BIT_CONVERT, dl, VT, Item);
3680       }
3681     }
3682
3683     // Is it a vector logical left shift?
3684     if (NumElems == 2 && Idx == 1 &&
3685         X86::isZeroNode(Op.getOperand(0)) &&
3686         !X86::isZeroNode(Op.getOperand(1))) {
3687       unsigned NumBits = VT.getSizeInBits();
3688       return getVShift(true, VT,
3689                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
3690                                    VT, Op.getOperand(1)),
3691                        NumBits/2, DAG, *this, dl);
3692     }
3693
3694     if (IsAllConstants) // Otherwise, it's better to do a constpool load.
3695       return SDValue();
3696
3697     // Otherwise, if this is a vector with i32 or f32 elements, and the element
3698     // is a non-constant being inserted into an element other than the low one,
3699     // we can't use a constant pool load.  Instead, use SCALAR_TO_VECTOR (aka
3700     // movd/movss) to move this into the low element, then shuffle it into
3701     // place.
3702     if (EVTBits == 32) {
3703       Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
3704
3705       // Turn it into a shuffle of zero and zero-extended scalar to vector.
3706       Item = getShuffleVectorZeroOrUndef(Item, 0, NumZero > 0,
3707                                          Subtarget->hasSSE2(), DAG);
3708       SmallVector<int, 8> MaskVec;
3709       for (unsigned i = 0; i < NumElems; i++)
3710         MaskVec.push_back(i == Idx ? 0 : 1);
3711       return DAG.getVectorShuffle(VT, dl, Item, DAG.getUNDEF(VT), &MaskVec[0]);
3712     }
3713   }
3714
3715   // Splat is obviously ok. Let legalizer expand it to a shuffle.
3716   if (Values.size() == 1) {
3717     if (EVTBits == 32) {
3718       // Instead of a shuffle like this:
3719       // shuffle (scalar_to_vector (load (ptr + 4))), undef, <0, 0, 0, 0>
3720       // Check if it's possible to issue this instead.
3721       // shuffle (vload ptr)), undef, <1, 1, 1, 1>
3722       unsigned Idx = CountTrailingZeros_32(NonZeros);
3723       SDValue Item = Op.getOperand(Idx);
3724       if (Op.getNode()->isOnlyUserOf(Item.getNode()))
3725         return LowerAsSplatVectorLoad(Item, VT, dl, DAG);
3726     }
3727     return SDValue();
3728   }
3729
3730   // A vector full of immediates; various special cases are already
3731   // handled, so this is best done with a single constant-pool load.
3732   if (IsAllConstants)
3733     return SDValue();
3734
3735   // Let legalizer expand 2-wide build_vectors.
3736   if (EVTBits == 64) {
3737     if (NumNonZero == 1) {
3738       // One half is zero or undef.
3739       unsigned Idx = CountTrailingZeros_32(NonZeros);
3740       SDValue V2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT,
3741                                  Op.getOperand(Idx));
3742       return getShuffleVectorZeroOrUndef(V2, Idx, true,
3743                                          Subtarget->hasSSE2(), DAG);
3744     }
3745     return SDValue();
3746   }
3747
3748   // If element VT is < 32 bits, convert it to inserts into a zero vector.
3749   if (EVTBits == 8 && NumElems == 16) {
3750     SDValue V = LowerBuildVectorv16i8(Op, NonZeros,NumNonZero,NumZero, DAG,
3751                                         *this);
3752     if (V.getNode()) return V;
3753   }
3754
3755   if (EVTBits == 16 && NumElems == 8) {
3756     SDValue V = LowerBuildVectorv8i16(Op, NonZeros,NumNonZero,NumZero, DAG,
3757                                         *this);
3758     if (V.getNode()) return V;
3759   }
3760
3761   // If element VT is == 32 bits, turn it into a number of shuffles.
3762   SmallVector<SDValue, 8> V;
3763   V.resize(NumElems);
3764   if (NumElems == 4 && NumZero > 0) {
3765     for (unsigned i = 0; i < 4; ++i) {
3766       bool isZero = !(NonZeros & (1 << i));
3767       if (isZero)
3768         V[i] = getZeroVector(VT, Subtarget->hasSSE2(), DAG, dl);
3769       else
3770         V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
3771     }
3772
3773     for (unsigned i = 0; i < 2; ++i) {
3774       switch ((NonZeros & (0x3 << i*2)) >> (i*2)) {
3775         default: break;
3776         case 0:
3777           V[i] = V[i*2];  // Must be a zero vector.
3778           break;
3779         case 1:
3780           V[i] = getMOVL(DAG, dl, VT, V[i*2+1], V[i*2]);
3781           break;
3782         case 2:
3783           V[i] = getMOVL(DAG, dl, VT, V[i*2], V[i*2+1]);
3784           break;
3785         case 3:
3786           V[i] = getUnpackl(DAG, dl, VT, V[i*2], V[i*2+1]);
3787           break;
3788       }
3789     }
3790
3791     SmallVector<int, 8> MaskVec;
3792     bool Reverse = (NonZeros & 0x3) == 2;
3793     for (unsigned i = 0; i < 2; ++i)
3794       MaskVec.push_back(Reverse ? 1-i : i);
3795     Reverse = ((NonZeros & (0x3 << 2)) >> 2) == 2;
3796     for (unsigned i = 0; i < 2; ++i)
3797       MaskVec.push_back(Reverse ? 1-i+NumElems : i+NumElems);
3798     return DAG.getVectorShuffle(VT, dl, V[0], V[1], &MaskVec[0]);
3799   }
3800
3801   if (Values.size() > 2) {
3802     // If we have SSE 4.1, Expand into a number of inserts unless the number of
3803     // values to be inserted is equal to the number of elements, in which case
3804     // use the unpack code below in the hopes of matching the consecutive elts
3805     // load merge pattern for shuffles.
3806     // FIXME: We could probably just check that here directly.
3807     if (Values.size() < NumElems && VT.getSizeInBits() == 128 &&
3808         getSubtarget()->hasSSE41()) {
3809       V[0] = DAG.getUNDEF(VT);
3810       for (unsigned i = 0; i < NumElems; ++i)
3811         if (Op.getOperand(i).getOpcode() != ISD::UNDEF)
3812           V[0] = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, V[0],
3813                              Op.getOperand(i), DAG.getIntPtrConstant(i));
3814       return V[0];
3815     }
3816     // Expand into a number of unpckl*.
3817     // e.g. for v4f32
3818     //   Step 1: unpcklps 0, 2 ==> X: <?, ?, 2, 0>
3819     //         : unpcklps 1, 3 ==> Y: <?, ?, 3, 1>
3820     //   Step 2: unpcklps X, Y ==>    <3, 2, 1, 0>
3821     for (unsigned i = 0; i < NumElems; ++i)
3822       V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
3823     NumElems >>= 1;
3824     while (NumElems != 0) {
3825       for (unsigned i = 0; i < NumElems; ++i)
3826         V[i] = getUnpackl(DAG, dl, VT, V[i], V[i + NumElems]);
3827       NumElems >>= 1;
3828     }
3829     return V[0];
3830   }
3831
3832   return SDValue();
3833 }
3834
3835 SDValue
3836 X86TargetLowering::LowerCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
3837   // We support concatenate two MMX registers and place them in a MMX
3838   // register.  This is better than doing a stack convert.
3839   DebugLoc dl = Op.getDebugLoc();
3840   EVT ResVT = Op.getValueType();
3841   assert(Op.getNumOperands() == 2);
3842   assert(ResVT == MVT::v2i64 || ResVT == MVT::v4i32 ||
3843          ResVT == MVT::v8i16 || ResVT == MVT::v16i8);
3844   int Mask[2];
3845   SDValue InVec = DAG.getNode(ISD::BIT_CONVERT,dl, MVT::v1i64, Op.getOperand(0));
3846   SDValue VecOp = DAG.getNode(X86ISD::MOVQ2DQ, dl, MVT::v2i64, InVec);
3847   InVec = Op.getOperand(1);
3848   if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR) {
3849     unsigned NumElts = ResVT.getVectorNumElements();
3850     VecOp = DAG.getNode(ISD::BIT_CONVERT, dl, ResVT, VecOp);
3851     VecOp = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, ResVT, VecOp,
3852                        InVec.getOperand(0), DAG.getIntPtrConstant(NumElts/2+1));
3853   } else {
3854     InVec = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v1i64, InVec);
3855     SDValue VecOp2 = DAG.getNode(X86ISD::MOVQ2DQ, dl, MVT::v2i64, InVec);
3856     Mask[0] = 0; Mask[1] = 2;
3857     VecOp = DAG.getVectorShuffle(MVT::v2i64, dl, VecOp, VecOp2, Mask);
3858   }
3859   return DAG.getNode(ISD::BIT_CONVERT, dl, ResVT, VecOp);
3860 }
3861
3862 // v8i16 shuffles - Prefer shuffles in the following order:
3863 // 1. [all]   pshuflw, pshufhw, optional move
3864 // 2. [ssse3] 1 x pshufb
3865 // 3. [ssse3] 2 x pshufb + 1 x por
3866 // 4. [all]   mov + pshuflw + pshufhw + N x (pextrw + pinsrw)
3867 static
3868 SDValue LowerVECTOR_SHUFFLEv8i16(ShuffleVectorSDNode *SVOp,
3869                                  SelectionDAG &DAG, X86TargetLowering &TLI) {
3870   SDValue V1 = SVOp->getOperand(0);
3871   SDValue V2 = SVOp->getOperand(1);
3872   DebugLoc dl = SVOp->getDebugLoc();
3873   SmallVector<int, 8> MaskVals;
3874
3875   // Determine if more than 1 of the words in each of the low and high quadwords
3876   // of the result come from the same quadword of one of the two inputs.  Undef
3877   // mask values count as coming from any quadword, for better codegen.
3878   SmallVector<unsigned, 4> LoQuad(4);
3879   SmallVector<unsigned, 4> HiQuad(4);
3880   BitVector InputQuads(4);
3881   for (unsigned i = 0; i < 8; ++i) {
3882     SmallVectorImpl<unsigned> &Quad = i < 4 ? LoQuad : HiQuad;
3883     int EltIdx = SVOp->getMaskElt(i);
3884     MaskVals.push_back(EltIdx);
3885     if (EltIdx < 0) {
3886       ++Quad[0];
3887       ++Quad[1];
3888       ++Quad[2];
3889       ++Quad[3];
3890       continue;
3891     }
3892     ++Quad[EltIdx / 4];
3893     InputQuads.set(EltIdx / 4);
3894   }
3895
3896   int BestLoQuad = -1;
3897   unsigned MaxQuad = 1;
3898   for (unsigned i = 0; i < 4; ++i) {
3899     if (LoQuad[i] > MaxQuad) {
3900       BestLoQuad = i;
3901       MaxQuad = LoQuad[i];
3902     }
3903   }
3904
3905   int BestHiQuad = -1;
3906   MaxQuad = 1;
3907   for (unsigned i = 0; i < 4; ++i) {
3908     if (HiQuad[i] > MaxQuad) {
3909       BestHiQuad = i;
3910       MaxQuad = HiQuad[i];
3911     }
3912   }
3913
3914   // For SSSE3, If all 8 words of the result come from only 1 quadword of each
3915   // of the two input vectors, shuffle them into one input vector so only a
3916   // single pshufb instruction is necessary. If There are more than 2 input
3917   // quads, disable the next transformation since it does not help SSSE3.
3918   bool V1Used = InputQuads[0] || InputQuads[1];
3919   bool V2Used = InputQuads[2] || InputQuads[3];
3920   if (TLI.getSubtarget()->hasSSSE3()) {
3921     if (InputQuads.count() == 2 && V1Used && V2Used) {
3922       BestLoQuad = InputQuads.find_first();
3923       BestHiQuad = InputQuads.find_next(BestLoQuad);
3924     }
3925     if (InputQuads.count() > 2) {
3926       BestLoQuad = -1;
3927       BestHiQuad = -1;
3928     }
3929   }
3930
3931   // If BestLoQuad or BestHiQuad are set, shuffle the quads together and update
3932   // the shuffle mask.  If a quad is scored as -1, that means that it contains
3933   // words from all 4 input quadwords.
3934   SDValue NewV;
3935   if (BestLoQuad >= 0 || BestHiQuad >= 0) {
3936     SmallVector<int, 8> MaskV;
3937     MaskV.push_back(BestLoQuad < 0 ? 0 : BestLoQuad);
3938     MaskV.push_back(BestHiQuad < 0 ? 1 : BestHiQuad);
3939     NewV = DAG.getVectorShuffle(MVT::v2i64, dl,
3940                   DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v2i64, V1),
3941                   DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v2i64, V2), &MaskV[0]);
3942     NewV = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v8i16, NewV);
3943
3944     // Rewrite the MaskVals and assign NewV to V1 if NewV now contains all the
3945     // source words for the shuffle, to aid later transformations.
3946     bool AllWordsInNewV = true;
3947     bool InOrder[2] = { true, true };
3948     for (unsigned i = 0; i != 8; ++i) {
3949       int idx = MaskVals[i];
3950       if (idx != (int)i)
3951         InOrder[i/4] = false;
3952       if (idx < 0 || (idx/4) == BestLoQuad || (idx/4) == BestHiQuad)
3953         continue;
3954       AllWordsInNewV = false;
3955       break;
3956     }
3957
3958     bool pshuflw = AllWordsInNewV, pshufhw = AllWordsInNewV;
3959     if (AllWordsInNewV) {
3960       for (int i = 0; i != 8; ++i) {
3961         int idx = MaskVals[i];
3962         if (idx < 0)
3963           continue;
3964         idx = MaskVals[i] = (idx / 4) == BestLoQuad ? (idx & 3) : (idx & 3) + 4;
3965         if ((idx != i) && idx < 4)
3966           pshufhw = false;
3967         if ((idx != i) && idx > 3)
3968           pshuflw = false;
3969       }
3970       V1 = NewV;
3971       V2Used = false;
3972       BestLoQuad = 0;
3973       BestHiQuad = 1;
3974     }
3975
3976     // If we've eliminated the use of V2, and the new mask is a pshuflw or
3977     // pshufhw, that's as cheap as it gets.  Return the new shuffle.
3978     if ((pshufhw && InOrder[0]) || (pshuflw && InOrder[1])) {
3979       return DAG.getVectorShuffle(MVT::v8i16, dl, NewV,
3980                                   DAG.getUNDEF(MVT::v8i16), &MaskVals[0]);
3981     }
3982   }
3983
3984   // If we have SSSE3, and all words of the result are from 1 input vector,
3985   // case 2 is generated, otherwise case 3 is generated.  If no SSSE3
3986   // is present, fall back to case 4.
3987   if (TLI.getSubtarget()->hasSSSE3()) {
3988     SmallVector<SDValue,16> pshufbMask;
3989
3990     // If we have elements from both input vectors, set the high bit of the
3991     // shuffle mask element to zero out elements that come from V2 in the V1
3992     // mask, and elements that come from V1 in the V2 mask, so that the two
3993     // results can be OR'd together.
3994     bool TwoInputs = V1Used && V2Used;
3995     for (unsigned i = 0; i != 8; ++i) {
3996       int EltIdx = MaskVals[i] * 2;
3997       if (TwoInputs && (EltIdx >= 16)) {
3998         pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
3999         pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
4000         continue;
4001       }
4002       pshufbMask.push_back(DAG.getConstant(EltIdx,   MVT::i8));
4003       pshufbMask.push_back(DAG.getConstant(EltIdx+1, MVT::i8));
4004     }
4005     V1 = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v16i8, V1);
4006     V1 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V1,
4007                      DAG.getNode(ISD::BUILD_VECTOR, dl,
4008                                  MVT::v16i8, &pshufbMask[0], 16));
4009     if (!TwoInputs)
4010       return DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v8i16, V1);
4011
4012     // Calculate the shuffle mask for the second input, shuffle it, and
4013     // OR it with the first shuffled input.
4014     pshufbMask.clear();
4015     for (unsigned i = 0; i != 8; ++i) {
4016       int EltIdx = MaskVals[i] * 2;
4017       if (EltIdx < 16) {
4018         pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
4019         pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
4020         continue;
4021       }
4022       pshufbMask.push_back(DAG.getConstant(EltIdx - 16, MVT::i8));
4023       pshufbMask.push_back(DAG.getConstant(EltIdx - 15, MVT::i8));
4024     }
4025     V2 = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v16i8, V2);
4026     V2 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V2,
4027                      DAG.getNode(ISD::BUILD_VECTOR, dl,
4028                                  MVT::v16i8, &pshufbMask[0], 16));
4029     V1 = DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2);
4030     return DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v8i16, V1);
4031   }
4032
4033   // If BestLoQuad >= 0, generate a pshuflw to put the low elements in order,
4034   // and update MaskVals with new element order.
4035   BitVector InOrder(8);
4036   if (BestLoQuad >= 0) {
4037     SmallVector<int, 8> MaskV;
4038     for (int i = 0; i != 4; ++i) {
4039       int idx = MaskVals[i];
4040       if (idx < 0) {
4041         MaskV.push_back(-1);
4042         InOrder.set(i);
4043       } else if ((idx / 4) == BestLoQuad) {
4044         MaskV.push_back(idx & 3);
4045         InOrder.set(i);
4046       } else {
4047         MaskV.push_back(-1);
4048       }
4049     }
4050     for (unsigned i = 4; i != 8; ++i)
4051       MaskV.push_back(i);
4052     NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::v8i16),
4053                                 &MaskV[0]);
4054   }
4055
4056   // If BestHi >= 0, generate a pshufhw to put the high elements in order,
4057   // and update MaskVals with the new element order.
4058   if (BestHiQuad >= 0) {
4059     SmallVector<int, 8> MaskV;
4060     for (unsigned i = 0; i != 4; ++i)
4061       MaskV.push_back(i);
4062     for (unsigned i = 4; i != 8; ++i) {
4063       int idx = MaskVals[i];
4064       if (idx < 0) {
4065         MaskV.push_back(-1);
4066         InOrder.set(i);
4067       } else if ((idx / 4) == BestHiQuad) {
4068         MaskV.push_back((idx & 3) + 4);
4069         InOrder.set(i);
4070       } else {
4071         MaskV.push_back(-1);
4072       }
4073     }
4074     NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::v8i16),
4075                                 &MaskV[0]);
4076   }
4077
4078   // In case BestHi & BestLo were both -1, which means each quadword has a word
4079   // from each of the four input quadwords, calculate the InOrder bitvector now
4080   // before falling through to the insert/extract cleanup.
4081   if (BestLoQuad == -1 && BestHiQuad == -1) {
4082     NewV = V1;
4083     for (int i = 0; i != 8; ++i)
4084       if (MaskVals[i] < 0 || MaskVals[i] == i)
4085         InOrder.set(i);
4086   }
4087
4088   // The other elements are put in the right place using pextrw and pinsrw.
4089   for (unsigned i = 0; i != 8; ++i) {
4090     if (InOrder[i])
4091       continue;
4092     int EltIdx = MaskVals[i];
4093     if (EltIdx < 0)
4094       continue;
4095     SDValue ExtOp = (EltIdx < 8)
4096     ? DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V1,
4097                   DAG.getIntPtrConstant(EltIdx))
4098     : DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V2,
4099                   DAG.getIntPtrConstant(EltIdx - 8));
4100     NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, ExtOp,
4101                        DAG.getIntPtrConstant(i));
4102   }
4103   return NewV;
4104 }
4105
4106 // v16i8 shuffles - Prefer shuffles in the following order:
4107 // 1. [ssse3] 1 x pshufb
4108 // 2. [ssse3] 2 x pshufb + 1 x por
4109 // 3. [all]   v8i16 shuffle + N x pextrw + rotate + pinsrw
4110 static
4111 SDValue LowerVECTOR_SHUFFLEv16i8(ShuffleVectorSDNode *SVOp,
4112                                  SelectionDAG &DAG, X86TargetLowering &TLI) {
4113   SDValue V1 = SVOp->getOperand(0);
4114   SDValue V2 = SVOp->getOperand(1);
4115   DebugLoc dl = SVOp->getDebugLoc();
4116   SmallVector<int, 16> MaskVals;
4117   SVOp->getMask(MaskVals);
4118
4119   // If we have SSSE3, case 1 is generated when all result bytes come from
4120   // one of  the inputs.  Otherwise, case 2 is generated.  If no SSSE3 is
4121   // present, fall back to case 3.
4122   // FIXME: kill V2Only once shuffles are canonizalized by getNode.
4123   bool V1Only = true;
4124   bool V2Only = true;
4125   for (unsigned i = 0; i < 16; ++i) {
4126     int EltIdx = MaskVals[i];
4127     if (EltIdx < 0)
4128       continue;
4129     if (EltIdx < 16)
4130       V2Only = false;
4131     else
4132       V1Only = false;
4133   }
4134
4135   // If SSSE3, use 1 pshufb instruction per vector with elements in the result.
4136   if (TLI.getSubtarget()->hasSSSE3()) {
4137     SmallVector<SDValue,16> pshufbMask;
4138
4139     // If all result elements are from one input vector, then only translate
4140     // undef mask values to 0x80 (zero out result) in the pshufb mask.
4141     //
4142     // Otherwise, we have elements from both input vectors, and must zero out
4143     // elements that come from V2 in the first mask, and V1 in the second mask
4144     // so that we can OR them together.
4145     bool TwoInputs = !(V1Only || V2Only);
4146     for (unsigned i = 0; i != 16; ++i) {
4147       int EltIdx = MaskVals[i];
4148       if (EltIdx < 0 || (TwoInputs && EltIdx >= 16)) {
4149         pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
4150         continue;
4151       }
4152       pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8));
4153     }
4154     // If all the elements are from V2, assign it to V1 and return after
4155     // building the first pshufb.
4156     if (V2Only)
4157       V1 = V2;
4158     V1 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V1,
4159                      DAG.getNode(ISD::BUILD_VECTOR, dl,
4160                                  MVT::v16i8, &pshufbMask[0], 16));
4161     if (!TwoInputs)
4162       return V1;
4163
4164     // Calculate the shuffle mask for the second input, shuffle it, and
4165     // OR it with the first shuffled input.
4166     pshufbMask.clear();
4167     for (unsigned i = 0; i != 16; ++i) {
4168       int EltIdx = MaskVals[i];
4169       if (EltIdx < 16) {
4170         pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
4171         continue;
4172       }
4173       pshufbMask.push_back(DAG.getConstant(EltIdx - 16, MVT::i8));
4174     }
4175     V2 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V2,
4176                      DAG.getNode(ISD::BUILD_VECTOR, dl,
4177                                  MVT::v16i8, &pshufbMask[0], 16));
4178     return DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2);
4179   }
4180
4181   // No SSSE3 - Calculate in place words and then fix all out of place words
4182   // With 0-16 extracts & inserts.  Worst case is 16 bytes out of order from
4183   // the 16 different words that comprise the two doublequadword input vectors.
4184   V1 = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v8i16, V1);
4185   V2 = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v8i16, V2);
4186   SDValue NewV = V2Only ? V2 : V1;
4187   for (int i = 0; i != 8; ++i) {
4188     int Elt0 = MaskVals[i*2];
4189     int Elt1 = MaskVals[i*2+1];
4190
4191     // This word of the result is all undef, skip it.
4192     if (Elt0 < 0 && Elt1 < 0)
4193       continue;
4194
4195     // This word of the result is already in the correct place, skip it.
4196     if (V1Only && (Elt0 == i*2) && (Elt1 == i*2+1))
4197       continue;
4198     if (V2Only && (Elt0 == i*2+16) && (Elt1 == i*2+17))
4199       continue;
4200
4201     SDValue Elt0Src = Elt0 < 16 ? V1 : V2;
4202     SDValue Elt1Src = Elt1 < 16 ? V1 : V2;
4203     SDValue InsElt;
4204
4205     // If Elt0 and Elt1 are defined, are consecutive, and can be load
4206     // using a single extract together, load it and store it.
4207     if ((Elt0 >= 0) && ((Elt0 + 1) == Elt1) && ((Elt0 & 1) == 0)) {
4208       InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src,
4209                            DAG.getIntPtrConstant(Elt1 / 2));
4210       NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt,
4211                         DAG.getIntPtrConstant(i));
4212       continue;
4213     }
4214
4215     // If Elt1 is defined, extract it from the appropriate source.  If the
4216     // source byte is not also odd, shift the extracted word left 8 bits
4217     // otherwise clear the bottom 8 bits if we need to do an or.
4218     if (Elt1 >= 0) {
4219       InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src,
4220                            DAG.getIntPtrConstant(Elt1 / 2));
4221       if ((Elt1 & 1) == 0)
4222         InsElt = DAG.getNode(ISD::SHL, dl, MVT::i16, InsElt,
4223                              DAG.getConstant(8, TLI.getShiftAmountTy()));
4224       else if (Elt0 >= 0)
4225         InsElt = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt,
4226                              DAG.getConstant(0xFF00, MVT::i16));
4227     }
4228     // If Elt0 is defined, extract it from the appropriate source.  If the
4229     // source byte is not also even, shift the extracted word right 8 bits. If
4230     // Elt1 was also defined, OR the extracted values together before
4231     // inserting them in the result.
4232     if (Elt0 >= 0) {
4233       SDValue InsElt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16,
4234                                     Elt0Src, DAG.getIntPtrConstant(Elt0 / 2));
4235       if ((Elt0 & 1) != 0)
4236         InsElt0 = DAG.getNode(ISD::SRL, dl, MVT::i16, InsElt0,
4237                               DAG.getConstant(8, TLI.getShiftAmountTy()));
4238       else if (Elt1 >= 0)
4239         InsElt0 = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt0,
4240                              DAG.getConstant(0x00FF, MVT::i16));
4241       InsElt = Elt1 >= 0 ? DAG.getNode(ISD::OR, dl, MVT::i16, InsElt, InsElt0)
4242                          : InsElt0;
4243     }
4244     NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt,
4245                        DAG.getIntPtrConstant(i));
4246   }
4247   return DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v16i8, NewV);
4248 }
4249
4250 /// RewriteAsNarrowerShuffle - Try rewriting v8i16 and v16i8 shuffles as 4 wide
4251 /// ones, or rewriting v4i32 / v2f32 as 2 wide ones if possible. This can be
4252 /// done when every pair / quad of shuffle mask elements point to elements in
4253 /// the right sequence. e.g.
4254 /// vector_shuffle <>, <>, < 3, 4, | 10, 11, | 0, 1, | 14, 15>
4255 static
4256 SDValue RewriteAsNarrowerShuffle(ShuffleVectorSDNode *SVOp,
4257                                  SelectionDAG &DAG,
4258                                  TargetLowering &TLI, DebugLoc dl) {
4259   EVT VT = SVOp->getValueType(0);
4260   SDValue V1 = SVOp->getOperand(0);
4261   SDValue V2 = SVOp->getOperand(1);
4262   unsigned NumElems = VT.getVectorNumElements();
4263   unsigned NewWidth = (NumElems == 4) ? 2 : 4;
4264   EVT MaskVT = MVT::getIntVectorWithNumElements(NewWidth);
4265   EVT MaskEltVT = MaskVT.getVectorElementType();
4266   EVT NewVT = MaskVT;
4267   switch (VT.getSimpleVT().SimpleTy) {
4268   default: assert(false && "Unexpected!");
4269   case MVT::v4f32: NewVT = MVT::v2f64; break;
4270   case MVT::v4i32: NewVT = MVT::v2i64; break;
4271   case MVT::v8i16: NewVT = MVT::v4i32; break;
4272   case MVT::v16i8: NewVT = MVT::v4i32; break;
4273   }
4274
4275   if (NewWidth == 2) {
4276     if (VT.isInteger())
4277       NewVT = MVT::v2i64;
4278     else
4279       NewVT = MVT::v2f64;
4280   }
4281   int Scale = NumElems / NewWidth;
4282   SmallVector<int, 8> MaskVec;
4283   for (unsigned i = 0; i < NumElems; i += Scale) {
4284     int StartIdx = -1;
4285     for (int j = 0; j < Scale; ++j) {
4286       int EltIdx = SVOp->getMaskElt(i+j);
4287       if (EltIdx < 0)
4288         continue;
4289       if (StartIdx == -1)
4290         StartIdx = EltIdx - (EltIdx % Scale);
4291       if (EltIdx != StartIdx + j)
4292         return SDValue();
4293     }
4294     if (StartIdx == -1)
4295       MaskVec.push_back(-1);
4296     else
4297       MaskVec.push_back(StartIdx / Scale);
4298   }
4299
4300   V1 = DAG.getNode(ISD::BIT_CONVERT, dl, NewVT, V1);
4301   V2 = DAG.getNode(ISD::BIT_CONVERT, dl, NewVT, V2);
4302   return DAG.getVectorShuffle(NewVT, dl, V1, V2, &MaskVec[0]);
4303 }
4304
4305 /// getVZextMovL - Return a zero-extending vector move low node.
4306 ///
4307 static SDValue getVZextMovL(EVT VT, EVT OpVT,
4308                             SDValue SrcOp, SelectionDAG &DAG,
4309                             const X86Subtarget *Subtarget, DebugLoc dl) {
4310   if (VT == MVT::v2f64 || VT == MVT::v4f32) {
4311     LoadSDNode *LD = NULL;
4312     if (!isScalarLoadToVector(SrcOp.getNode(), &LD))
4313       LD = dyn_cast<LoadSDNode>(SrcOp);
4314     if (!LD) {
4315       // movssrr and movsdrr do not clear top bits. Try to use movd, movq
4316       // instead.
4317       MVT ExtVT = (OpVT == MVT::v2f64) ? MVT::i64 : MVT::i32;
4318       if ((ExtVT.SimpleTy != MVT::i64 || Subtarget->is64Bit()) &&
4319           SrcOp.getOpcode() == ISD::SCALAR_TO_VECTOR &&
4320           SrcOp.getOperand(0).getOpcode() == ISD::BIT_CONVERT &&
4321           SrcOp.getOperand(0).getOperand(0).getValueType() == ExtVT) {
4322         // PR2108
4323         OpVT = (OpVT == MVT::v2f64) ? MVT::v2i64 : MVT::v4i32;
4324         return DAG.getNode(ISD::BIT_CONVERT, dl, VT,
4325                            DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT,
4326                                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
4327                                                    OpVT,
4328                                                    SrcOp.getOperand(0)
4329                                                           .getOperand(0))));
4330       }
4331     }
4332   }
4333
4334   return DAG.getNode(ISD::BIT_CONVERT, dl, VT,
4335                      DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT,
4336                                  DAG.getNode(ISD::BIT_CONVERT, dl,
4337                                              OpVT, SrcOp)));
4338 }
4339
4340 /// LowerVECTOR_SHUFFLE_4wide - Handle all 4 wide cases with a number of
4341 /// shuffles.
4342 static SDValue
4343 LowerVECTOR_SHUFFLE_4wide(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
4344   SDValue V1 = SVOp->getOperand(0);
4345   SDValue V2 = SVOp->getOperand(1);
4346   DebugLoc dl = SVOp->getDebugLoc();
4347   EVT VT = SVOp->getValueType(0);
4348
4349   SmallVector<std::pair<int, int>, 8> Locs;
4350   Locs.resize(4);
4351   SmallVector<int, 8> Mask1(4U, -1);
4352   SmallVector<int, 8> PermMask;
4353   SVOp->getMask(PermMask);
4354
4355   unsigned NumHi = 0;
4356   unsigned NumLo = 0;
4357   for (unsigned i = 0; i != 4; ++i) {
4358     int Idx = PermMask[i];
4359     if (Idx < 0) {
4360       Locs[i] = std::make_pair(-1, -1);
4361     } else {
4362       assert(Idx < 8 && "Invalid VECTOR_SHUFFLE index!");
4363       if (Idx < 4) {
4364         Locs[i] = std::make_pair(0, NumLo);
4365         Mask1[NumLo] = Idx;
4366         NumLo++;
4367       } else {
4368         Locs[i] = std::make_pair(1, NumHi);
4369         if (2+NumHi < 4)
4370           Mask1[2+NumHi] = Idx;
4371         NumHi++;
4372       }
4373     }
4374   }
4375
4376   if (NumLo <= 2 && NumHi <= 2) {
4377     // If no more than two elements come from either vector. This can be
4378     // implemented with two shuffles. First shuffle gather the elements.
4379     // The second shuffle, which takes the first shuffle as both of its
4380     // vector operands, put the elements into the right order.
4381     V1 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
4382
4383     SmallVector<int, 8> Mask2(4U, -1);
4384
4385     for (unsigned i = 0; i != 4; ++i) {
4386       if (Locs[i].first == -1)
4387         continue;
4388       else {
4389         unsigned Idx = (i < 2) ? 0 : 4;
4390         Idx += Locs[i].first * 2 + Locs[i].second;
4391         Mask2[i] = Idx;
4392       }
4393     }
4394
4395     return DAG.getVectorShuffle(VT, dl, V1, V1, &Mask2[0]);
4396   } else if (NumLo == 3 || NumHi == 3) {
4397     // Otherwise, we must have three elements from one vector, call it X, and
4398     // one element from the other, call it Y.  First, use a shufps to build an
4399     // intermediate vector with the one element from Y and the element from X
4400     // that will be in the same half in the final destination (the indexes don't
4401     // matter). Then, use a shufps to build the final vector, taking the half
4402     // containing the element from Y from the intermediate, and the other half
4403     // from X.
4404     if (NumHi == 3) {
4405       // Normalize it so the 3 elements come from V1.
4406       CommuteVectorShuffleMask(PermMask, VT);
4407       std::swap(V1, V2);
4408     }
4409
4410     // Find the element from V2.
4411     unsigned HiIndex;
4412     for (HiIndex = 0; HiIndex < 3; ++HiIndex) {
4413       int Val = PermMask[HiIndex];
4414       if (Val < 0)
4415         continue;
4416       if (Val >= 4)
4417         break;
4418     }
4419
4420     Mask1[0] = PermMask[HiIndex];
4421     Mask1[1] = -1;
4422     Mask1[2] = PermMask[HiIndex^1];
4423     Mask1[3] = -1;
4424     V2 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
4425
4426     if (HiIndex >= 2) {
4427       Mask1[0] = PermMask[0];
4428       Mask1[1] = PermMask[1];
4429       Mask1[2] = HiIndex & 1 ? 6 : 4;
4430       Mask1[3] = HiIndex & 1 ? 4 : 6;
4431       return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
4432     } else {
4433       Mask1[0] = HiIndex & 1 ? 2 : 0;
4434       Mask1[1] = HiIndex & 1 ? 0 : 2;
4435       Mask1[2] = PermMask[2];
4436       Mask1[3] = PermMask[3];
4437       if (Mask1[2] >= 0)
4438         Mask1[2] += 4;
4439       if (Mask1[3] >= 0)
4440         Mask1[3] += 4;
4441       return DAG.getVectorShuffle(VT, dl, V2, V1, &Mask1[0]);
4442     }
4443   }
4444
4445   // Break it into (shuffle shuffle_hi, shuffle_lo).
4446   Locs.clear();
4447   SmallVector<int,8> LoMask(4U, -1);
4448   SmallVector<int,8> HiMask(4U, -1);
4449
4450   SmallVector<int,8> *MaskPtr = &LoMask;
4451   unsigned MaskIdx = 0;
4452   unsigned LoIdx = 0;
4453   unsigned HiIdx = 2;
4454   for (unsigned i = 0; i != 4; ++i) {
4455     if (i == 2) {
4456       MaskPtr = &HiMask;
4457       MaskIdx = 1;
4458       LoIdx = 0;
4459       HiIdx = 2;
4460     }
4461     int Idx = PermMask[i];
4462     if (Idx < 0) {
4463       Locs[i] = std::make_pair(-1, -1);
4464     } else if (Idx < 4) {
4465       Locs[i] = std::make_pair(MaskIdx, LoIdx);
4466       (*MaskPtr)[LoIdx] = Idx;
4467       LoIdx++;
4468     } else {
4469       Locs[i] = std::make_pair(MaskIdx, HiIdx);
4470       (*MaskPtr)[HiIdx] = Idx;
4471       HiIdx++;
4472     }
4473   }
4474
4475   SDValue LoShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &LoMask[0]);
4476   SDValue HiShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &HiMask[0]);
4477   SmallVector<int, 8> MaskOps;
4478   for (unsigned i = 0; i != 4; ++i) {
4479     if (Locs[i].first == -1) {
4480       MaskOps.push_back(-1);
4481     } else {
4482       unsigned Idx = Locs[i].first * 4 + Locs[i].second;
4483       MaskOps.push_back(Idx);
4484     }
4485   }
4486   return DAG.getVectorShuffle(VT, dl, LoShuffle, HiShuffle, &MaskOps[0]);
4487 }
4488
4489 SDValue
4490 X86TargetLowering::LowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG) {
4491   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
4492   SDValue V1 = Op.getOperand(0);
4493   SDValue V2 = Op.getOperand(1);
4494   EVT VT = Op.getValueType();
4495   DebugLoc dl = Op.getDebugLoc();
4496   unsigned NumElems = VT.getVectorNumElements();
4497   bool isMMX = VT.getSizeInBits() == 64;
4498   bool V1IsUndef = V1.getOpcode() == ISD::UNDEF;
4499   bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
4500   bool V1IsSplat = false;
4501   bool V2IsSplat = false;
4502
4503   if (isZeroShuffle(SVOp))
4504     return getZeroVector(VT, Subtarget->hasSSE2(), DAG, dl);
4505
4506   // Promote splats to v4f32.
4507   if (SVOp->isSplat()) {
4508     if (isMMX || NumElems < 4)
4509       return Op;
4510     return PromoteSplat(SVOp, DAG, Subtarget->hasSSE2());
4511   }
4512
4513   // If the shuffle can be profitably rewritten as a narrower shuffle, then
4514   // do it!
4515   if (VT == MVT::v8i16 || VT == MVT::v16i8) {
4516     SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG, *this, dl);
4517     if (NewOp.getNode())
4518       return DAG.getNode(ISD::BIT_CONVERT, dl, VT,
4519                          LowerVECTOR_SHUFFLE(NewOp, DAG));
4520   } else if ((VT == MVT::v4i32 || (VT == MVT::v4f32 && Subtarget->hasSSE2()))) {
4521     // FIXME: Figure out a cleaner way to do this.
4522     // Try to make use of movq to zero out the top part.
4523     if (ISD::isBuildVectorAllZeros(V2.getNode())) {
4524       SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG, *this, dl);
4525       if (NewOp.getNode()) {
4526         if (isCommutedMOVL(cast<ShuffleVectorSDNode>(NewOp), true, false))
4527           return getVZextMovL(VT, NewOp.getValueType(), NewOp.getOperand(0),
4528                               DAG, Subtarget, dl);
4529       }
4530     } else if (ISD::isBuildVectorAllZeros(V1.getNode())) {
4531       SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG, *this, dl);
4532       if (NewOp.getNode() && X86::isMOVLMask(cast<ShuffleVectorSDNode>(NewOp)))
4533         return getVZextMovL(VT, NewOp.getValueType(), NewOp.getOperand(1),
4534                             DAG, Subtarget, dl);
4535     }
4536   }
4537
4538   if (X86::isPSHUFDMask(SVOp))
4539     return Op;
4540
4541   // Check if this can be converted into a logical shift.
4542   bool isLeft = false;
4543   unsigned ShAmt = 0;
4544   SDValue ShVal;
4545   bool isShift = getSubtarget()->hasSSE2() &&
4546     isVectorShift(SVOp, DAG, isLeft, ShVal, ShAmt);
4547   if (isShift && ShVal.hasOneUse()) {
4548     // If the shifted value has multiple uses, it may be cheaper to use
4549     // v_set0 + movlhps or movhlps, etc.
4550     EVT EltVT = VT.getVectorElementType();
4551     ShAmt *= EltVT.getSizeInBits();
4552     return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
4553   }
4554
4555   if (X86::isMOVLMask(SVOp)) {
4556     if (V1IsUndef)
4557       return V2;
4558     if (ISD::isBuildVectorAllZeros(V1.getNode()))
4559       return getVZextMovL(VT, VT, V2, DAG, Subtarget, dl);
4560     if (!isMMX)
4561       return Op;
4562   }
4563
4564   // FIXME: fold these into legal mask.
4565   if (!isMMX && (X86::isMOVSHDUPMask(SVOp) ||
4566                  X86::isMOVSLDUPMask(SVOp) ||
4567                  X86::isMOVHLPSMask(SVOp) ||
4568                  X86::isMOVLHPSMask(SVOp) ||
4569                  X86::isMOVLPMask(SVOp)))
4570     return Op;
4571
4572   if (ShouldXformToMOVHLPS(SVOp) ||
4573       ShouldXformToMOVLP(V1.getNode(), V2.getNode(), SVOp))
4574     return CommuteVectorShuffle(SVOp, DAG);
4575
4576   if (isShift) {
4577     // No better options. Use a vshl / vsrl.
4578     EVT EltVT = VT.getVectorElementType();
4579     ShAmt *= EltVT.getSizeInBits();
4580     return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
4581   }
4582
4583   bool Commuted = false;
4584   // FIXME: This should also accept a bitcast of a splat?  Be careful, not
4585   // 1,1,1,1 -> v8i16 though.
4586   V1IsSplat = isSplatVector(V1.getNode());
4587   V2IsSplat = isSplatVector(V2.getNode());
4588
4589   // Canonicalize the splat or undef, if present, to be on the RHS.
4590   if ((V1IsSplat || V1IsUndef) && !(V2IsSplat || V2IsUndef)) {
4591     Op = CommuteVectorShuffle(SVOp, DAG);
4592     SVOp = cast<ShuffleVectorSDNode>(Op);
4593     V1 = SVOp->getOperand(0);
4594     V2 = SVOp->getOperand(1);
4595     std::swap(V1IsSplat, V2IsSplat);
4596     std::swap(V1IsUndef, V2IsUndef);
4597     Commuted = true;
4598   }
4599
4600   if (isCommutedMOVL(SVOp, V2IsSplat, V2IsUndef)) {
4601     // Shuffling low element of v1 into undef, just return v1.
4602     if (V2IsUndef)
4603       return V1;
4604     // If V2 is a splat, the mask may be malformed such as <4,3,3,3>, which
4605     // the instruction selector will not match, so get a canonical MOVL with
4606     // swapped operands to undo the commute.
4607     return getMOVL(DAG, dl, VT, V2, V1);
4608   }
4609
4610   if (X86::isUNPCKL_v_undef_Mask(SVOp) ||
4611       X86::isUNPCKH_v_undef_Mask(SVOp) ||
4612       X86::isUNPCKLMask(SVOp) ||
4613       X86::isUNPCKHMask(SVOp))
4614     return Op;
4615
4616   if (V2IsSplat) {
4617     // Normalize mask so all entries that point to V2 points to its first
4618     // element then try to match unpck{h|l} again. If match, return a
4619     // new vector_shuffle with the corrected mask.
4620     SDValue NewMask = NormalizeMask(SVOp, DAG);
4621     ShuffleVectorSDNode *NSVOp = cast<ShuffleVectorSDNode>(NewMask);
4622     if (NSVOp != SVOp) {
4623       if (X86::isUNPCKLMask(NSVOp, true)) {
4624         return NewMask;
4625       } else if (X86::isUNPCKHMask(NSVOp, true)) {
4626         return NewMask;
4627       }
4628     }
4629   }
4630
4631   if (Commuted) {
4632     // Commute is back and try unpck* again.
4633     // FIXME: this seems wrong.
4634     SDValue NewOp = CommuteVectorShuffle(SVOp, DAG);
4635     ShuffleVectorSDNode *NewSVOp = cast<ShuffleVectorSDNode>(NewOp);
4636     if (X86::isUNPCKL_v_undef_Mask(NewSVOp) ||
4637         X86::isUNPCKH_v_undef_Mask(NewSVOp) ||
4638         X86::isUNPCKLMask(NewSVOp) ||
4639         X86::isUNPCKHMask(NewSVOp))
4640       return NewOp;
4641   }
4642
4643   // FIXME: for mmx, bitcast v2i32 to v4i16 for shuffle.
4644
4645   // Normalize the node to match x86 shuffle ops if needed
4646   if (!isMMX && V2.getOpcode() != ISD::UNDEF && isCommutedSHUFP(SVOp))
4647     return CommuteVectorShuffle(SVOp, DAG);
4648
4649   // Check for legal shuffle and return?
4650   SmallVector<int, 16> PermMask;
4651   SVOp->getMask(PermMask);
4652   if (isShuffleMaskLegal(PermMask, VT))
4653     return Op;
4654
4655   // Handle v8i16 specifically since SSE can do byte extraction and insertion.
4656   if (VT == MVT::v8i16) {
4657     SDValue NewOp = LowerVECTOR_SHUFFLEv8i16(SVOp, DAG, *this);
4658     if (NewOp.getNode())
4659       return NewOp;
4660   }
4661
4662   if (VT == MVT::v16i8) {
4663     SDValue NewOp = LowerVECTOR_SHUFFLEv16i8(SVOp, DAG, *this);
4664     if (NewOp.getNode())
4665       return NewOp;
4666   }
4667
4668   // Handle all 4 wide cases with a number of shuffles except for MMX.
4669   if (NumElems == 4 && !isMMX)
4670     return LowerVECTOR_SHUFFLE_4wide(SVOp, DAG);
4671
4672   return SDValue();
4673 }
4674
4675 SDValue
4676 X86TargetLowering::LowerEXTRACT_VECTOR_ELT_SSE4(SDValue Op,
4677                                                 SelectionDAG &DAG) {
4678   EVT VT = Op.getValueType();
4679   DebugLoc dl = Op.getDebugLoc();
4680   if (VT.getSizeInBits() == 8) {
4681     SDValue Extract = DAG.getNode(X86ISD::PEXTRB, dl, MVT::i32,
4682                                     Op.getOperand(0), Op.getOperand(1));
4683     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
4684                                     DAG.getValueType(VT));
4685     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
4686   } else if (VT.getSizeInBits() == 16) {
4687     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
4688     // If Idx is 0, it's cheaper to do a move instead of a pextrw.
4689     if (Idx == 0)
4690       return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
4691                          DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
4692                                      DAG.getNode(ISD::BIT_CONVERT, dl,
4693                                                  MVT::v4i32,
4694                                                  Op.getOperand(0)),
4695                                      Op.getOperand(1)));
4696     SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, MVT::i32,
4697                                     Op.getOperand(0), Op.getOperand(1));
4698     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
4699                                     DAG.getValueType(VT));
4700     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
4701   } else if (VT == MVT::f32) {
4702     // EXTRACTPS outputs to a GPR32 register which will require a movd to copy
4703     // the result back to FR32 register. It's only worth matching if the
4704     // result has a single use which is a store or a bitcast to i32.  And in
4705     // the case of a store, it's not worth it if the index is a constant 0,
4706     // because a MOVSSmr can be used instead, which is smaller and faster.
4707     if (!Op.hasOneUse())
4708       return SDValue();
4709     SDNode *User = *Op.getNode()->use_begin();
4710     if ((User->getOpcode() != ISD::STORE ||
4711          (isa<ConstantSDNode>(Op.getOperand(1)) &&
4712           cast<ConstantSDNode>(Op.getOperand(1))->isNullValue())) &&
4713         (User->getOpcode() != ISD::BIT_CONVERT ||
4714          User->getValueType(0) != MVT::i32))
4715       return SDValue();
4716     SDValue Extract = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
4717                                   DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v4i32,
4718                                               Op.getOperand(0)),
4719                                               Op.getOperand(1));
4720     return DAG.getNode(ISD::BIT_CONVERT, dl, MVT::f32, Extract);
4721   } else if (VT == MVT::i32) {
4722     // ExtractPS works with constant index.
4723     if (isa<ConstantSDNode>(Op.getOperand(1)))
4724       return Op;
4725   }
4726   return SDValue();
4727 }
4728
4729
4730 SDValue
4731 X86TargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) {
4732   if (!isa<ConstantSDNode>(Op.getOperand(1)))
4733     return SDValue();
4734
4735   if (Subtarget->hasSSE41()) {
4736     SDValue Res = LowerEXTRACT_VECTOR_ELT_SSE4(Op, DAG);
4737     if (Res.getNode())
4738       return Res;
4739   }
4740
4741   EVT VT = Op.getValueType();
4742   DebugLoc dl = Op.getDebugLoc();
4743   // TODO: handle v16i8.
4744   if (VT.getSizeInBits() == 16) {
4745     SDValue Vec = Op.getOperand(0);
4746     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
4747     if (Idx == 0)
4748       return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
4749                          DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
4750                                      DAG.getNode(ISD::BIT_CONVERT, dl,
4751                                                  MVT::v4i32, Vec),
4752                                      Op.getOperand(1)));
4753     // Transform it so it match pextrw which produces a 32-bit result.
4754     EVT EltVT = MVT::i32;
4755     SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, EltVT,
4756                                     Op.getOperand(0), Op.getOperand(1));
4757     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, EltVT, Extract,
4758                                     DAG.getValueType(VT));
4759     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
4760   } else if (VT.getSizeInBits() == 32) {
4761     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
4762     if (Idx == 0)
4763       return Op;
4764
4765     // SHUFPS the element to the lowest double word, then movss.
4766     int Mask[4] = { Idx, -1, -1, -1 };
4767     EVT VVT = Op.getOperand(0).getValueType();
4768     SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
4769                                        DAG.getUNDEF(VVT), Mask);
4770     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
4771                        DAG.getIntPtrConstant(0));
4772   } else if (VT.getSizeInBits() == 64) {
4773     // FIXME: .td only matches this for <2 x f64>, not <2 x i64> on 32b
4774     // FIXME: seems like this should be unnecessary if mov{h,l}pd were taught
4775     //        to match extract_elt for f64.
4776     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
4777     if (Idx == 0)
4778       return Op;
4779
4780     // UNPCKHPD the element to the lowest double word, then movsd.
4781     // Note if the lower 64 bits of the result of the UNPCKHPD is then stored
4782     // to a f64mem, the whole operation is folded into a single MOVHPDmr.
4783     int Mask[2] = { 1, -1 };
4784     EVT VVT = Op.getOperand(0).getValueType();
4785     SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
4786                                        DAG.getUNDEF(VVT), Mask);
4787     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
4788                        DAG.getIntPtrConstant(0));
4789   }
4790
4791   return SDValue();
4792 }
4793
4794 SDValue
4795 X86TargetLowering::LowerINSERT_VECTOR_ELT_SSE4(SDValue Op, SelectionDAG &DAG){
4796   EVT VT = Op.getValueType();
4797   EVT EltVT = VT.getVectorElementType();
4798   DebugLoc dl = Op.getDebugLoc();
4799
4800   SDValue N0 = Op.getOperand(0);
4801   SDValue N1 = Op.getOperand(1);
4802   SDValue N2 = Op.getOperand(2);
4803
4804   if ((EltVT.getSizeInBits() == 8 || EltVT.getSizeInBits() == 16) &&
4805       isa<ConstantSDNode>(N2)) {
4806     unsigned Opc = (EltVT.getSizeInBits() == 8) ? X86ISD::PINSRB
4807                                                 : X86ISD::PINSRW;
4808     // Transform it so it match pinsr{b,w} which expects a GR32 as its second
4809     // argument.
4810     if (N1.getValueType() != MVT::i32)
4811       N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
4812     if (N2.getValueType() != MVT::i32)
4813       N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue());
4814     return DAG.getNode(Opc, dl, VT, N0, N1, N2);
4815   } else if (EltVT == MVT::f32 && isa<ConstantSDNode>(N2)) {
4816     // Bits [7:6] of the constant are the source select.  This will always be
4817     //  zero here.  The DAG Combiner may combine an extract_elt index into these
4818     //  bits.  For example (insert (extract, 3), 2) could be matched by putting
4819     //  the '3' into bits [7:6] of X86ISD::INSERTPS.
4820     // Bits [5:4] of the constant are the destination select.  This is the
4821     //  value of the incoming immediate.
4822     // Bits [3:0] of the constant are the zero mask.  The DAG Combiner may
4823     //   combine either bitwise AND or insert of float 0.0 to set these bits.
4824     N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue() << 4);
4825     // Create this as a scalar to vector..
4826     N1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4f32, N1);
4827     return DAG.getNode(X86ISD::INSERTPS, dl, VT, N0, N1, N2);
4828   } else if (EltVT == MVT::i32 && isa<ConstantSDNode>(N2)) {
4829     // PINSR* works with constant index.
4830     return Op;
4831   }
4832   return SDValue();
4833 }
4834
4835 SDValue
4836 X86TargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) {
4837   EVT VT = Op.getValueType();
4838   EVT EltVT = VT.getVectorElementType();
4839
4840   if (Subtarget->hasSSE41())
4841     return LowerINSERT_VECTOR_ELT_SSE4(Op, DAG);
4842
4843   if (EltVT == MVT::i8)
4844     return SDValue();
4845
4846   DebugLoc dl = Op.getDebugLoc();
4847   SDValue N0 = Op.getOperand(0);
4848   SDValue N1 = Op.getOperand(1);
4849   SDValue N2 = Op.getOperand(2);
4850
4851   if (EltVT.getSizeInBits() == 16 && isa<ConstantSDNode>(N2)) {
4852     // Transform it so it match pinsrw which expects a 16-bit value in a GR32
4853     // as its second argument.
4854     if (N1.getValueType() != MVT::i32)
4855       N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
4856     if (N2.getValueType() != MVT::i32)
4857       N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue());
4858     return DAG.getNode(X86ISD::PINSRW, dl, VT, N0, N1, N2);
4859   }
4860   return SDValue();
4861 }
4862
4863 SDValue
4864 X86TargetLowering::LowerSCALAR_TO_VECTOR(SDValue Op, SelectionDAG &DAG) {
4865   DebugLoc dl = Op.getDebugLoc();
4866   if (Op.getValueType() == MVT::v2f32)
4867     return DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v2f32,
4868                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i32,
4869                                    DAG.getNode(ISD::BIT_CONVERT, dl, MVT::i32,
4870                                                Op.getOperand(0))));
4871
4872   if (Op.getValueType() == MVT::v1i64 && Op.getOperand(0).getValueType() == MVT::i64)
4873     return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v1i64, Op.getOperand(0));
4874
4875   SDValue AnyExt = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, Op.getOperand(0));
4876   EVT VT = MVT::v2i32;
4877   switch (Op.getValueType().getSimpleVT().SimpleTy) {
4878   default: break;
4879   case MVT::v16i8:
4880   case MVT::v8i16:
4881     VT = MVT::v4i32;
4882     break;
4883   }
4884   return DAG.getNode(ISD::BIT_CONVERT, dl, Op.getValueType(),
4885                      DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, AnyExt));
4886 }
4887
4888 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
4889 // their target countpart wrapped in the X86ISD::Wrapper node. Suppose N is
4890 // one of the above mentioned nodes. It has to be wrapped because otherwise
4891 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
4892 // be used to form addressing mode. These wrapped nodes will be selected
4893 // into MOV32ri.
4894 SDValue
4895 X86TargetLowering::LowerConstantPool(SDValue Op, SelectionDAG &DAG) {
4896   ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
4897
4898   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
4899   // global base reg.
4900   unsigned char OpFlag = 0;
4901   unsigned WrapperKind = X86ISD::Wrapper;
4902   CodeModel::Model M = getTargetMachine().getCodeModel();
4903
4904   if (Subtarget->isPICStyleRIPRel() &&
4905       (M == CodeModel::Small || M == CodeModel::Kernel))
4906     WrapperKind = X86ISD::WrapperRIP;
4907   else if (Subtarget->isPICStyleGOT())
4908     OpFlag = X86II::MO_GOTOFF;
4909   else if (Subtarget->isPICStyleStubPIC())
4910     OpFlag = X86II::MO_PIC_BASE_OFFSET;
4911
4912   SDValue Result = DAG.getTargetConstantPool(CP->getConstVal(), getPointerTy(),
4913                                              CP->getAlignment(),
4914                                              CP->getOffset(), OpFlag);
4915   DebugLoc DL = CP->getDebugLoc();
4916   Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
4917   // With PIC, the address is actually $g + Offset.
4918   if (OpFlag) {
4919     Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
4920                          DAG.getNode(X86ISD::GlobalBaseReg,
4921                                      DebugLoc::getUnknownLoc(), getPointerTy()),
4922                          Result);
4923   }
4924
4925   return Result;
4926 }
4927
4928 SDValue X86TargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) {
4929   JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
4930
4931   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
4932   // global base reg.
4933   unsigned char OpFlag = 0;
4934   unsigned WrapperKind = X86ISD::Wrapper;
4935   CodeModel::Model M = getTargetMachine().getCodeModel();
4936
4937   if (Subtarget->isPICStyleRIPRel() &&
4938       (M == CodeModel::Small || M == CodeModel::Kernel))
4939     WrapperKind = X86ISD::WrapperRIP;
4940   else if (Subtarget->isPICStyleGOT())
4941     OpFlag = X86II::MO_GOTOFF;
4942   else if (Subtarget->isPICStyleStubPIC())
4943     OpFlag = X86II::MO_PIC_BASE_OFFSET;
4944
4945   SDValue Result = DAG.getTargetJumpTable(JT->getIndex(), getPointerTy(),
4946                                           OpFlag);
4947   DebugLoc DL = JT->getDebugLoc();
4948   Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
4949
4950   // With PIC, the address is actually $g + Offset.
4951   if (OpFlag) {
4952     Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
4953                          DAG.getNode(X86ISD::GlobalBaseReg,
4954                                      DebugLoc::getUnknownLoc(), getPointerTy()),
4955                          Result);
4956   }
4957
4958   return Result;
4959 }
4960
4961 SDValue
4962 X86TargetLowering::LowerExternalSymbol(SDValue Op, SelectionDAG &DAG) {
4963   const char *Sym = cast<ExternalSymbolSDNode>(Op)->getSymbol();
4964
4965   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
4966   // global base reg.
4967   unsigned char OpFlag = 0;
4968   unsigned WrapperKind = X86ISD::Wrapper;
4969   CodeModel::Model M = getTargetMachine().getCodeModel();
4970
4971   if (Subtarget->isPICStyleRIPRel() &&
4972       (M == CodeModel::Small || M == CodeModel::Kernel))
4973     WrapperKind = X86ISD::WrapperRIP;
4974   else if (Subtarget->isPICStyleGOT())
4975     OpFlag = X86II::MO_GOTOFF;
4976   else if (Subtarget->isPICStyleStubPIC())
4977     OpFlag = X86II::MO_PIC_BASE_OFFSET;
4978
4979   SDValue Result = DAG.getTargetExternalSymbol(Sym, getPointerTy(), OpFlag);
4980
4981   DebugLoc DL = Op.getDebugLoc();
4982   Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
4983
4984
4985   // With PIC, the address is actually $g + Offset.
4986   if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
4987       !Subtarget->is64Bit()) {
4988     Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
4989                          DAG.getNode(X86ISD::GlobalBaseReg,
4990                                      DebugLoc::getUnknownLoc(),
4991                                      getPointerTy()),
4992                          Result);
4993   }
4994
4995   return Result;
4996 }
4997
4998 SDValue
4999 X86TargetLowering::LowerBlockAddress(SDValue Op, SelectionDAG &DAG) {
5000   // Create the TargetBlockAddressAddress node.
5001   unsigned char OpFlags =
5002     Subtarget->ClassifyBlockAddressReference();
5003   CodeModel::Model M = getTargetMachine().getCodeModel();
5004   BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
5005   DebugLoc dl = Op.getDebugLoc();
5006   SDValue Result = DAG.getBlockAddress(BA, getPointerTy(),
5007                                        /*isTarget=*/true, OpFlags);
5008
5009   if (Subtarget->isPICStyleRIPRel() &&
5010       (M == CodeModel::Small || M == CodeModel::Kernel))
5011     Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
5012   else
5013     Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
5014
5015   // With PIC, the address is actually $g + Offset.
5016   if (isGlobalRelativeToPICBase(OpFlags)) {
5017     Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
5018                          DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
5019                          Result);
5020   }
5021
5022   return Result;
5023 }
5024
5025 SDValue
5026 X86TargetLowering::LowerGlobalAddress(const GlobalValue *GV, DebugLoc dl,
5027                                       int64_t Offset,
5028                                       SelectionDAG &DAG) const {
5029   // Create the TargetGlobalAddress node, folding in the constant
5030   // offset if it is legal.
5031   unsigned char OpFlags =
5032     Subtarget->ClassifyGlobalReference(GV, getTargetMachine());
5033   CodeModel::Model M = getTargetMachine().getCodeModel();
5034   SDValue Result;
5035   if (OpFlags == X86II::MO_NO_FLAG &&
5036       X86::isOffsetSuitableForCodeModel(Offset, M)) {
5037     // A direct static reference to a global.
5038     Result = DAG.getTargetGlobalAddress(GV, getPointerTy(), Offset);
5039     Offset = 0;
5040   } else {
5041     Result = DAG.getTargetGlobalAddress(GV, getPointerTy(), 0, OpFlags);
5042   }
5043
5044   if (Subtarget->isPICStyleRIPRel() &&
5045       (M == CodeModel::Small || M == CodeModel::Kernel))
5046     Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
5047   else
5048     Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
5049
5050   // With PIC, the address is actually $g + Offset.
5051   if (isGlobalRelativeToPICBase(OpFlags)) {
5052     Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
5053                          DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
5054                          Result);
5055   }
5056
5057   // For globals that require a load from a stub to get the address, emit the
5058   // load.
5059   if (isGlobalStubReference(OpFlags))
5060     Result = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Result,
5061                          PseudoSourceValue::getGOT(), 0);
5062
5063   // If there was a non-zero offset that we didn't fold, create an explicit
5064   // addition for it.
5065   if (Offset != 0)
5066     Result = DAG.getNode(ISD::ADD, dl, getPointerTy(), Result,
5067                          DAG.getConstant(Offset, getPointerTy()));
5068
5069   return Result;
5070 }
5071
5072 SDValue
5073 X86TargetLowering::LowerGlobalAddress(SDValue Op, SelectionDAG &DAG) {
5074   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
5075   int64_t Offset = cast<GlobalAddressSDNode>(Op)->getOffset();
5076   return LowerGlobalAddress(GV, Op.getDebugLoc(), Offset, DAG);
5077 }
5078
5079 static SDValue
5080 GetTLSADDR(SelectionDAG &DAG, SDValue Chain, GlobalAddressSDNode *GA,
5081            SDValue *InFlag, const EVT PtrVT, unsigned ReturnReg,
5082            unsigned char OperandFlags) {
5083   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
5084   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Flag);
5085   DebugLoc dl = GA->getDebugLoc();
5086   SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(),
5087                                            GA->getValueType(0),
5088                                            GA->getOffset(),
5089                                            OperandFlags);
5090   if (InFlag) {
5091     SDValue Ops[] = { Chain,  TGA, *InFlag };
5092     Chain = DAG.getNode(X86ISD::TLSADDR, dl, NodeTys, Ops, 3);
5093   } else {
5094     SDValue Ops[]  = { Chain, TGA };
5095     Chain = DAG.getNode(X86ISD::TLSADDR, dl, NodeTys, Ops, 2);
5096   }
5097
5098   // TLSADDR will be codegen'ed as call. Inform MFI that function has calls.
5099   MFI->setHasCalls(true);
5100
5101   SDValue Flag = Chain.getValue(1);
5102   return DAG.getCopyFromReg(Chain, dl, ReturnReg, PtrVT, Flag);
5103 }
5104
5105 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 32 bit
5106 static SDValue
5107 LowerToTLSGeneralDynamicModel32(GlobalAddressSDNode *GA, SelectionDAG &DAG,
5108                                 const EVT PtrVT) {
5109   SDValue InFlag;
5110   DebugLoc dl = GA->getDebugLoc();  // ? function entry point might be better
5111   SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
5112                                      DAG.getNode(X86ISD::GlobalBaseReg,
5113                                                  DebugLoc::getUnknownLoc(),
5114                                                  PtrVT), InFlag);
5115   InFlag = Chain.getValue(1);
5116
5117   return GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX, X86II::MO_TLSGD);
5118 }
5119
5120 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 64 bit
5121 static SDValue
5122 LowerToTLSGeneralDynamicModel64(GlobalAddressSDNode *GA, SelectionDAG &DAG,
5123                                 const EVT PtrVT) {
5124   return GetTLSADDR(DAG, DAG.getEntryNode(), GA, NULL, PtrVT,
5125                     X86::RAX, X86II::MO_TLSGD);
5126 }
5127
5128 // Lower ISD::GlobalTLSAddress using the "initial exec" (for no-pic) or
5129 // "local exec" model.
5130 static SDValue LowerToTLSExecModel(GlobalAddressSDNode *GA, SelectionDAG &DAG,
5131                                    const EVT PtrVT, TLSModel::Model model,
5132                                    bool is64Bit) {
5133   DebugLoc dl = GA->getDebugLoc();
5134   // Get the Thread Pointer
5135   SDValue Base = DAG.getNode(X86ISD::SegmentBaseAddress,
5136                              DebugLoc::getUnknownLoc(), PtrVT,
5137                              DAG.getRegister(is64Bit? X86::FS : X86::GS,
5138                                              MVT::i32));
5139
5140   SDValue ThreadPointer = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Base,
5141                                       NULL, 0);
5142
5143   unsigned char OperandFlags = 0;
5144   // Most TLS accesses are not RIP relative, even on x86-64.  One exception is
5145   // initialexec.
5146   unsigned WrapperKind = X86ISD::Wrapper;
5147   if (model == TLSModel::LocalExec) {
5148     OperandFlags = is64Bit ? X86II::MO_TPOFF : X86II::MO_NTPOFF;
5149   } else if (is64Bit) {
5150     assert(model == TLSModel::InitialExec);
5151     OperandFlags = X86II::MO_GOTTPOFF;
5152     WrapperKind = X86ISD::WrapperRIP;
5153   } else {
5154     assert(model == TLSModel::InitialExec);
5155     OperandFlags = X86II::MO_INDNTPOFF;
5156   }
5157
5158   // emit "addl x@ntpoff,%eax" (local exec) or "addl x@indntpoff,%eax" (initial
5159   // exec)
5160   SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), GA->getValueType(0),
5161                                            GA->getOffset(), OperandFlags);
5162   SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
5163
5164   if (model == TLSModel::InitialExec)
5165     Offset = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Offset,
5166                          PseudoSourceValue::getGOT(), 0);
5167
5168   // The address of the thread local variable is the add of the thread
5169   // pointer with the offset of the variable.
5170   return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
5171 }
5172
5173 SDValue
5174 X86TargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) {
5175   // TODO: implement the "local dynamic" model
5176   // TODO: implement the "initial exec"model for pic executables
5177   assert(Subtarget->isTargetELF() &&
5178          "TLS not implemented for non-ELF targets");
5179   GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
5180   const GlobalValue *GV = GA->getGlobal();
5181
5182   // If GV is an alias then use the aliasee for determining
5183   // thread-localness.
5184   if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(GV))
5185     GV = GA->resolveAliasedGlobal(false);
5186
5187   TLSModel::Model model = getTLSModel(GV,
5188                                       getTargetMachine().getRelocationModel());
5189
5190   switch (model) {
5191   case TLSModel::GeneralDynamic:
5192   case TLSModel::LocalDynamic: // not implemented
5193     if (Subtarget->is64Bit())
5194       return LowerToTLSGeneralDynamicModel64(GA, DAG, getPointerTy());
5195     return LowerToTLSGeneralDynamicModel32(GA, DAG, getPointerTy());
5196
5197   case TLSModel::InitialExec:
5198   case TLSModel::LocalExec:
5199     return LowerToTLSExecModel(GA, DAG, getPointerTy(), model,
5200                                Subtarget->is64Bit());
5201   }
5202
5203   llvm_unreachable("Unreachable");
5204   return SDValue();
5205 }
5206
5207
5208 /// LowerShift - Lower SRA_PARTS and friends, which return two i32 values and
5209 /// take a 2 x i32 value to shift plus a shift amount.
5210 SDValue X86TargetLowering::LowerShift(SDValue Op, SelectionDAG &DAG) {
5211   assert(Op.getNumOperands() == 3 && "Not a double-shift!");
5212   EVT VT = Op.getValueType();
5213   unsigned VTBits = VT.getSizeInBits();
5214   DebugLoc dl = Op.getDebugLoc();
5215   bool isSRA = Op.getOpcode() == ISD::SRA_PARTS;
5216   SDValue ShOpLo = Op.getOperand(0);
5217   SDValue ShOpHi = Op.getOperand(1);
5218   SDValue ShAmt  = Op.getOperand(2);
5219   SDValue Tmp1 = isSRA ? DAG.getNode(ISD::SRA, dl, VT, ShOpHi,
5220                                      DAG.getConstant(VTBits - 1, MVT::i8))
5221                        : DAG.getConstant(0, VT);
5222
5223   SDValue Tmp2, Tmp3;
5224   if (Op.getOpcode() == ISD::SHL_PARTS) {
5225     Tmp2 = DAG.getNode(X86ISD::SHLD, dl, VT, ShOpHi, ShOpLo, ShAmt);
5226     Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ShAmt);
5227   } else {
5228     Tmp2 = DAG.getNode(X86ISD::SHRD, dl, VT, ShOpLo, ShOpHi, ShAmt);
5229     Tmp3 = DAG.getNode(isSRA ? ISD::SRA : ISD::SRL, dl, VT, ShOpHi, ShAmt);
5230   }
5231
5232   SDValue AndNode = DAG.getNode(ISD::AND, dl, MVT::i8, ShAmt,
5233                                 DAG.getConstant(VTBits, MVT::i8));
5234   SDValue Cond = DAG.getNode(X86ISD::CMP, dl, VT,
5235                              AndNode, DAG.getConstant(0, MVT::i8));
5236
5237   SDValue Hi, Lo;
5238   SDValue CC = DAG.getConstant(X86::COND_NE, MVT::i8);
5239   SDValue Ops0[4] = { Tmp2, Tmp3, CC, Cond };
5240   SDValue Ops1[4] = { Tmp3, Tmp1, CC, Cond };
5241
5242   if (Op.getOpcode() == ISD::SHL_PARTS) {
5243     Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0, 4);
5244     Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1, 4);
5245   } else {
5246     Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0, 4);
5247     Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1, 4);
5248   }
5249
5250   SDValue Ops[2] = { Lo, Hi };
5251   return DAG.getMergeValues(Ops, 2, dl);
5252 }
5253
5254 SDValue X86TargetLowering::LowerSINT_TO_FP(SDValue Op, SelectionDAG &DAG) {
5255   EVT SrcVT = Op.getOperand(0).getValueType();
5256
5257   if (SrcVT.isVector()) {
5258     if (SrcVT == MVT::v2i32 && Op.getValueType() == MVT::v2f64) {
5259       return Op;
5260     }
5261     return SDValue();
5262   }
5263
5264   assert(SrcVT.getSimpleVT() <= MVT::i64 && SrcVT.getSimpleVT() >= MVT::i16 &&
5265          "Unknown SINT_TO_FP to lower!");
5266
5267   // These are really Legal; return the operand so the caller accepts it as
5268   // Legal.
5269   if (SrcVT == MVT::i32 && isScalarFPTypeInSSEReg(Op.getValueType()))
5270     return Op;
5271   if (SrcVT == MVT::i64 && isScalarFPTypeInSSEReg(Op.getValueType()) &&
5272       Subtarget->is64Bit()) {
5273     return Op;
5274   }
5275
5276   DebugLoc dl = Op.getDebugLoc();
5277   unsigned Size = SrcVT.getSizeInBits()/8;
5278   MachineFunction &MF = DAG.getMachineFunction();
5279   int SSFI = MF.getFrameInfo()->CreateStackObject(Size, Size, false);
5280   SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
5281   SDValue Chain = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
5282                                StackSlot,
5283                                PseudoSourceValue::getFixedStack(SSFI), 0);
5284   return BuildFILD(Op, SrcVT, Chain, StackSlot, DAG);
5285 }
5286
5287 SDValue X86TargetLowering::BuildFILD(SDValue Op, EVT SrcVT, SDValue Chain,
5288                                      SDValue StackSlot,
5289                                      SelectionDAG &DAG) {
5290   // Build the FILD
5291   DebugLoc dl = Op.getDebugLoc();
5292   SDVTList Tys;
5293   bool useSSE = isScalarFPTypeInSSEReg(Op.getValueType());
5294   if (useSSE)
5295     Tys = DAG.getVTList(MVT::f64, MVT::Other, MVT::Flag);
5296   else
5297     Tys = DAG.getVTList(Op.getValueType(), MVT::Other);
5298   SDValue Ops[] = { Chain, StackSlot, DAG.getValueType(SrcVT) };
5299   SDValue Result = DAG.getNode(useSSE ? X86ISD::FILD_FLAG : X86ISD::FILD, dl,
5300                                Tys, Ops, array_lengthof(Ops));
5301
5302   if (useSSE) {
5303     Chain = Result.getValue(1);
5304     SDValue InFlag = Result.getValue(2);
5305
5306     // FIXME: Currently the FST is flagged to the FILD_FLAG. This
5307     // shouldn't be necessary except that RFP cannot be live across
5308     // multiple blocks. When stackifier is fixed, they can be uncoupled.
5309     MachineFunction &MF = DAG.getMachineFunction();
5310     int SSFI = MF.getFrameInfo()->CreateStackObject(8, 8, false);
5311     SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
5312     Tys = DAG.getVTList(MVT::Other);
5313     SDValue Ops[] = {
5314       Chain, Result, StackSlot, DAG.getValueType(Op.getValueType()), InFlag
5315     };
5316     Chain = DAG.getNode(X86ISD::FST, dl, Tys, Ops, array_lengthof(Ops));
5317     Result = DAG.getLoad(Op.getValueType(), dl, Chain, StackSlot,
5318                          PseudoSourceValue::getFixedStack(SSFI), 0);
5319   }
5320
5321   return Result;
5322 }
5323
5324 // LowerUINT_TO_FP_i64 - 64-bit unsigned integer to double expansion.
5325 SDValue X86TargetLowering::LowerUINT_TO_FP_i64(SDValue Op, SelectionDAG &DAG) {
5326   // This algorithm is not obvious. Here it is in C code, more or less:
5327   /*
5328     double uint64_to_double( uint32_t hi, uint32_t lo ) {
5329       static const __m128i exp = { 0x4330000045300000ULL, 0 };
5330       static const __m128d bias = { 0x1.0p84, 0x1.0p52 };
5331
5332       // Copy ints to xmm registers.
5333       __m128i xh = _mm_cvtsi32_si128( hi );
5334       __m128i xl = _mm_cvtsi32_si128( lo );
5335
5336       // Combine into low half of a single xmm register.
5337       __m128i x = _mm_unpacklo_epi32( xh, xl );
5338       __m128d d;
5339       double sd;
5340
5341       // Merge in appropriate exponents to give the integer bits the right
5342       // magnitude.
5343       x = _mm_unpacklo_epi32( x, exp );
5344
5345       // Subtract away the biases to deal with the IEEE-754 double precision
5346       // implicit 1.
5347       d = _mm_sub_pd( (__m128d) x, bias );
5348
5349       // All conversions up to here are exact. The correctly rounded result is
5350       // calculated using the current rounding mode using the following
5351       // horizontal add.
5352       d = _mm_add_sd( d, _mm_unpackhi_pd( d, d ) );
5353       _mm_store_sd( &sd, d );   // Because we are returning doubles in XMM, this
5354                                 // store doesn't really need to be here (except
5355                                 // maybe to zero the other double)
5356       return sd;
5357     }
5358   */
5359
5360   DebugLoc dl = Op.getDebugLoc();
5361   LLVMContext *Context = DAG.getContext();
5362
5363   // Build some magic constants.
5364   std::vector<Constant*> CV0;
5365   CV0.push_back(ConstantInt::get(*Context, APInt(32, 0x45300000)));
5366   CV0.push_back(ConstantInt::get(*Context, APInt(32, 0x43300000)));
5367   CV0.push_back(ConstantInt::get(*Context, APInt(32, 0)));
5368   CV0.push_back(ConstantInt::get(*Context, APInt(32, 0)));
5369   Constant *C0 = ConstantVector::get(CV0);
5370   SDValue CPIdx0 = DAG.getConstantPool(C0, getPointerTy(), 16);
5371
5372   std::vector<Constant*> CV1;
5373   CV1.push_back(
5374     ConstantFP::get(*Context, APFloat(APInt(64, 0x4530000000000000ULL))));
5375   CV1.push_back(
5376     ConstantFP::get(*Context, APFloat(APInt(64, 0x4330000000000000ULL))));
5377   Constant *C1 = ConstantVector::get(CV1);
5378   SDValue CPIdx1 = DAG.getConstantPool(C1, getPointerTy(), 16);
5379
5380   SDValue XR1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
5381                             DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
5382                                         Op.getOperand(0),
5383                                         DAG.getIntPtrConstant(1)));
5384   SDValue XR2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
5385                             DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
5386                                         Op.getOperand(0),
5387                                         DAG.getIntPtrConstant(0)));
5388   SDValue Unpck1 = getUnpackl(DAG, dl, MVT::v4i32, XR1, XR2);
5389   SDValue CLod0 = DAG.getLoad(MVT::v4i32, dl, DAG.getEntryNode(), CPIdx0,
5390                               PseudoSourceValue::getConstantPool(), 0,
5391                               false, 16);
5392   SDValue Unpck2 = getUnpackl(DAG, dl, MVT::v4i32, Unpck1, CLod0);
5393   SDValue XR2F = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v2f64, Unpck2);
5394   SDValue CLod1 = DAG.getLoad(MVT::v2f64, dl, CLod0.getValue(1), CPIdx1,
5395                               PseudoSourceValue::getConstantPool(), 0,
5396                               false, 16);
5397   SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, XR2F, CLod1);
5398
5399   // Add the halves; easiest way is to swap them into another reg first.
5400   int ShufMask[2] = { 1, -1 };
5401   SDValue Shuf = DAG.getVectorShuffle(MVT::v2f64, dl, Sub,
5402                                       DAG.getUNDEF(MVT::v2f64), ShufMask);
5403   SDValue Add = DAG.getNode(ISD::FADD, dl, MVT::v2f64, Shuf, Sub);
5404   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Add,
5405                      DAG.getIntPtrConstant(0));
5406 }
5407
5408 // LowerUINT_TO_FP_i32 - 32-bit unsigned integer to float expansion.
5409 SDValue X86TargetLowering::LowerUINT_TO_FP_i32(SDValue Op, SelectionDAG &DAG) {
5410   DebugLoc dl = Op.getDebugLoc();
5411   // FP constant to bias correct the final result.
5412   SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL),
5413                                    MVT::f64);
5414
5415   // Load the 32-bit value into an XMM register.
5416   SDValue Load = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
5417                              DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
5418                                          Op.getOperand(0),
5419                                          DAG.getIntPtrConstant(0)));
5420
5421   Load = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
5422                      DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v2f64, Load),
5423                      DAG.getIntPtrConstant(0));
5424
5425   // Or the load with the bias.
5426   SDValue Or = DAG.getNode(ISD::OR, dl, MVT::v2i64,
5427                            DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v2i64,
5428                                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
5429                                                    MVT::v2f64, Load)),
5430                            DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v2i64,
5431                                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
5432                                                    MVT::v2f64, Bias)));
5433   Or = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
5434                    DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v2f64, Or),
5435                    DAG.getIntPtrConstant(0));
5436
5437   // Subtract the bias.
5438   SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::f64, Or, Bias);
5439
5440   // Handle final rounding.
5441   EVT DestVT = Op.getValueType();
5442
5443   if (DestVT.bitsLT(MVT::f64)) {
5444     return DAG.getNode(ISD::FP_ROUND, dl, DestVT, Sub,
5445                        DAG.getIntPtrConstant(0));
5446   } else if (DestVT.bitsGT(MVT::f64)) {
5447     return DAG.getNode(ISD::FP_EXTEND, dl, DestVT, Sub);
5448   }
5449
5450   // Handle final rounding.
5451   return Sub;
5452 }
5453
5454 SDValue X86TargetLowering::LowerUINT_TO_FP(SDValue Op, SelectionDAG &DAG) {
5455   SDValue N0 = Op.getOperand(0);
5456   DebugLoc dl = Op.getDebugLoc();
5457
5458   // Now not UINT_TO_FP is legal (it's marked custom), dag combiner won't
5459   // optimize it to a SINT_TO_FP when the sign bit is known zero. Perform
5460   // the optimization here.
5461   if (DAG.SignBitIsZero(N0))
5462     return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(), N0);
5463
5464   EVT SrcVT = N0.getValueType();
5465   if (SrcVT == MVT::i64) {
5466     // We only handle SSE2 f64 target here; caller can expand the rest.
5467     if (Op.getValueType() != MVT::f64 || !X86ScalarSSEf64)
5468       return SDValue();
5469
5470     return LowerUINT_TO_FP_i64(Op, DAG);
5471   } else if (SrcVT == MVT::i32 && X86ScalarSSEf64) {
5472     return LowerUINT_TO_FP_i32(Op, DAG);
5473   }
5474
5475   assert(SrcVT == MVT::i32 && "Unknown UINT_TO_FP to lower!");
5476
5477   // Make a 64-bit buffer, and use it to build an FILD.
5478   SDValue StackSlot = DAG.CreateStackTemporary(MVT::i64);
5479   SDValue WordOff = DAG.getConstant(4, getPointerTy());
5480   SDValue OffsetSlot = DAG.getNode(ISD::ADD, dl,
5481                                    getPointerTy(), StackSlot, WordOff);
5482   SDValue Store1 = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
5483                                 StackSlot, NULL, 0);
5484   SDValue Store2 = DAG.getStore(Store1, dl, DAG.getConstant(0, MVT::i32),
5485                                 OffsetSlot, NULL, 0);
5486   return BuildFILD(Op, MVT::i64, Store2, StackSlot, DAG);
5487 }
5488
5489 std::pair<SDValue,SDValue> X86TargetLowering::
5490 FP_TO_INTHelper(SDValue Op, SelectionDAG &DAG, bool IsSigned) {
5491   DebugLoc dl = Op.getDebugLoc();
5492
5493   EVT DstTy = Op.getValueType();
5494
5495   if (!IsSigned) {
5496     assert(DstTy == MVT::i32 && "Unexpected FP_TO_UINT");
5497     DstTy = MVT::i64;
5498   }
5499
5500   assert(DstTy.getSimpleVT() <= MVT::i64 &&
5501          DstTy.getSimpleVT() >= MVT::i16 &&
5502          "Unknown FP_TO_SINT to lower!");
5503
5504   // These are really Legal.
5505   if (DstTy == MVT::i32 &&
5506       isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
5507     return std::make_pair(SDValue(), SDValue());
5508   if (Subtarget->is64Bit() &&
5509       DstTy == MVT::i64 &&
5510       isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
5511     return std::make_pair(SDValue(), SDValue());
5512
5513   // We lower FP->sint64 into FISTP64, followed by a load, all to a temporary
5514   // stack slot.
5515   MachineFunction &MF = DAG.getMachineFunction();
5516   unsigned MemSize = DstTy.getSizeInBits()/8;
5517   int SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
5518   SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
5519
5520   unsigned Opc;
5521   switch (DstTy.getSimpleVT().SimpleTy) {
5522   default: llvm_unreachable("Invalid FP_TO_SINT to lower!");
5523   case MVT::i16: Opc = X86ISD::FP_TO_INT16_IN_MEM; break;
5524   case MVT::i32: Opc = X86ISD::FP_TO_INT32_IN_MEM; break;
5525   case MVT::i64: Opc = X86ISD::FP_TO_INT64_IN_MEM; break;
5526   }
5527
5528   SDValue Chain = DAG.getEntryNode();
5529   SDValue Value = Op.getOperand(0);
5530   if (isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType())) {
5531     assert(DstTy == MVT::i64 && "Invalid FP_TO_SINT to lower!");
5532     Chain = DAG.getStore(Chain, dl, Value, StackSlot,
5533                          PseudoSourceValue::getFixedStack(SSFI), 0);
5534     SDVTList Tys = DAG.getVTList(Op.getOperand(0).getValueType(), MVT::Other);
5535     SDValue Ops[] = {
5536       Chain, StackSlot, DAG.getValueType(Op.getOperand(0).getValueType())
5537     };
5538     Value = DAG.getNode(X86ISD::FLD, dl, Tys, Ops, 3);
5539     Chain = Value.getValue(1);
5540     SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
5541     StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
5542   }
5543
5544   // Build the FP_TO_INT*_IN_MEM
5545   SDValue Ops[] = { Chain, Value, StackSlot };
5546   SDValue FIST = DAG.getNode(Opc, dl, MVT::Other, Ops, 3);
5547
5548   return std::make_pair(FIST, StackSlot);
5549 }
5550
5551 SDValue X86TargetLowering::LowerFP_TO_SINT(SDValue Op, SelectionDAG &DAG) {
5552   if (Op.getValueType().isVector()) {
5553     if (Op.getValueType() == MVT::v2i32 &&
5554         Op.getOperand(0).getValueType() == MVT::v2f64) {
5555       return Op;
5556     }
5557     return SDValue();
5558   }
5559
5560   std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG, true);
5561   SDValue FIST = Vals.first, StackSlot = Vals.second;
5562   // If FP_TO_INTHelper failed, the node is actually supposed to be Legal.
5563   if (FIST.getNode() == 0) return Op;
5564
5565   // Load the result.
5566   return DAG.getLoad(Op.getValueType(), Op.getDebugLoc(),
5567                      FIST, StackSlot, NULL, 0);
5568 }
5569
5570 SDValue X86TargetLowering::LowerFP_TO_UINT(SDValue Op, SelectionDAG &DAG) {
5571   std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG, false);
5572   SDValue FIST = Vals.first, StackSlot = Vals.second;
5573   assert(FIST.getNode() && "Unexpected failure");
5574
5575   // Load the result.
5576   return DAG.getLoad(Op.getValueType(), Op.getDebugLoc(),
5577                      FIST, StackSlot, NULL, 0);
5578 }
5579
5580 SDValue X86TargetLowering::LowerFABS(SDValue Op, SelectionDAG &DAG) {
5581   LLVMContext *Context = DAG.getContext();
5582   DebugLoc dl = Op.getDebugLoc();
5583   EVT VT = Op.getValueType();
5584   EVT EltVT = VT;
5585   if (VT.isVector())
5586     EltVT = VT.getVectorElementType();
5587   std::vector<Constant*> CV;
5588   if (EltVT == MVT::f64) {
5589     Constant *C = ConstantFP::get(*Context, APFloat(APInt(64, ~(1ULL << 63))));
5590     CV.push_back(C);
5591     CV.push_back(C);
5592   } else {
5593     Constant *C = ConstantFP::get(*Context, APFloat(APInt(32, ~(1U << 31))));
5594     CV.push_back(C);
5595     CV.push_back(C);
5596     CV.push_back(C);
5597     CV.push_back(C);
5598   }
5599   Constant *C = ConstantVector::get(CV);
5600   SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
5601   SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
5602                                PseudoSourceValue::getConstantPool(), 0,
5603                                false, 16);
5604   return DAG.getNode(X86ISD::FAND, dl, VT, Op.getOperand(0), Mask);
5605 }
5606
5607 SDValue X86TargetLowering::LowerFNEG(SDValue Op, SelectionDAG &DAG) {
5608   LLVMContext *Context = DAG.getContext();
5609   DebugLoc dl = Op.getDebugLoc();
5610   EVT VT = Op.getValueType();
5611   EVT EltVT = VT;
5612   if (VT.isVector())
5613     EltVT = VT.getVectorElementType();
5614   std::vector<Constant*> CV;
5615   if (EltVT == MVT::f64) {
5616     Constant *C = ConstantFP::get(*Context, APFloat(APInt(64, 1ULL << 63)));
5617     CV.push_back(C);
5618     CV.push_back(C);
5619   } else {
5620     Constant *C = ConstantFP::get(*Context, APFloat(APInt(32, 1U << 31)));
5621     CV.push_back(C);
5622     CV.push_back(C);
5623     CV.push_back(C);
5624     CV.push_back(C);
5625   }
5626   Constant *C = ConstantVector::get(CV);
5627   SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
5628   SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
5629                                PseudoSourceValue::getConstantPool(), 0,
5630                                false, 16);
5631   if (VT.isVector()) {
5632     return DAG.getNode(ISD::BIT_CONVERT, dl, VT,
5633                        DAG.getNode(ISD::XOR, dl, MVT::v2i64,
5634                     DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v2i64,
5635                                 Op.getOperand(0)),
5636                     DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v2i64, Mask)));
5637   } else {
5638     return DAG.getNode(X86ISD::FXOR, dl, VT, Op.getOperand(0), Mask);
5639   }
5640 }
5641
5642 SDValue X86TargetLowering::LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) {
5643   LLVMContext *Context = DAG.getContext();
5644   SDValue Op0 = Op.getOperand(0);
5645   SDValue Op1 = Op.getOperand(1);
5646   DebugLoc dl = Op.getDebugLoc();
5647   EVT VT = Op.getValueType();
5648   EVT SrcVT = Op1.getValueType();
5649
5650   // If second operand is smaller, extend it first.
5651   if (SrcVT.bitsLT(VT)) {
5652     Op1 = DAG.getNode(ISD::FP_EXTEND, dl, VT, Op1);
5653     SrcVT = VT;
5654   }
5655   // And if it is bigger, shrink it first.
5656   if (SrcVT.bitsGT(VT)) {
5657     Op1 = DAG.getNode(ISD::FP_ROUND, dl, VT, Op1, DAG.getIntPtrConstant(1));
5658     SrcVT = VT;
5659   }
5660
5661   // At this point the operands and the result should have the same
5662   // type, and that won't be f80 since that is not custom lowered.
5663
5664   // First get the sign bit of second operand.
5665   std::vector<Constant*> CV;
5666   if (SrcVT == MVT::f64) {
5667     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, 1ULL << 63))));
5668     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, 0))));
5669   } else {
5670     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 1U << 31))));
5671     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
5672     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
5673     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
5674   }
5675   Constant *C = ConstantVector::get(CV);
5676   SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
5677   SDValue Mask1 = DAG.getLoad(SrcVT, dl, DAG.getEntryNode(), CPIdx,
5678                                 PseudoSourceValue::getConstantPool(), 0,
5679                                 false, 16);
5680   SDValue SignBit = DAG.getNode(X86ISD::FAND, dl, SrcVT, Op1, Mask1);
5681
5682   // Shift sign bit right or left if the two operands have different types.
5683   if (SrcVT.bitsGT(VT)) {
5684     // Op0 is MVT::f32, Op1 is MVT::f64.
5685     SignBit = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f64, SignBit);
5686     SignBit = DAG.getNode(X86ISD::FSRL, dl, MVT::v2f64, SignBit,
5687                           DAG.getConstant(32, MVT::i32));
5688     SignBit = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v4f32, SignBit);
5689     SignBit = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f32, SignBit,
5690                           DAG.getIntPtrConstant(0));
5691   }
5692
5693   // Clear first operand sign bit.
5694   CV.clear();
5695   if (VT == MVT::f64) {
5696     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, ~(1ULL << 63)))));
5697     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, 0))));
5698   } else {
5699     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, ~(1U << 31)))));
5700     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
5701     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
5702     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
5703   }
5704   C = ConstantVector::get(CV);
5705   CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
5706   SDValue Mask2 = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
5707                                 PseudoSourceValue::getConstantPool(), 0,
5708                                 false, 16);
5709   SDValue Val = DAG.getNode(X86ISD::FAND, dl, VT, Op0, Mask2);
5710
5711   // Or the value with the sign bit.
5712   return DAG.getNode(X86ISD::FOR, dl, VT, Val, SignBit);
5713 }
5714
5715 /// Emit nodes that will be selected as "test Op0,Op0", or something
5716 /// equivalent.
5717 SDValue X86TargetLowering::EmitTest(SDValue Op, unsigned X86CC,
5718                                     SelectionDAG &DAG) {
5719   DebugLoc dl = Op.getDebugLoc();
5720
5721   // CF and OF aren't always set the way we want. Determine which
5722   // of these we need.
5723   bool NeedCF = false;
5724   bool NeedOF = false;
5725   switch (X86CC) {
5726   case X86::COND_A: case X86::COND_AE:
5727   case X86::COND_B: case X86::COND_BE:
5728     NeedCF = true;
5729     break;
5730   case X86::COND_G: case X86::COND_GE:
5731   case X86::COND_L: case X86::COND_LE:
5732   case X86::COND_O: case X86::COND_NO:
5733     NeedOF = true;
5734     break;
5735   default: break;
5736   }
5737
5738   // See if we can use the EFLAGS value from the operand instead of
5739   // doing a separate TEST. TEST always sets OF and CF to 0, so unless
5740   // we prove that the arithmetic won't overflow, we can't use OF or CF.
5741   if (Op.getResNo() == 0 && !NeedOF && !NeedCF) {
5742     unsigned Opcode = 0;
5743     unsigned NumOperands = 0;
5744     switch (Op.getNode()->getOpcode()) {
5745     case ISD::ADD:
5746       // Due to an isel shortcoming, be conservative if this add is likely to
5747       // be selected as part of a load-modify-store instruction. When the root
5748       // node in a match is a store, isel doesn't know how to remap non-chain
5749       // non-flag uses of other nodes in the match, such as the ADD in this
5750       // case. This leads to the ADD being left around and reselected, with
5751       // the result being two adds in the output.
5752       for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
5753            UE = Op.getNode()->use_end(); UI != UE; ++UI)
5754         if (UI->getOpcode() == ISD::STORE)
5755           goto default_case;
5756       if (ConstantSDNode *C =
5757             dyn_cast<ConstantSDNode>(Op.getNode()->getOperand(1))) {
5758         // An add of one will be selected as an INC.
5759         if (C->getAPIntValue() == 1) {
5760           Opcode = X86ISD::INC;
5761           NumOperands = 1;
5762           break;
5763         }
5764         // An add of negative one (subtract of one) will be selected as a DEC.
5765         if (C->getAPIntValue().isAllOnesValue()) {
5766           Opcode = X86ISD::DEC;
5767           NumOperands = 1;
5768           break;
5769         }
5770       }
5771       // Otherwise use a regular EFLAGS-setting add.
5772       Opcode = X86ISD::ADD;
5773       NumOperands = 2;
5774       break;
5775     case ISD::AND: {
5776       // If the primary and result isn't used, don't bother using X86ISD::AND,
5777       // because a TEST instruction will be better.
5778       bool NonFlagUse = false;
5779       for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
5780              UE = Op.getNode()->use_end(); UI != UE; ++UI) {
5781         SDNode *User = *UI;
5782         unsigned UOpNo = UI.getOperandNo();
5783         if (User->getOpcode() == ISD::TRUNCATE && User->hasOneUse()) {
5784           // Look pass truncate.
5785           UOpNo = User->use_begin().getOperandNo();
5786           User = *User->use_begin();
5787         }
5788         if (User->getOpcode() != ISD::BRCOND &&
5789             User->getOpcode() != ISD::SETCC &&
5790             (User->getOpcode() != ISD::SELECT || UOpNo != 0)) {
5791           NonFlagUse = true;
5792           break;
5793         }
5794       }
5795       if (!NonFlagUse)
5796         break;
5797     }
5798     // FALL THROUGH
5799     case ISD::SUB:
5800     case ISD::OR:
5801     case ISD::XOR:
5802       // Due to the ISEL shortcoming noted above, be conservative if this op is
5803       // likely to be selected as part of a load-modify-store instruction.
5804       for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
5805            UE = Op.getNode()->use_end(); UI != UE; ++UI)
5806         if (UI->getOpcode() == ISD::STORE)
5807           goto default_case;
5808       // Otherwise use a regular EFLAGS-setting instruction.
5809       switch (Op.getNode()->getOpcode()) {
5810       case ISD::SUB: Opcode = X86ISD::SUB; break;
5811       case ISD::OR:  Opcode = X86ISD::OR;  break;
5812       case ISD::XOR: Opcode = X86ISD::XOR; break;
5813       case ISD::AND: Opcode = X86ISD::AND; break;
5814       default: llvm_unreachable("unexpected operator!");
5815       }
5816       NumOperands = 2;
5817       break;
5818     case X86ISD::ADD:
5819     case X86ISD::SUB:
5820     case X86ISD::INC:
5821     case X86ISD::DEC:
5822     case X86ISD::OR:
5823     case X86ISD::XOR:
5824     case X86ISD::AND:
5825       return SDValue(Op.getNode(), 1);
5826     default:
5827     default_case:
5828       break;
5829     }
5830     if (Opcode != 0) {
5831       SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
5832       SmallVector<SDValue, 4> Ops;
5833       for (unsigned i = 0; i != NumOperands; ++i)
5834         Ops.push_back(Op.getOperand(i));
5835       SDValue New = DAG.getNode(Opcode, dl, VTs, &Ops[0], NumOperands);
5836       DAG.ReplaceAllUsesWith(Op, New);
5837       return SDValue(New.getNode(), 1);
5838     }
5839   }
5840
5841   // Otherwise just emit a CMP with 0, which is the TEST pattern.
5842   return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
5843                      DAG.getConstant(0, Op.getValueType()));
5844 }
5845
5846 /// Emit nodes that will be selected as "cmp Op0,Op1", or something
5847 /// equivalent.
5848 SDValue X86TargetLowering::EmitCmp(SDValue Op0, SDValue Op1, unsigned X86CC,
5849                                    SelectionDAG &DAG) {
5850   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op1))
5851     if (C->getAPIntValue() == 0)
5852       return EmitTest(Op0, X86CC, DAG);
5853
5854   DebugLoc dl = Op0.getDebugLoc();
5855   return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op0, Op1);
5856 }
5857
5858 /// LowerToBT - Result of 'and' is compared against zero. Turn it into a BT node
5859 /// if it's possible.
5860 static SDValue LowerToBT(SDValue Op0, ISD::CondCode CC,
5861                          DebugLoc dl, SelectionDAG &DAG) {
5862   SDValue LHS, RHS;
5863   if (Op0.getOperand(1).getOpcode() == ISD::SHL) {
5864     if (ConstantSDNode *Op010C =
5865         dyn_cast<ConstantSDNode>(Op0.getOperand(1).getOperand(0)))
5866       if (Op010C->getZExtValue() == 1) {
5867         LHS = Op0.getOperand(0);
5868         RHS = Op0.getOperand(1).getOperand(1);
5869       }
5870   } else if (Op0.getOperand(0).getOpcode() == ISD::SHL) {
5871     if (ConstantSDNode *Op000C =
5872         dyn_cast<ConstantSDNode>(Op0.getOperand(0).getOperand(0)))
5873       if (Op000C->getZExtValue() == 1) {
5874         LHS = Op0.getOperand(1);
5875         RHS = Op0.getOperand(0).getOperand(1);
5876       }
5877   } else if (Op0.getOperand(1).getOpcode() == ISD::Constant) {
5878     ConstantSDNode *AndRHS = cast<ConstantSDNode>(Op0.getOperand(1));
5879     SDValue AndLHS = Op0.getOperand(0);
5880     if (AndRHS->getZExtValue() == 1 && AndLHS.getOpcode() == ISD::SRL) {
5881       LHS = AndLHS.getOperand(0);
5882       RHS = AndLHS.getOperand(1);
5883     }
5884   }
5885
5886   if (LHS.getNode()) {
5887     // If LHS is i8, promote it to i16 with any_extend.  There is no i8 BT
5888     // instruction.  Since the shift amount is in-range-or-undefined, we know
5889     // that doing a bittest on the i16 value is ok.  We extend to i32 because
5890     // the encoding for the i16 version is larger than the i32 version.
5891     if (LHS.getValueType() == MVT::i8)
5892       LHS = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, LHS);
5893
5894     // If the operand types disagree, extend the shift amount to match.  Since
5895     // BT ignores high bits (like shifts) we can use anyextend.
5896     if (LHS.getValueType() != RHS.getValueType())
5897       RHS = DAG.getNode(ISD::ANY_EXTEND, dl, LHS.getValueType(), RHS);
5898
5899     SDValue BT = DAG.getNode(X86ISD::BT, dl, MVT::i32, LHS, RHS);
5900     unsigned Cond = CC == ISD::SETEQ ? X86::COND_AE : X86::COND_B;
5901     return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
5902                        DAG.getConstant(Cond, MVT::i8), BT);
5903   }
5904
5905   return SDValue();
5906 }
5907
5908 SDValue X86TargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) {
5909   assert(Op.getValueType() == MVT::i8 && "SetCC type must be 8-bit integer");
5910   SDValue Op0 = Op.getOperand(0);
5911   SDValue Op1 = Op.getOperand(1);
5912   DebugLoc dl = Op.getDebugLoc();
5913   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
5914
5915   // Optimize to BT if possible.
5916   // Lower (X & (1 << N)) == 0 to BT(X, N).
5917   // Lower ((X >>u N) & 1) != 0 to BT(X, N).
5918   // Lower ((X >>s N) & 1) != 0 to BT(X, N).
5919   if (Op0.getOpcode() == ISD::AND &&
5920       Op0.hasOneUse() &&
5921       Op1.getOpcode() == ISD::Constant &&
5922       cast<ConstantSDNode>(Op1)->getZExtValue() == 0 &&
5923       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
5924     SDValue NewSetCC = LowerToBT(Op0, CC, dl, DAG);
5925     if (NewSetCC.getNode())
5926       return NewSetCC;
5927   }
5928
5929   bool isFP = Op.getOperand(1).getValueType().isFloatingPoint();
5930   unsigned X86CC = TranslateX86CC(CC, isFP, Op0, Op1, DAG);
5931   if (X86CC == X86::COND_INVALID)
5932     return SDValue();
5933
5934   SDValue Cond = EmitCmp(Op0, Op1, X86CC, DAG);
5935
5936   // Use sbb x, x to materialize carry bit into a GPR.
5937   if (X86CC == X86::COND_B)
5938     return DAG.getNode(ISD::AND, dl, MVT::i8,
5939                        DAG.getNode(X86ISD::SETCC_CARRY, dl, MVT::i8,
5940                                    DAG.getConstant(X86CC, MVT::i8), Cond),
5941                        DAG.getConstant(1, MVT::i8));
5942
5943   return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
5944                      DAG.getConstant(X86CC, MVT::i8), Cond);
5945 }
5946
5947 SDValue X86TargetLowering::LowerVSETCC(SDValue Op, SelectionDAG &DAG) {
5948   SDValue Cond;
5949   SDValue Op0 = Op.getOperand(0);
5950   SDValue Op1 = Op.getOperand(1);
5951   SDValue CC = Op.getOperand(2);
5952   EVT VT = Op.getValueType();
5953   ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
5954   bool isFP = Op.getOperand(1).getValueType().isFloatingPoint();
5955   DebugLoc dl = Op.getDebugLoc();
5956
5957   if (isFP) {
5958     unsigned SSECC = 8;
5959     EVT VT0 = Op0.getValueType();
5960     assert(VT0 == MVT::v4f32 || VT0 == MVT::v2f64);
5961     unsigned Opc = VT0 == MVT::v4f32 ? X86ISD::CMPPS : X86ISD::CMPPD;
5962     bool Swap = false;
5963
5964     switch (SetCCOpcode) {
5965     default: break;
5966     case ISD::SETOEQ:
5967     case ISD::SETEQ:  SSECC = 0; break;
5968     case ISD::SETOGT:
5969     case ISD::SETGT: Swap = true; // Fallthrough
5970     case ISD::SETLT:
5971     case ISD::SETOLT: SSECC = 1; break;
5972     case ISD::SETOGE:
5973     case ISD::SETGE: Swap = true; // Fallthrough
5974     case ISD::SETLE:
5975     case ISD::SETOLE: SSECC = 2; break;
5976     case ISD::SETUO:  SSECC = 3; break;
5977     case ISD::SETUNE:
5978     case ISD::SETNE:  SSECC = 4; break;
5979     case ISD::SETULE: Swap = true;
5980     case ISD::SETUGE: SSECC = 5; break;
5981     case ISD::SETULT: Swap = true;
5982     case ISD::SETUGT: SSECC = 6; break;
5983     case ISD::SETO:   SSECC = 7; break;
5984     }
5985     if (Swap)
5986       std::swap(Op0, Op1);
5987
5988     // In the two special cases we can't handle, emit two comparisons.
5989     if (SSECC == 8) {
5990       if (SetCCOpcode == ISD::SETUEQ) {
5991         SDValue UNORD, EQ;
5992         UNORD = DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(3, MVT::i8));
5993         EQ = DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(0, MVT::i8));
5994         return DAG.getNode(ISD::OR, dl, VT, UNORD, EQ);
5995       }
5996       else if (SetCCOpcode == ISD::SETONE) {
5997         SDValue ORD, NEQ;
5998         ORD = DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(7, MVT::i8));
5999         NEQ = DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(4, MVT::i8));
6000         return DAG.getNode(ISD::AND, dl, VT, ORD, NEQ);
6001       }
6002       llvm_unreachable("Illegal FP comparison");
6003     }
6004     // Handle all other FP comparisons here.
6005     return DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(SSECC, MVT::i8));
6006   }
6007
6008   // We are handling one of the integer comparisons here.  Since SSE only has
6009   // GT and EQ comparisons for integer, swapping operands and multiple
6010   // operations may be required for some comparisons.
6011   unsigned Opc = 0, EQOpc = 0, GTOpc = 0;
6012   bool Swap = false, Invert = false, FlipSigns = false;
6013
6014   switch (VT.getSimpleVT().SimpleTy) {
6015   default: break;
6016   case MVT::v8i8:
6017   case MVT::v16i8: EQOpc = X86ISD::PCMPEQB; GTOpc = X86ISD::PCMPGTB; break;
6018   case MVT::v4i16:
6019   case MVT::v8i16: EQOpc = X86ISD::PCMPEQW; GTOpc = X86ISD::PCMPGTW; break;
6020   case MVT::v2i32:
6021   case MVT::v4i32: EQOpc = X86ISD::PCMPEQD; GTOpc = X86ISD::PCMPGTD; break;
6022   case MVT::v2i64: EQOpc = X86ISD::PCMPEQQ; GTOpc = X86ISD::PCMPGTQ; break;
6023   }
6024
6025   switch (SetCCOpcode) {
6026   default: break;
6027   case ISD::SETNE:  Invert = true;
6028   case ISD::SETEQ:  Opc = EQOpc; break;
6029   case ISD::SETLT:  Swap = true;
6030   case ISD::SETGT:  Opc = GTOpc; break;
6031   case ISD::SETGE:  Swap = true;
6032   case ISD::SETLE:  Opc = GTOpc; Invert = true; break;
6033   case ISD::SETULT: Swap = true;
6034   case ISD::SETUGT: Opc = GTOpc; FlipSigns = true; break;
6035   case ISD::SETUGE: Swap = true;
6036   case ISD::SETULE: Opc = GTOpc; FlipSigns = true; Invert = true; break;
6037   }
6038   if (Swap)
6039     std::swap(Op0, Op1);
6040
6041   // Since SSE has no unsigned integer comparisons, we need to flip  the sign
6042   // bits of the inputs before performing those operations.
6043   if (FlipSigns) {
6044     EVT EltVT = VT.getVectorElementType();
6045     SDValue SignBit = DAG.getConstant(APInt::getSignBit(EltVT.getSizeInBits()),
6046                                       EltVT);
6047     std::vector<SDValue> SignBits(VT.getVectorNumElements(), SignBit);
6048     SDValue SignVec = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &SignBits[0],
6049                                     SignBits.size());
6050     Op0 = DAG.getNode(ISD::XOR, dl, VT, Op0, SignVec);
6051     Op1 = DAG.getNode(ISD::XOR, dl, VT, Op1, SignVec);
6052   }
6053
6054   SDValue Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
6055
6056   // If the logical-not of the result is required, perform that now.
6057   if (Invert)
6058     Result = DAG.getNOT(dl, Result, VT);
6059
6060   return Result;
6061 }
6062
6063 // isX86LogicalCmp - Return true if opcode is a X86 logical comparison.
6064 static bool isX86LogicalCmp(SDValue Op) {
6065   unsigned Opc = Op.getNode()->getOpcode();
6066   if (Opc == X86ISD::CMP || Opc == X86ISD::COMI || Opc == X86ISD::UCOMI)
6067     return true;
6068   if (Op.getResNo() == 1 &&
6069       (Opc == X86ISD::ADD ||
6070        Opc == X86ISD::SUB ||
6071        Opc == X86ISD::SMUL ||
6072        Opc == X86ISD::UMUL ||
6073        Opc == X86ISD::INC ||
6074        Opc == X86ISD::DEC ||
6075        Opc == X86ISD::OR ||
6076        Opc == X86ISD::XOR ||
6077        Opc == X86ISD::AND))
6078     return true;
6079
6080   return false;
6081 }
6082
6083 SDValue X86TargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) {
6084   bool addTest = true;
6085   SDValue Cond  = Op.getOperand(0);
6086   DebugLoc dl = Op.getDebugLoc();
6087   SDValue CC;
6088
6089   if (Cond.getOpcode() == ISD::SETCC) {
6090     SDValue NewCond = LowerSETCC(Cond, DAG);
6091     if (NewCond.getNode())
6092       Cond = NewCond;
6093   }
6094
6095   // (select (x == 0), -1, 0) -> (sign_bit (x - 1))
6096   SDValue Op1 = Op.getOperand(1);
6097   SDValue Op2 = Op.getOperand(2);
6098   if (Cond.getOpcode() == X86ISD::SETCC &&
6099       cast<ConstantSDNode>(Cond.getOperand(0))->getZExtValue() == X86::COND_E) {
6100     SDValue Cmp = Cond.getOperand(1);
6101     if (Cmp.getOpcode() == X86ISD::CMP) {
6102       ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(Op1);
6103       ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(Op2);
6104       ConstantSDNode *RHSC =
6105         dyn_cast<ConstantSDNode>(Cmp.getOperand(1).getNode());
6106       if (N1C && N1C->isAllOnesValue() &&
6107           N2C && N2C->isNullValue() &&
6108           RHSC && RHSC->isNullValue()) {
6109         SDValue CmpOp0 = Cmp.getOperand(0);
6110         Cmp = DAG.getNode(X86ISD::CMP, dl, CmpOp0.getValueType(),
6111                           CmpOp0, DAG.getConstant(1, CmpOp0.getValueType()));
6112         return DAG.getNode(X86ISD::SETCC_CARRY, dl, Op.getValueType(),
6113                            DAG.getConstant(X86::COND_B, MVT::i8), Cmp);
6114       }
6115     }
6116   }
6117
6118   // Look pass (and (setcc_carry (cmp ...)), 1).
6119   if (Cond.getOpcode() == ISD::AND &&
6120       Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
6121     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
6122     if (C && C->getAPIntValue() == 1) 
6123       Cond = Cond.getOperand(0);
6124   }
6125
6126   // If condition flag is set by a X86ISD::CMP, then use it as the condition
6127   // setting operand in place of the X86ISD::SETCC.
6128   if (Cond.getOpcode() == X86ISD::SETCC ||
6129       Cond.getOpcode() == X86ISD::SETCC_CARRY) {
6130     CC = Cond.getOperand(0);
6131
6132     SDValue Cmp = Cond.getOperand(1);
6133     unsigned Opc = Cmp.getOpcode();
6134     EVT VT = Op.getValueType();
6135
6136     bool IllegalFPCMov = false;
6137     if (VT.isFloatingPoint() && !VT.isVector() &&
6138         !isScalarFPTypeInSSEReg(VT))  // FPStack?
6139       IllegalFPCMov = !hasFPCMov(cast<ConstantSDNode>(CC)->getSExtValue());
6140
6141     if ((isX86LogicalCmp(Cmp) && !IllegalFPCMov) ||
6142         Opc == X86ISD::BT) { // FIXME
6143       Cond = Cmp;
6144       addTest = false;
6145     }
6146   }
6147
6148   if (addTest) {
6149     // Look pass the truncate.
6150     if (Cond.getOpcode() == ISD::TRUNCATE)
6151       Cond = Cond.getOperand(0);
6152
6153     // We know the result of AND is compared against zero. Try to match
6154     // it to BT.
6155     if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) { 
6156       SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, dl, DAG);
6157       if (NewSetCC.getNode()) {
6158         CC = NewSetCC.getOperand(0);
6159         Cond = NewSetCC.getOperand(1);
6160         addTest = false;
6161       }
6162     }
6163   }
6164
6165   if (addTest) {
6166     CC = DAG.getConstant(X86::COND_NE, MVT::i8);
6167     Cond = EmitTest(Cond, X86::COND_NE, DAG);
6168   }
6169
6170   // X86ISD::CMOV means set the result (which is operand 1) to the RHS if
6171   // condition is true.
6172   SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::Flag);
6173   SDValue Ops[] = { Op2, Op1, CC, Cond };
6174   return DAG.getNode(X86ISD::CMOV, dl, VTs, Ops, array_lengthof(Ops));
6175 }
6176
6177 // isAndOrOfSingleUseSetCCs - Return true if node is an ISD::AND or
6178 // ISD::OR of two X86ISD::SETCC nodes each of which has no other use apart
6179 // from the AND / OR.
6180 static bool isAndOrOfSetCCs(SDValue Op, unsigned &Opc) {
6181   Opc = Op.getOpcode();
6182   if (Opc != ISD::OR && Opc != ISD::AND)
6183     return false;
6184   return (Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
6185           Op.getOperand(0).hasOneUse() &&
6186           Op.getOperand(1).getOpcode() == X86ISD::SETCC &&
6187           Op.getOperand(1).hasOneUse());
6188 }
6189
6190 // isXor1OfSetCC - Return true if node is an ISD::XOR of a X86ISD::SETCC and
6191 // 1 and that the SETCC node has a single use.
6192 static bool isXor1OfSetCC(SDValue Op) {
6193   if (Op.getOpcode() != ISD::XOR)
6194     return false;
6195   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
6196   if (N1C && N1C->getAPIntValue() == 1) {
6197     return Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
6198       Op.getOperand(0).hasOneUse();
6199   }
6200   return false;
6201 }
6202
6203 SDValue X86TargetLowering::LowerBRCOND(SDValue Op, SelectionDAG &DAG) {
6204   bool addTest = true;
6205   SDValue Chain = Op.getOperand(0);
6206   SDValue Cond  = Op.getOperand(1);
6207   SDValue Dest  = Op.getOperand(2);
6208   DebugLoc dl = Op.getDebugLoc();
6209   SDValue CC;
6210
6211   if (Cond.getOpcode() == ISD::SETCC) {
6212     SDValue NewCond = LowerSETCC(Cond, DAG);
6213     if (NewCond.getNode())
6214       Cond = NewCond;
6215   }
6216 #if 0
6217   // FIXME: LowerXALUO doesn't handle these!!
6218   else if (Cond.getOpcode() == X86ISD::ADD  ||
6219            Cond.getOpcode() == X86ISD::SUB  ||
6220            Cond.getOpcode() == X86ISD::SMUL ||
6221            Cond.getOpcode() == X86ISD::UMUL)
6222     Cond = LowerXALUO(Cond, DAG);
6223 #endif
6224
6225   // Look pass (and (setcc_carry (cmp ...)), 1).
6226   if (Cond.getOpcode() == ISD::AND &&
6227       Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
6228     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
6229     if (C && C->getAPIntValue() == 1) 
6230       Cond = Cond.getOperand(0);
6231   }
6232
6233   // If condition flag is set by a X86ISD::CMP, then use it as the condition
6234   // setting operand in place of the X86ISD::SETCC.
6235   if (Cond.getOpcode() == X86ISD::SETCC ||
6236       Cond.getOpcode() == X86ISD::SETCC_CARRY) {
6237     CC = Cond.getOperand(0);
6238
6239     SDValue Cmp = Cond.getOperand(1);
6240     unsigned Opc = Cmp.getOpcode();
6241     // FIXME: WHY THE SPECIAL CASING OF LogicalCmp??
6242     if (isX86LogicalCmp(Cmp) || Opc == X86ISD::BT) {
6243       Cond = Cmp;
6244       addTest = false;
6245     } else {
6246       switch (cast<ConstantSDNode>(CC)->getZExtValue()) {
6247       default: break;
6248       case X86::COND_O:
6249       case X86::COND_B:
6250         // These can only come from an arithmetic instruction with overflow,
6251         // e.g. SADDO, UADDO.
6252         Cond = Cond.getNode()->getOperand(1);
6253         addTest = false;
6254         break;
6255       }
6256     }
6257   } else {
6258     unsigned CondOpc;
6259     if (Cond.hasOneUse() && isAndOrOfSetCCs(Cond, CondOpc)) {
6260       SDValue Cmp = Cond.getOperand(0).getOperand(1);
6261       if (CondOpc == ISD::OR) {
6262         // Also, recognize the pattern generated by an FCMP_UNE. We can emit
6263         // two branches instead of an explicit OR instruction with a
6264         // separate test.
6265         if (Cmp == Cond.getOperand(1).getOperand(1) &&
6266             isX86LogicalCmp(Cmp)) {
6267           CC = Cond.getOperand(0).getOperand(0);
6268           Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
6269                               Chain, Dest, CC, Cmp);
6270           CC = Cond.getOperand(1).getOperand(0);
6271           Cond = Cmp;
6272           addTest = false;
6273         }
6274       } else { // ISD::AND
6275         // Also, recognize the pattern generated by an FCMP_OEQ. We can emit
6276         // two branches instead of an explicit AND instruction with a
6277         // separate test. However, we only do this if this block doesn't
6278         // have a fall-through edge, because this requires an explicit
6279         // jmp when the condition is false.
6280         if (Cmp == Cond.getOperand(1).getOperand(1) &&
6281             isX86LogicalCmp(Cmp) &&
6282             Op.getNode()->hasOneUse()) {
6283           X86::CondCode CCode =
6284             (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
6285           CCode = X86::GetOppositeBranchCondition(CCode);
6286           CC = DAG.getConstant(CCode, MVT::i8);
6287           SDValue User = SDValue(*Op.getNode()->use_begin(), 0);
6288           // Look for an unconditional branch following this conditional branch.
6289           // We need this because we need to reverse the successors in order
6290           // to implement FCMP_OEQ.
6291           if (User.getOpcode() == ISD::BR) {
6292             SDValue FalseBB = User.getOperand(1);
6293             SDValue NewBR =
6294               DAG.UpdateNodeOperands(User, User.getOperand(0), Dest);
6295             assert(NewBR == User);
6296             Dest = FalseBB;
6297
6298             Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
6299                                 Chain, Dest, CC, Cmp);
6300             X86::CondCode CCode =
6301               (X86::CondCode)Cond.getOperand(1).getConstantOperandVal(0);
6302             CCode = X86::GetOppositeBranchCondition(CCode);
6303             CC = DAG.getConstant(CCode, MVT::i8);
6304             Cond = Cmp;
6305             addTest = false;
6306           }
6307         }
6308       }
6309     } else if (Cond.hasOneUse() && isXor1OfSetCC(Cond)) {
6310       // Recognize for xorb (setcc), 1 patterns. The xor inverts the condition.
6311       // It should be transformed during dag combiner except when the condition
6312       // is set by a arithmetics with overflow node.
6313       X86::CondCode CCode =
6314         (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
6315       CCode = X86::GetOppositeBranchCondition(CCode);
6316       CC = DAG.getConstant(CCode, MVT::i8);
6317       Cond = Cond.getOperand(0).getOperand(1);
6318       addTest = false;
6319     }
6320   }
6321
6322   if (addTest) {
6323     // Look pass the truncate.
6324     if (Cond.getOpcode() == ISD::TRUNCATE)
6325       Cond = Cond.getOperand(0);
6326
6327     // We know the result of AND is compared against zero. Try to match
6328     // it to BT.
6329     if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) { 
6330       SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, dl, DAG);
6331       if (NewSetCC.getNode()) {
6332         CC = NewSetCC.getOperand(0);
6333         Cond = NewSetCC.getOperand(1);
6334         addTest = false;
6335       }
6336     }
6337   }
6338
6339   if (addTest) {
6340     CC = DAG.getConstant(X86::COND_NE, MVT::i8);
6341     Cond = EmitTest(Cond, X86::COND_NE, DAG);
6342   }
6343   return DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
6344                      Chain, Dest, CC, Cond);
6345 }
6346
6347
6348 // Lower dynamic stack allocation to _alloca call for Cygwin/Mingw targets.
6349 // Calls to _alloca is needed to probe the stack when allocating more than 4k
6350 // bytes in one go. Touching the stack at 4K increments is necessary to ensure
6351 // that the guard pages used by the OS virtual memory manager are allocated in
6352 // correct sequence.
6353 SDValue
6354 X86TargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
6355                                            SelectionDAG &DAG) {
6356   assert(Subtarget->isTargetCygMing() &&
6357          "This should be used only on Cygwin/Mingw targets");
6358   DebugLoc dl = Op.getDebugLoc();
6359
6360   // Get the inputs.
6361   SDValue Chain = Op.getOperand(0);
6362   SDValue Size  = Op.getOperand(1);
6363   // FIXME: Ensure alignment here
6364
6365   SDValue Flag;
6366
6367   EVT IntPtr = getPointerTy();
6368   EVT SPTy = Subtarget->is64Bit() ? MVT::i64 : MVT::i32;
6369
6370   Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(0, true));
6371
6372   Chain = DAG.getCopyToReg(Chain, dl, X86::EAX, Size, Flag);
6373   Flag = Chain.getValue(1);
6374
6375   SDVTList  NodeTys = DAG.getVTList(MVT::Other, MVT::Flag);
6376   SDValue Ops[] = { Chain,
6377                       DAG.getTargetExternalSymbol("_alloca", IntPtr),
6378                       DAG.getRegister(X86::EAX, IntPtr),
6379                       DAG.getRegister(X86StackPtr, SPTy),
6380                       Flag };
6381   Chain = DAG.getNode(X86ISD::CALL, dl, NodeTys, Ops, 5);
6382   Flag = Chain.getValue(1);
6383
6384   Chain = DAG.getCALLSEQ_END(Chain,
6385                              DAG.getIntPtrConstant(0, true),
6386                              DAG.getIntPtrConstant(0, true),
6387                              Flag);
6388
6389   Chain = DAG.getCopyFromReg(Chain, dl, X86StackPtr, SPTy).getValue(1);
6390
6391   SDValue Ops1[2] = { Chain.getValue(0), Chain };
6392   return DAG.getMergeValues(Ops1, 2, dl);
6393 }
6394
6395 SDValue
6396 X86TargetLowering::EmitTargetCodeForMemset(SelectionDAG &DAG, DebugLoc dl,
6397                                            SDValue Chain,
6398                                            SDValue Dst, SDValue Src,
6399                                            SDValue Size, unsigned Align,
6400                                            const Value *DstSV,
6401                                            uint64_t DstSVOff) {
6402   ConstantSDNode *ConstantSize = dyn_cast<ConstantSDNode>(Size);
6403
6404   // If not DWORD aligned or size is more than the threshold, call the library.
6405   // The libc version is likely to be faster for these cases. It can use the
6406   // address value and run time information about the CPU.
6407   if ((Align & 3) != 0 ||
6408       !ConstantSize ||
6409       ConstantSize->getZExtValue() >
6410         getSubtarget()->getMaxInlineSizeThreshold()) {
6411     SDValue InFlag(0, 0);
6412
6413     // Check to see if there is a specialized entry-point for memory zeroing.
6414     ConstantSDNode *V = dyn_cast<ConstantSDNode>(Src);
6415
6416     if (const char *bzeroEntry =  V &&
6417         V->isNullValue() ? Subtarget->getBZeroEntry() : 0) {
6418       EVT IntPtr = getPointerTy();
6419       const Type *IntPtrTy = TD->getIntPtrType(*DAG.getContext());
6420       TargetLowering::ArgListTy Args;
6421       TargetLowering::ArgListEntry Entry;
6422       Entry.Node = Dst;
6423       Entry.Ty = IntPtrTy;
6424       Args.push_back(Entry);
6425       Entry.Node = Size;
6426       Args.push_back(Entry);
6427       std::pair<SDValue,SDValue> CallResult =
6428         LowerCallTo(Chain, Type::getVoidTy(*DAG.getContext()),
6429                     false, false, false, false,
6430                     0, CallingConv::C, false, /*isReturnValueUsed=*/false,
6431                     DAG.getExternalSymbol(bzeroEntry, IntPtr), Args, DAG, dl,
6432                     DAG.GetOrdering(Chain.getNode()));
6433       return CallResult.second;
6434     }
6435
6436     // Otherwise have the target-independent code call memset.
6437     return SDValue();
6438   }
6439
6440   uint64_t SizeVal = ConstantSize->getZExtValue();
6441   SDValue InFlag(0, 0);
6442   EVT AVT;
6443   SDValue Count;
6444   ConstantSDNode *ValC = dyn_cast<ConstantSDNode>(Src);
6445   unsigned BytesLeft = 0;
6446   bool TwoRepStos = false;
6447   if (ValC) {
6448     unsigned ValReg;
6449     uint64_t Val = ValC->getZExtValue() & 255;
6450
6451     // If the value is a constant, then we can potentially use larger sets.
6452     switch (Align & 3) {
6453     case 2:   // WORD aligned
6454       AVT = MVT::i16;
6455       ValReg = X86::AX;
6456       Val = (Val << 8) | Val;
6457       break;
6458     case 0:  // DWORD aligned
6459       AVT = MVT::i32;
6460       ValReg = X86::EAX;
6461       Val = (Val << 8)  | Val;
6462       Val = (Val << 16) | Val;
6463       if (Subtarget->is64Bit() && ((Align & 0x7) == 0)) {  // QWORD aligned
6464         AVT = MVT::i64;
6465         ValReg = X86::RAX;
6466         Val = (Val << 32) | Val;
6467       }
6468       break;
6469     default:  // Byte aligned
6470       AVT = MVT::i8;
6471       ValReg = X86::AL;
6472       Count = DAG.getIntPtrConstant(SizeVal);
6473       break;
6474     }
6475
6476     if (AVT.bitsGT(MVT::i8)) {
6477       unsigned UBytes = AVT.getSizeInBits() / 8;
6478       Count = DAG.getIntPtrConstant(SizeVal / UBytes);
6479       BytesLeft = SizeVal % UBytes;
6480     }
6481
6482     Chain  = DAG.getCopyToReg(Chain, dl, ValReg, DAG.getConstant(Val, AVT),
6483                               InFlag);
6484     InFlag = Chain.getValue(1);
6485   } else {
6486     AVT = MVT::i8;
6487     Count  = DAG.getIntPtrConstant(SizeVal);
6488     Chain  = DAG.getCopyToReg(Chain, dl, X86::AL, Src, InFlag);
6489     InFlag = Chain.getValue(1);
6490   }
6491
6492   Chain  = DAG.getCopyToReg(Chain, dl, Subtarget->is64Bit() ? X86::RCX :
6493                                                               X86::ECX,
6494                             Count, InFlag);
6495   InFlag = Chain.getValue(1);
6496   Chain  = DAG.getCopyToReg(Chain, dl, Subtarget->is64Bit() ? X86::RDI :
6497                                                               X86::EDI,
6498                             Dst, InFlag);
6499   InFlag = Chain.getValue(1);
6500
6501   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Flag);
6502   SDValue Ops[] = { Chain, DAG.getValueType(AVT), InFlag };
6503   Chain = DAG.getNode(X86ISD::REP_STOS, dl, Tys, Ops, array_lengthof(Ops));
6504
6505   if (TwoRepStos) {
6506     InFlag = Chain.getValue(1);
6507     Count  = Size;
6508     EVT CVT = Count.getValueType();
6509     SDValue Left = DAG.getNode(ISD::AND, dl, CVT, Count,
6510                                DAG.getConstant((AVT == MVT::i64) ? 7 : 3, CVT));
6511     Chain  = DAG.getCopyToReg(Chain, dl, (CVT == MVT::i64) ? X86::RCX :
6512                                                              X86::ECX,
6513                               Left, InFlag);
6514     InFlag = Chain.getValue(1);
6515     Tys = DAG.getVTList(MVT::Other, MVT::Flag);
6516     SDValue Ops[] = { Chain, DAG.getValueType(MVT::i8), InFlag };
6517     Chain = DAG.getNode(X86ISD::REP_STOS, dl, Tys, Ops, array_lengthof(Ops));
6518   } else if (BytesLeft) {
6519     // Handle the last 1 - 7 bytes.
6520     unsigned Offset = SizeVal - BytesLeft;
6521     EVT AddrVT = Dst.getValueType();
6522     EVT SizeVT = Size.getValueType();
6523
6524     Chain = DAG.getMemset(Chain, dl,
6525                           DAG.getNode(ISD::ADD, dl, AddrVT, Dst,
6526                                       DAG.getConstant(Offset, AddrVT)),
6527                           Src,
6528                           DAG.getConstant(BytesLeft, SizeVT),
6529                           Align, DstSV, DstSVOff + Offset);
6530   }
6531
6532   // TODO: Use a Tokenfactor, as in memcpy, instead of a single chain.
6533   return Chain;
6534 }
6535
6536 SDValue
6537 X86TargetLowering::EmitTargetCodeForMemcpy(SelectionDAG &DAG, DebugLoc dl,
6538                                       SDValue Chain, SDValue Dst, SDValue Src,
6539                                       SDValue Size, unsigned Align,
6540                                       bool AlwaysInline,
6541                                       const Value *DstSV, uint64_t DstSVOff,
6542                                       const Value *SrcSV, uint64_t SrcSVOff) {
6543   // This requires the copy size to be a constant, preferrably
6544   // within a subtarget-specific limit.
6545   ConstantSDNode *ConstantSize = dyn_cast<ConstantSDNode>(Size);
6546   if (!ConstantSize)
6547     return SDValue();
6548   uint64_t SizeVal = ConstantSize->getZExtValue();
6549   if (!AlwaysInline && SizeVal > getSubtarget()->getMaxInlineSizeThreshold())
6550     return SDValue();
6551
6552   /// If not DWORD aligned, call the library.
6553   if ((Align & 3) != 0)
6554     return SDValue();
6555
6556   // DWORD aligned
6557   EVT AVT = MVT::i32;
6558   if (Subtarget->is64Bit() && ((Align & 0x7) == 0))  // QWORD aligned
6559     AVT = MVT::i64;
6560
6561   unsigned UBytes = AVT.getSizeInBits() / 8;
6562   unsigned CountVal = SizeVal / UBytes;
6563   SDValue Count = DAG.getIntPtrConstant(CountVal);
6564   unsigned BytesLeft = SizeVal % UBytes;
6565
6566   SDValue InFlag(0, 0);
6567   Chain  = DAG.getCopyToReg(Chain, dl, Subtarget->is64Bit() ? X86::RCX :
6568                                                               X86::ECX,
6569                             Count, InFlag);
6570   InFlag = Chain.getValue(1);
6571   Chain  = DAG.getCopyToReg(Chain, dl, Subtarget->is64Bit() ? X86::RDI :
6572                                                              X86::EDI,
6573                             Dst, InFlag);
6574   InFlag = Chain.getValue(1);
6575   Chain  = DAG.getCopyToReg(Chain, dl, Subtarget->is64Bit() ? X86::RSI :
6576                                                               X86::ESI,
6577                             Src, InFlag);
6578   InFlag = Chain.getValue(1);
6579
6580   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Flag);
6581   SDValue Ops[] = { Chain, DAG.getValueType(AVT), InFlag };
6582   SDValue RepMovs = DAG.getNode(X86ISD::REP_MOVS, dl, Tys, Ops,
6583                                 array_lengthof(Ops));
6584
6585   SmallVector<SDValue, 4> Results;
6586   Results.push_back(RepMovs);
6587   if (BytesLeft) {
6588     // Handle the last 1 - 7 bytes.
6589     unsigned Offset = SizeVal - BytesLeft;
6590     EVT DstVT = Dst.getValueType();
6591     EVT SrcVT = Src.getValueType();
6592     EVT SizeVT = Size.getValueType();
6593     Results.push_back(DAG.getMemcpy(Chain, dl,
6594                                     DAG.getNode(ISD::ADD, dl, DstVT, Dst,
6595                                                 DAG.getConstant(Offset, DstVT)),
6596                                     DAG.getNode(ISD::ADD, dl, SrcVT, Src,
6597                                                 DAG.getConstant(Offset, SrcVT)),
6598                                     DAG.getConstant(BytesLeft, SizeVT),
6599                                     Align, AlwaysInline,
6600                                     DstSV, DstSVOff + Offset,
6601                                     SrcSV, SrcSVOff + Offset));
6602   }
6603
6604   return DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
6605                      &Results[0], Results.size());
6606 }
6607
6608 SDValue X86TargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) {
6609   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
6610   DebugLoc dl = Op.getDebugLoc();
6611
6612   if (!Subtarget->is64Bit()) {
6613     // vastart just stores the address of the VarArgsFrameIndex slot into the
6614     // memory location argument.
6615     SDValue FR = DAG.getFrameIndex(VarArgsFrameIndex, getPointerTy());
6616     return DAG.getStore(Op.getOperand(0), dl, FR, Op.getOperand(1), SV, 0);
6617   }
6618
6619   // __va_list_tag:
6620   //   gp_offset         (0 - 6 * 8)
6621   //   fp_offset         (48 - 48 + 8 * 16)
6622   //   overflow_arg_area (point to parameters coming in memory).
6623   //   reg_save_area
6624   SmallVector<SDValue, 8> MemOps;
6625   SDValue FIN = Op.getOperand(1);
6626   // Store gp_offset
6627   SDValue Store = DAG.getStore(Op.getOperand(0), dl,
6628                                  DAG.getConstant(VarArgsGPOffset, MVT::i32),
6629                                  FIN, SV, 0);
6630   MemOps.push_back(Store);
6631
6632   // Store fp_offset
6633   FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(),
6634                     FIN, DAG.getIntPtrConstant(4));
6635   Store = DAG.getStore(Op.getOperand(0), dl,
6636                        DAG.getConstant(VarArgsFPOffset, MVT::i32),
6637                        FIN, SV, 0);
6638   MemOps.push_back(Store);
6639
6640   // Store ptr to overflow_arg_area
6641   FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(),
6642                     FIN, DAG.getIntPtrConstant(4));
6643   SDValue OVFIN = DAG.getFrameIndex(VarArgsFrameIndex, getPointerTy());
6644   Store = DAG.getStore(Op.getOperand(0), dl, OVFIN, FIN, SV, 0);
6645   MemOps.push_back(Store);
6646
6647   // Store ptr to reg_save_area.
6648   FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(),
6649                     FIN, DAG.getIntPtrConstant(8));
6650   SDValue RSFIN = DAG.getFrameIndex(RegSaveFrameIndex, getPointerTy());
6651   Store = DAG.getStore(Op.getOperand(0), dl, RSFIN, FIN, SV, 0);
6652   MemOps.push_back(Store);
6653   return DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
6654                      &MemOps[0], MemOps.size());
6655 }
6656
6657 SDValue X86TargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) {
6658   // X86-64 va_list is a struct { i32, i32, i8*, i8* }.
6659   assert(Subtarget->is64Bit() && "This code only handles 64-bit va_arg!");
6660   SDValue Chain = Op.getOperand(0);
6661   SDValue SrcPtr = Op.getOperand(1);
6662   SDValue SrcSV = Op.getOperand(2);
6663
6664   llvm_report_error("VAArgInst is not yet implemented for x86-64!");
6665   return SDValue();
6666 }
6667
6668 SDValue X86TargetLowering::LowerVACOPY(SDValue Op, SelectionDAG &DAG) {
6669   // X86-64 va_list is a struct { i32, i32, i8*, i8* }.
6670   assert(Subtarget->is64Bit() && "This code only handles 64-bit va_copy!");
6671   SDValue Chain = Op.getOperand(0);
6672   SDValue DstPtr = Op.getOperand(1);
6673   SDValue SrcPtr = Op.getOperand(2);
6674   const Value *DstSV = cast<SrcValueSDNode>(Op.getOperand(3))->getValue();
6675   const Value *SrcSV = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
6676   DebugLoc dl = Op.getDebugLoc();
6677
6678   return DAG.getMemcpy(Chain, dl, DstPtr, SrcPtr,
6679                        DAG.getIntPtrConstant(24), 8, false,
6680                        DstSV, 0, SrcSV, 0);
6681 }
6682
6683 SDValue
6684 X86TargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op, SelectionDAG &DAG) {
6685   DebugLoc dl = Op.getDebugLoc();
6686   unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
6687   switch (IntNo) {
6688   default: return SDValue();    // Don't custom lower most intrinsics.
6689   // Comparison intrinsics.
6690   case Intrinsic::x86_sse_comieq_ss:
6691   case Intrinsic::x86_sse_comilt_ss:
6692   case Intrinsic::x86_sse_comile_ss:
6693   case Intrinsic::x86_sse_comigt_ss:
6694   case Intrinsic::x86_sse_comige_ss:
6695   case Intrinsic::x86_sse_comineq_ss:
6696   case Intrinsic::x86_sse_ucomieq_ss:
6697   case Intrinsic::x86_sse_ucomilt_ss:
6698   case Intrinsic::x86_sse_ucomile_ss:
6699   case Intrinsic::x86_sse_ucomigt_ss:
6700   case Intrinsic::x86_sse_ucomige_ss:
6701   case Intrinsic::x86_sse_ucomineq_ss:
6702   case Intrinsic::x86_sse2_comieq_sd:
6703   case Intrinsic::x86_sse2_comilt_sd:
6704   case Intrinsic::x86_sse2_comile_sd:
6705   case Intrinsic::x86_sse2_comigt_sd:
6706   case Intrinsic::x86_sse2_comige_sd:
6707   case Intrinsic::x86_sse2_comineq_sd:
6708   case Intrinsic::x86_sse2_ucomieq_sd:
6709   case Intrinsic::x86_sse2_ucomilt_sd:
6710   case Intrinsic::x86_sse2_ucomile_sd:
6711   case Intrinsic::x86_sse2_ucomigt_sd:
6712   case Intrinsic::x86_sse2_ucomige_sd:
6713   case Intrinsic::x86_sse2_ucomineq_sd: {
6714     unsigned Opc = 0;
6715     ISD::CondCode CC = ISD::SETCC_INVALID;
6716     switch (IntNo) {
6717     default: break;
6718     case Intrinsic::x86_sse_comieq_ss:
6719     case Intrinsic::x86_sse2_comieq_sd:
6720       Opc = X86ISD::COMI;
6721       CC = ISD::SETEQ;
6722       break;
6723     case Intrinsic::x86_sse_comilt_ss:
6724     case Intrinsic::x86_sse2_comilt_sd:
6725       Opc = X86ISD::COMI;
6726       CC = ISD::SETLT;
6727       break;
6728     case Intrinsic::x86_sse_comile_ss:
6729     case Intrinsic::x86_sse2_comile_sd:
6730       Opc = X86ISD::COMI;
6731       CC = ISD::SETLE;
6732       break;
6733     case Intrinsic::x86_sse_comigt_ss:
6734     case Intrinsic::x86_sse2_comigt_sd:
6735       Opc = X86ISD::COMI;
6736       CC = ISD::SETGT;
6737       break;
6738     case Intrinsic::x86_sse_comige_ss:
6739     case Intrinsic::x86_sse2_comige_sd:
6740       Opc = X86ISD::COMI;
6741       CC = ISD::SETGE;
6742       break;
6743     case Intrinsic::x86_sse_comineq_ss:
6744     case Intrinsic::x86_sse2_comineq_sd:
6745       Opc = X86ISD::COMI;
6746       CC = ISD::SETNE;
6747       break;
6748     case Intrinsic::x86_sse_ucomieq_ss:
6749     case Intrinsic::x86_sse2_ucomieq_sd:
6750       Opc = X86ISD::UCOMI;
6751       CC = ISD::SETEQ;
6752       break;
6753     case Intrinsic::x86_sse_ucomilt_ss:
6754     case Intrinsic::x86_sse2_ucomilt_sd:
6755       Opc = X86ISD::UCOMI;
6756       CC = ISD::SETLT;
6757       break;
6758     case Intrinsic::x86_sse_ucomile_ss:
6759     case Intrinsic::x86_sse2_ucomile_sd:
6760       Opc = X86ISD::UCOMI;
6761       CC = ISD::SETLE;
6762       break;
6763     case Intrinsic::x86_sse_ucomigt_ss:
6764     case Intrinsic::x86_sse2_ucomigt_sd:
6765       Opc = X86ISD::UCOMI;
6766       CC = ISD::SETGT;
6767       break;
6768     case Intrinsic::x86_sse_ucomige_ss:
6769     case Intrinsic::x86_sse2_ucomige_sd:
6770       Opc = X86ISD::UCOMI;
6771       CC = ISD::SETGE;
6772       break;
6773     case Intrinsic::x86_sse_ucomineq_ss:
6774     case Intrinsic::x86_sse2_ucomineq_sd:
6775       Opc = X86ISD::UCOMI;
6776       CC = ISD::SETNE;
6777       break;
6778     }
6779
6780     SDValue LHS = Op.getOperand(1);
6781     SDValue RHS = Op.getOperand(2);
6782     unsigned X86CC = TranslateX86CC(CC, true, LHS, RHS, DAG);
6783     assert(X86CC != X86::COND_INVALID && "Unexpected illegal condition!");
6784     SDValue Cond = DAG.getNode(Opc, dl, MVT::i32, LHS, RHS);
6785     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
6786                                 DAG.getConstant(X86CC, MVT::i8), Cond);
6787     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
6788   }
6789   // ptest intrinsics. The intrinsic these come from are designed to return
6790   // an integer value, not just an instruction so lower it to the ptest
6791   // pattern and a setcc for the result.
6792   case Intrinsic::x86_sse41_ptestz:
6793   case Intrinsic::x86_sse41_ptestc:
6794   case Intrinsic::x86_sse41_ptestnzc:{
6795     unsigned X86CC = 0;
6796     switch (IntNo) {
6797     default: llvm_unreachable("Bad fallthrough in Intrinsic lowering.");
6798     case Intrinsic::x86_sse41_ptestz:
6799       // ZF = 1
6800       X86CC = X86::COND_E;
6801       break;
6802     case Intrinsic::x86_sse41_ptestc:
6803       // CF = 1
6804       X86CC = X86::COND_B;
6805       break;
6806     case Intrinsic::x86_sse41_ptestnzc:
6807       // ZF and CF = 0
6808       X86CC = X86::COND_A;
6809       break;
6810     }
6811
6812     SDValue LHS = Op.getOperand(1);
6813     SDValue RHS = Op.getOperand(2);
6814     SDValue Test = DAG.getNode(X86ISD::PTEST, dl, MVT::i32, LHS, RHS);
6815     SDValue CC = DAG.getConstant(X86CC, MVT::i8);
6816     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8, CC, Test);
6817     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
6818   }
6819
6820   // Fix vector shift instructions where the last operand is a non-immediate
6821   // i32 value.
6822   case Intrinsic::x86_sse2_pslli_w:
6823   case Intrinsic::x86_sse2_pslli_d:
6824   case Intrinsic::x86_sse2_pslli_q:
6825   case Intrinsic::x86_sse2_psrli_w:
6826   case Intrinsic::x86_sse2_psrli_d:
6827   case Intrinsic::x86_sse2_psrli_q:
6828   case Intrinsic::x86_sse2_psrai_w:
6829   case Intrinsic::x86_sse2_psrai_d:
6830   case Intrinsic::x86_mmx_pslli_w:
6831   case Intrinsic::x86_mmx_pslli_d:
6832   case Intrinsic::x86_mmx_pslli_q:
6833   case Intrinsic::x86_mmx_psrli_w:
6834   case Intrinsic::x86_mmx_psrli_d:
6835   case Intrinsic::x86_mmx_psrli_q:
6836   case Intrinsic::x86_mmx_psrai_w:
6837   case Intrinsic::x86_mmx_psrai_d: {
6838     SDValue ShAmt = Op.getOperand(2);
6839     if (isa<ConstantSDNode>(ShAmt))
6840       return SDValue();
6841
6842     unsigned NewIntNo = 0;
6843     EVT ShAmtVT = MVT::v4i32;
6844     switch (IntNo) {
6845     case Intrinsic::x86_sse2_pslli_w:
6846       NewIntNo = Intrinsic::x86_sse2_psll_w;
6847       break;
6848     case Intrinsic::x86_sse2_pslli_d:
6849       NewIntNo = Intrinsic::x86_sse2_psll_d;
6850       break;
6851     case Intrinsic::x86_sse2_pslli_q:
6852       NewIntNo = Intrinsic::x86_sse2_psll_q;
6853       break;
6854     case Intrinsic::x86_sse2_psrli_w:
6855       NewIntNo = Intrinsic::x86_sse2_psrl_w;
6856       break;
6857     case Intrinsic::x86_sse2_psrli_d:
6858       NewIntNo = Intrinsic::x86_sse2_psrl_d;
6859       break;
6860     case Intrinsic::x86_sse2_psrli_q:
6861       NewIntNo = Intrinsic::x86_sse2_psrl_q;
6862       break;
6863     case Intrinsic::x86_sse2_psrai_w:
6864       NewIntNo = Intrinsic::x86_sse2_psra_w;
6865       break;
6866     case Intrinsic::x86_sse2_psrai_d:
6867       NewIntNo = Intrinsic::x86_sse2_psra_d;
6868       break;
6869     default: {
6870       ShAmtVT = MVT::v2i32;
6871       switch (IntNo) {
6872       case Intrinsic::x86_mmx_pslli_w:
6873         NewIntNo = Intrinsic::x86_mmx_psll_w;
6874         break;
6875       case Intrinsic::x86_mmx_pslli_d:
6876         NewIntNo = Intrinsic::x86_mmx_psll_d;
6877         break;
6878       case Intrinsic::x86_mmx_pslli_q:
6879         NewIntNo = Intrinsic::x86_mmx_psll_q;
6880         break;
6881       case Intrinsic::x86_mmx_psrli_w:
6882         NewIntNo = Intrinsic::x86_mmx_psrl_w;
6883         break;
6884       case Intrinsic::x86_mmx_psrli_d:
6885         NewIntNo = Intrinsic::x86_mmx_psrl_d;
6886         break;
6887       case Intrinsic::x86_mmx_psrli_q:
6888         NewIntNo = Intrinsic::x86_mmx_psrl_q;
6889         break;
6890       case Intrinsic::x86_mmx_psrai_w:
6891         NewIntNo = Intrinsic::x86_mmx_psra_w;
6892         break;
6893       case Intrinsic::x86_mmx_psrai_d:
6894         NewIntNo = Intrinsic::x86_mmx_psra_d;
6895         break;
6896       default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
6897       }
6898       break;
6899     }
6900     }
6901
6902     // The vector shift intrinsics with scalars uses 32b shift amounts but
6903     // the sse2/mmx shift instructions reads 64 bits. Set the upper 32 bits
6904     // to be zero.
6905     SDValue ShOps[4];
6906     ShOps[0] = ShAmt;
6907     ShOps[1] = DAG.getConstant(0, MVT::i32);
6908     if (ShAmtVT == MVT::v4i32) {
6909       ShOps[2] = DAG.getUNDEF(MVT::i32);
6910       ShOps[3] = DAG.getUNDEF(MVT::i32);
6911       ShAmt =  DAG.getNode(ISD::BUILD_VECTOR, dl, ShAmtVT, &ShOps[0], 4);
6912     } else {
6913       ShAmt =  DAG.getNode(ISD::BUILD_VECTOR, dl, ShAmtVT, &ShOps[0], 2);
6914     }
6915
6916     EVT VT = Op.getValueType();
6917     ShAmt = DAG.getNode(ISD::BIT_CONVERT, dl, VT, ShAmt);
6918     return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
6919                        DAG.getConstant(NewIntNo, MVT::i32),
6920                        Op.getOperand(1), ShAmt);
6921   }
6922   }
6923 }
6924
6925 SDValue X86TargetLowering::LowerRETURNADDR(SDValue Op, SelectionDAG &DAG) {
6926   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
6927   DebugLoc dl = Op.getDebugLoc();
6928
6929   if (Depth > 0) {
6930     SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
6931     SDValue Offset =
6932       DAG.getConstant(TD->getPointerSize(),
6933                       Subtarget->is64Bit() ? MVT::i64 : MVT::i32);
6934     return DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(),
6935                        DAG.getNode(ISD::ADD, dl, getPointerTy(),
6936                                    FrameAddr, Offset),
6937                        NULL, 0);
6938   }
6939
6940   // Just load the return address.
6941   SDValue RetAddrFI = getReturnAddressFrameIndex(DAG);
6942   return DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(),
6943                      RetAddrFI, NULL, 0);
6944 }
6945
6946 SDValue X86TargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) {
6947   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
6948   MFI->setFrameAddressIsTaken(true);
6949   EVT VT = Op.getValueType();
6950   DebugLoc dl = Op.getDebugLoc();  // FIXME probably not meaningful
6951   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
6952   unsigned FrameReg = Subtarget->is64Bit() ? X86::RBP : X86::EBP;
6953   SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
6954   while (Depth--)
6955     FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr, NULL, 0);
6956   return FrameAddr;
6957 }
6958
6959 SDValue X86TargetLowering::LowerFRAME_TO_ARGS_OFFSET(SDValue Op,
6960                                                      SelectionDAG &DAG) {
6961   return DAG.getIntPtrConstant(2*TD->getPointerSize());
6962 }
6963
6964 SDValue X86TargetLowering::LowerEH_RETURN(SDValue Op, SelectionDAG &DAG)
6965 {
6966   MachineFunction &MF = DAG.getMachineFunction();
6967   SDValue Chain     = Op.getOperand(0);
6968   SDValue Offset    = Op.getOperand(1);
6969   SDValue Handler   = Op.getOperand(2);
6970   DebugLoc dl       = Op.getDebugLoc();
6971
6972   SDValue Frame = DAG.getRegister(Subtarget->is64Bit() ? X86::RBP : X86::EBP,
6973                                   getPointerTy());
6974   unsigned StoreAddrReg = (Subtarget->is64Bit() ? X86::RCX : X86::ECX);
6975
6976   SDValue StoreAddr = DAG.getNode(ISD::SUB, dl, getPointerTy(), Frame,
6977                                   DAG.getIntPtrConstant(-TD->getPointerSize()));
6978   StoreAddr = DAG.getNode(ISD::ADD, dl, getPointerTy(), StoreAddr, Offset);
6979   Chain = DAG.getStore(Chain, dl, Handler, StoreAddr, NULL, 0);
6980   Chain = DAG.getCopyToReg(Chain, dl, StoreAddrReg, StoreAddr);
6981   MF.getRegInfo().addLiveOut(StoreAddrReg);
6982
6983   return DAG.getNode(X86ISD::EH_RETURN, dl,
6984                      MVT::Other,
6985                      Chain, DAG.getRegister(StoreAddrReg, getPointerTy()));
6986 }
6987
6988 SDValue X86TargetLowering::LowerTRAMPOLINE(SDValue Op,
6989                                              SelectionDAG &DAG) {
6990   SDValue Root = Op.getOperand(0);
6991   SDValue Trmp = Op.getOperand(1); // trampoline
6992   SDValue FPtr = Op.getOperand(2); // nested function
6993   SDValue Nest = Op.getOperand(3); // 'nest' parameter value
6994   DebugLoc dl  = Op.getDebugLoc();
6995
6996   const Value *TrmpAddr = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
6997
6998   const X86InstrInfo *TII =
6999     ((X86TargetMachine&)getTargetMachine()).getInstrInfo();
7000
7001   if (Subtarget->is64Bit()) {
7002     SDValue OutChains[6];
7003
7004     // Large code-model.
7005
7006     const unsigned char JMP64r  = TII->getBaseOpcodeFor(X86::JMP64r);
7007     const unsigned char MOV64ri = TII->getBaseOpcodeFor(X86::MOV64ri);
7008
7009     const unsigned char N86R10 = RegInfo->getX86RegNum(X86::R10);
7010     const unsigned char N86R11 = RegInfo->getX86RegNum(X86::R11);
7011
7012     const unsigned char REX_WB = 0x40 | 0x08 | 0x01; // REX prefix
7013
7014     // Load the pointer to the nested function into R11.
7015     unsigned OpCode = ((MOV64ri | N86R11) << 8) | REX_WB; // movabsq r11
7016     SDValue Addr = Trmp;
7017     OutChains[0] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
7018                                 Addr, TrmpAddr, 0);
7019
7020     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
7021                        DAG.getConstant(2, MVT::i64));
7022     OutChains[1] = DAG.getStore(Root, dl, FPtr, Addr, TrmpAddr, 2, false, 2);
7023
7024     // Load the 'nest' parameter value into R10.
7025     // R10 is specified in X86CallingConv.td
7026     OpCode = ((MOV64ri | N86R10) << 8) | REX_WB; // movabsq r10
7027     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
7028                        DAG.getConstant(10, MVT::i64));
7029     OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
7030                                 Addr, TrmpAddr, 10);
7031
7032     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
7033                        DAG.getConstant(12, MVT::i64));
7034     OutChains[3] = DAG.getStore(Root, dl, Nest, Addr, TrmpAddr, 12, false, 2);
7035
7036     // Jump to the nested function.
7037     OpCode = (JMP64r << 8) | REX_WB; // jmpq *...
7038     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
7039                        DAG.getConstant(20, MVT::i64));
7040     OutChains[4] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
7041                                 Addr, TrmpAddr, 20);
7042
7043     unsigned char ModRM = N86R11 | (4 << 3) | (3 << 6); // ...r11
7044     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
7045                        DAG.getConstant(22, MVT::i64));
7046     OutChains[5] = DAG.getStore(Root, dl, DAG.getConstant(ModRM, MVT::i8), Addr,
7047                                 TrmpAddr, 22);
7048
7049     SDValue Ops[] =
7050       { Trmp, DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains, 6) };
7051     return DAG.getMergeValues(Ops, 2, dl);
7052   } else {
7053     const Function *Func =
7054       cast<Function>(cast<SrcValueSDNode>(Op.getOperand(5))->getValue());
7055     CallingConv::ID CC = Func->getCallingConv();
7056     unsigned NestReg;
7057
7058     switch (CC) {
7059     default:
7060       llvm_unreachable("Unsupported calling convention");
7061     case CallingConv::C:
7062     case CallingConv::X86_StdCall: {
7063       // Pass 'nest' parameter in ECX.
7064       // Must be kept in sync with X86CallingConv.td
7065       NestReg = X86::ECX;
7066
7067       // Check that ECX wasn't needed by an 'inreg' parameter.
7068       const FunctionType *FTy = Func->getFunctionType();
7069       const AttrListPtr &Attrs = Func->getAttributes();
7070
7071       if (!Attrs.isEmpty() && !Func->isVarArg()) {
7072         unsigned InRegCount = 0;
7073         unsigned Idx = 1;
7074
7075         for (FunctionType::param_iterator I = FTy->param_begin(),
7076              E = FTy->param_end(); I != E; ++I, ++Idx)
7077           if (Attrs.paramHasAttr(Idx, Attribute::InReg))
7078             // FIXME: should only count parameters that are lowered to integers.
7079             InRegCount += (TD->getTypeSizeInBits(*I) + 31) / 32;
7080
7081         if (InRegCount > 2) {
7082           llvm_report_error("Nest register in use - reduce number of inreg parameters!");
7083         }
7084       }
7085       break;
7086     }
7087     case CallingConv::X86_FastCall:
7088     case CallingConv::Fast:
7089       // Pass 'nest' parameter in EAX.
7090       // Must be kept in sync with X86CallingConv.td
7091       NestReg = X86::EAX;
7092       break;
7093     }
7094
7095     SDValue OutChains[4];
7096     SDValue Addr, Disp;
7097
7098     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
7099                        DAG.getConstant(10, MVT::i32));
7100     Disp = DAG.getNode(ISD::SUB, dl, MVT::i32, FPtr, Addr);
7101
7102     const unsigned char MOV32ri = TII->getBaseOpcodeFor(X86::MOV32ri);
7103     const unsigned char N86Reg = RegInfo->getX86RegNum(NestReg);
7104     OutChains[0] = DAG.getStore(Root, dl,
7105                                 DAG.getConstant(MOV32ri|N86Reg, MVT::i8),
7106                                 Trmp, TrmpAddr, 0);
7107
7108     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
7109                        DAG.getConstant(1, MVT::i32));
7110     OutChains[1] = DAG.getStore(Root, dl, Nest, Addr, TrmpAddr, 1, false, 1);
7111
7112     const unsigned char JMP = TII->getBaseOpcodeFor(X86::JMP);
7113     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
7114                        DAG.getConstant(5, MVT::i32));
7115     OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(JMP, MVT::i8), Addr,
7116                                 TrmpAddr, 5, false, 1);
7117
7118     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
7119                        DAG.getConstant(6, MVT::i32));
7120     OutChains[3] = DAG.getStore(Root, dl, Disp, Addr, TrmpAddr, 6, false, 1);
7121
7122     SDValue Ops[] =
7123       { Trmp, DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains, 4) };
7124     return DAG.getMergeValues(Ops, 2, dl);
7125   }
7126 }
7127
7128 SDValue X86TargetLowering::LowerFLT_ROUNDS_(SDValue Op, SelectionDAG &DAG) {
7129   /*
7130    The rounding mode is in bits 11:10 of FPSR, and has the following
7131    settings:
7132      00 Round to nearest
7133      01 Round to -inf
7134      10 Round to +inf
7135      11 Round to 0
7136
7137   FLT_ROUNDS, on the other hand, expects the following:
7138     -1 Undefined
7139      0 Round to 0
7140      1 Round to nearest
7141      2 Round to +inf
7142      3 Round to -inf
7143
7144   To perform the conversion, we do:
7145     (((((FPSR & 0x800) >> 11) | ((FPSR & 0x400) >> 9)) + 1) & 3)
7146   */
7147
7148   MachineFunction &MF = DAG.getMachineFunction();
7149   const TargetMachine &TM = MF.getTarget();
7150   const TargetFrameInfo &TFI = *TM.getFrameInfo();
7151   unsigned StackAlignment = TFI.getStackAlignment();
7152   EVT VT = Op.getValueType();
7153   DebugLoc dl = Op.getDebugLoc();
7154
7155   // Save FP Control Word to stack slot
7156   int SSFI = MF.getFrameInfo()->CreateStackObject(2, StackAlignment, false);
7157   SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
7158
7159   SDValue Chain = DAG.getNode(X86ISD::FNSTCW16m, dl, MVT::Other,
7160                               DAG.getEntryNode(), StackSlot);
7161
7162   // Load FP Control Word from stack slot
7163   SDValue CWD = DAG.getLoad(MVT::i16, dl, Chain, StackSlot, NULL, 0);
7164
7165   // Transform as necessary
7166   SDValue CWD1 =
7167     DAG.getNode(ISD::SRL, dl, MVT::i16,
7168                 DAG.getNode(ISD::AND, dl, MVT::i16,
7169                             CWD, DAG.getConstant(0x800, MVT::i16)),
7170                 DAG.getConstant(11, MVT::i8));
7171   SDValue CWD2 =
7172     DAG.getNode(ISD::SRL, dl, MVT::i16,
7173                 DAG.getNode(ISD::AND, dl, MVT::i16,
7174                             CWD, DAG.getConstant(0x400, MVT::i16)),
7175                 DAG.getConstant(9, MVT::i8));
7176
7177   SDValue RetVal =
7178     DAG.getNode(ISD::AND, dl, MVT::i16,
7179                 DAG.getNode(ISD::ADD, dl, MVT::i16,
7180                             DAG.getNode(ISD::OR, dl, MVT::i16, CWD1, CWD2),
7181                             DAG.getConstant(1, MVT::i16)),
7182                 DAG.getConstant(3, MVT::i16));
7183
7184
7185   return DAG.getNode((VT.getSizeInBits() < 16 ?
7186                       ISD::TRUNCATE : ISD::ZERO_EXTEND), dl, VT, RetVal);
7187 }
7188
7189 SDValue X86TargetLowering::LowerCTLZ(SDValue Op, SelectionDAG &DAG) {
7190   EVT VT = Op.getValueType();
7191   EVT OpVT = VT;
7192   unsigned NumBits = VT.getSizeInBits();
7193   DebugLoc dl = Op.getDebugLoc();
7194
7195   Op = Op.getOperand(0);
7196   if (VT == MVT::i8) {
7197     // Zero extend to i32 since there is not an i8 bsr.
7198     OpVT = MVT::i32;
7199     Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
7200   }
7201
7202   // Issue a bsr (scan bits in reverse) which also sets EFLAGS.
7203   SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
7204   Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
7205
7206   // If src is zero (i.e. bsr sets ZF), returns NumBits.
7207   SDValue Ops[] = {
7208     Op,
7209     DAG.getConstant(NumBits+NumBits-1, OpVT),
7210     DAG.getConstant(X86::COND_E, MVT::i8),
7211     Op.getValue(1)
7212   };
7213   Op = DAG.getNode(X86ISD::CMOV, dl, OpVT, Ops, array_lengthof(Ops));
7214
7215   // Finally xor with NumBits-1.
7216   Op = DAG.getNode(ISD::XOR, dl, OpVT, Op, DAG.getConstant(NumBits-1, OpVT));
7217
7218   if (VT == MVT::i8)
7219     Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
7220   return Op;
7221 }
7222
7223 SDValue X86TargetLowering::LowerCTTZ(SDValue Op, SelectionDAG &DAG) {
7224   EVT VT = Op.getValueType();
7225   EVT OpVT = VT;
7226   unsigned NumBits = VT.getSizeInBits();
7227   DebugLoc dl = Op.getDebugLoc();
7228
7229   Op = Op.getOperand(0);
7230   if (VT == MVT::i8) {
7231     OpVT = MVT::i32;
7232     Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
7233   }
7234
7235   // Issue a bsf (scan bits forward) which also sets EFLAGS.
7236   SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
7237   Op = DAG.getNode(X86ISD::BSF, dl, VTs, Op);
7238
7239   // If src is zero (i.e. bsf sets ZF), returns NumBits.
7240   SDValue Ops[] = {
7241     Op,
7242     DAG.getConstant(NumBits, OpVT),
7243     DAG.getConstant(X86::COND_E, MVT::i8),
7244     Op.getValue(1)
7245   };
7246   Op = DAG.getNode(X86ISD::CMOV, dl, OpVT, Ops, array_lengthof(Ops));
7247
7248   if (VT == MVT::i8)
7249     Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
7250   return Op;
7251 }
7252
7253 SDValue X86TargetLowering::LowerMUL_V2I64(SDValue Op, SelectionDAG &DAG) {
7254   EVT VT = Op.getValueType();
7255   assert(VT == MVT::v2i64 && "Only know how to lower V2I64 multiply");
7256   DebugLoc dl = Op.getDebugLoc();
7257
7258   //  ulong2 Ahi = __builtin_ia32_psrlqi128( a, 32);
7259   //  ulong2 Bhi = __builtin_ia32_psrlqi128( b, 32);
7260   //  ulong2 AloBlo = __builtin_ia32_pmuludq128( a, b );
7261   //  ulong2 AloBhi = __builtin_ia32_pmuludq128( a, Bhi );
7262   //  ulong2 AhiBlo = __builtin_ia32_pmuludq128( Ahi, b );
7263   //
7264   //  AloBhi = __builtin_ia32_psllqi128( AloBhi, 32 );
7265   //  AhiBlo = __builtin_ia32_psllqi128( AhiBlo, 32 );
7266   //  return AloBlo + AloBhi + AhiBlo;
7267
7268   SDValue A = Op.getOperand(0);
7269   SDValue B = Op.getOperand(1);
7270
7271   SDValue Ahi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
7272                        DAG.getConstant(Intrinsic::x86_sse2_psrli_q, MVT::i32),
7273                        A, DAG.getConstant(32, MVT::i32));
7274   SDValue Bhi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
7275                        DAG.getConstant(Intrinsic::x86_sse2_psrli_q, MVT::i32),
7276                        B, DAG.getConstant(32, MVT::i32));
7277   SDValue AloBlo = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
7278                        DAG.getConstant(Intrinsic::x86_sse2_pmulu_dq, MVT::i32),
7279                        A, B);
7280   SDValue AloBhi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
7281                        DAG.getConstant(Intrinsic::x86_sse2_pmulu_dq, MVT::i32),
7282                        A, Bhi);
7283   SDValue AhiBlo = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
7284                        DAG.getConstant(Intrinsic::x86_sse2_pmulu_dq, MVT::i32),
7285                        Ahi, B);
7286   AloBhi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
7287                        DAG.getConstant(Intrinsic::x86_sse2_pslli_q, MVT::i32),
7288                        AloBhi, DAG.getConstant(32, MVT::i32));
7289   AhiBlo = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
7290                        DAG.getConstant(Intrinsic::x86_sse2_pslli_q, MVT::i32),
7291                        AhiBlo, DAG.getConstant(32, MVT::i32));
7292   SDValue Res = DAG.getNode(ISD::ADD, dl, VT, AloBlo, AloBhi);
7293   Res = DAG.getNode(ISD::ADD, dl, VT, Res, AhiBlo);
7294   return Res;
7295 }
7296
7297
7298 SDValue X86TargetLowering::LowerXALUO(SDValue Op, SelectionDAG &DAG) {
7299   // Lower the "add/sub/mul with overflow" instruction into a regular ins plus
7300   // a "setcc" instruction that checks the overflow flag. The "brcond" lowering
7301   // looks for this combo and may remove the "setcc" instruction if the "setcc"
7302   // has only one use.
7303   SDNode *N = Op.getNode();
7304   SDValue LHS = N->getOperand(0);
7305   SDValue RHS = N->getOperand(1);
7306   unsigned BaseOp = 0;
7307   unsigned Cond = 0;
7308   DebugLoc dl = Op.getDebugLoc();
7309
7310   switch (Op.getOpcode()) {
7311   default: llvm_unreachable("Unknown ovf instruction!");
7312   case ISD::SADDO:
7313     // A subtract of one will be selected as a INC. Note that INC doesn't
7314     // set CF, so we can't do this for UADDO.
7315     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op))
7316       if (C->getAPIntValue() == 1) {
7317         BaseOp = X86ISD::INC;
7318         Cond = X86::COND_O;
7319         break;
7320       }
7321     BaseOp = X86ISD::ADD;
7322     Cond = X86::COND_O;
7323     break;
7324   case ISD::UADDO:
7325     BaseOp = X86ISD::ADD;
7326     Cond = X86::COND_B;
7327     break;
7328   case ISD::SSUBO:
7329     // A subtract of one will be selected as a DEC. Note that DEC doesn't
7330     // set CF, so we can't do this for USUBO.
7331     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op))
7332       if (C->getAPIntValue() == 1) {
7333         BaseOp = X86ISD::DEC;
7334         Cond = X86::COND_O;
7335         break;
7336       }
7337     BaseOp = X86ISD::SUB;
7338     Cond = X86::COND_O;
7339     break;
7340   case ISD::USUBO:
7341     BaseOp = X86ISD::SUB;
7342     Cond = X86::COND_B;
7343     break;
7344   case ISD::SMULO:
7345     BaseOp = X86ISD::SMUL;
7346     Cond = X86::COND_O;
7347     break;
7348   case ISD::UMULO:
7349     BaseOp = X86ISD::UMUL;
7350     Cond = X86::COND_B;
7351     break;
7352   }
7353
7354   // Also sets EFLAGS.
7355   SDVTList VTs = DAG.getVTList(N->getValueType(0), MVT::i32);
7356   SDValue Sum = DAG.getNode(BaseOp, dl, VTs, LHS, RHS);
7357
7358   SDValue SetCC =
7359     DAG.getNode(X86ISD::SETCC, dl, N->getValueType(1),
7360                 DAG.getConstant(Cond, MVT::i32), SDValue(Sum.getNode(), 1));
7361
7362   DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), SetCC);
7363   return Sum;
7364 }
7365
7366 SDValue X86TargetLowering::LowerCMP_SWAP(SDValue Op, SelectionDAG &DAG) {
7367   EVT T = Op.getValueType();
7368   DebugLoc dl = Op.getDebugLoc();
7369   unsigned Reg = 0;
7370   unsigned size = 0;
7371   switch(T.getSimpleVT().SimpleTy) {
7372   default:
7373     assert(false && "Invalid value type!");
7374   case MVT::i8:  Reg = X86::AL;  size = 1; break;
7375   case MVT::i16: Reg = X86::AX;  size = 2; break;
7376   case MVT::i32: Reg = X86::EAX; size = 4; break;
7377   case MVT::i64:
7378     assert(Subtarget->is64Bit() && "Node not type legal!");
7379     Reg = X86::RAX; size = 8;
7380     break;
7381   }
7382   SDValue cpIn = DAG.getCopyToReg(Op.getOperand(0), dl, Reg,
7383                                     Op.getOperand(2), SDValue());
7384   SDValue Ops[] = { cpIn.getValue(0),
7385                     Op.getOperand(1),
7386                     Op.getOperand(3),
7387                     DAG.getTargetConstant(size, MVT::i8),
7388                     cpIn.getValue(1) };
7389   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Flag);
7390   SDValue Result = DAG.getNode(X86ISD::LCMPXCHG_DAG, dl, Tys, Ops, 5);
7391   SDValue cpOut =
7392     DAG.getCopyFromReg(Result.getValue(0), dl, Reg, T, Result.getValue(1));
7393   return cpOut;
7394 }
7395
7396 SDValue X86TargetLowering::LowerREADCYCLECOUNTER(SDValue Op,
7397                                                  SelectionDAG &DAG) {
7398   assert(Subtarget->is64Bit() && "Result not type legalized?");
7399   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Flag);
7400   SDValue TheChain = Op.getOperand(0);
7401   DebugLoc dl = Op.getDebugLoc();
7402   SDValue rd = DAG.getNode(X86ISD::RDTSC_DAG, dl, Tys, &TheChain, 1);
7403   SDValue rax = DAG.getCopyFromReg(rd, dl, X86::RAX, MVT::i64, rd.getValue(1));
7404   SDValue rdx = DAG.getCopyFromReg(rax.getValue(1), dl, X86::RDX, MVT::i64,
7405                                    rax.getValue(2));
7406   SDValue Tmp = DAG.getNode(ISD::SHL, dl, MVT::i64, rdx,
7407                             DAG.getConstant(32, MVT::i8));
7408   SDValue Ops[] = {
7409     DAG.getNode(ISD::OR, dl, MVT::i64, rax, Tmp),
7410     rdx.getValue(1)
7411   };
7412   return DAG.getMergeValues(Ops, 2, dl);
7413 }
7414
7415 SDValue X86TargetLowering::LowerLOAD_SUB(SDValue Op, SelectionDAG &DAG) {
7416   SDNode *Node = Op.getNode();
7417   DebugLoc dl = Node->getDebugLoc();
7418   EVT T = Node->getValueType(0);
7419   SDValue negOp = DAG.getNode(ISD::SUB, dl, T,
7420                               DAG.getConstant(0, T), Node->getOperand(2));
7421   return DAG.getAtomic(ISD::ATOMIC_LOAD_ADD, dl,
7422                        cast<AtomicSDNode>(Node)->getMemoryVT(),
7423                        Node->getOperand(0),
7424                        Node->getOperand(1), negOp,
7425                        cast<AtomicSDNode>(Node)->getSrcValue(),
7426                        cast<AtomicSDNode>(Node)->getAlignment());
7427 }
7428
7429 /// LowerOperation - Provide custom lowering hooks for some operations.
7430 ///
7431 SDValue X86TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) {
7432   switch (Op.getOpcode()) {
7433   default: llvm_unreachable("Should not custom lower this!");
7434   case ISD::ATOMIC_CMP_SWAP:    return LowerCMP_SWAP(Op,DAG);
7435   case ISD::ATOMIC_LOAD_SUB:    return LowerLOAD_SUB(Op,DAG);
7436   case ISD::BUILD_VECTOR:       return LowerBUILD_VECTOR(Op, DAG);
7437   case ISD::CONCAT_VECTORS:     return LowerCONCAT_VECTORS(Op, DAG);
7438   case ISD::VECTOR_SHUFFLE:     return LowerVECTOR_SHUFFLE(Op, DAG);
7439   case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
7440   case ISD::INSERT_VECTOR_ELT:  return LowerINSERT_VECTOR_ELT(Op, DAG);
7441   case ISD::SCALAR_TO_VECTOR:   return LowerSCALAR_TO_VECTOR(Op, DAG);
7442   case ISD::ConstantPool:       return LowerConstantPool(Op, DAG);
7443   case ISD::GlobalAddress:      return LowerGlobalAddress(Op, DAG);
7444   case ISD::GlobalTLSAddress:   return LowerGlobalTLSAddress(Op, DAG);
7445   case ISD::ExternalSymbol:     return LowerExternalSymbol(Op, DAG);
7446   case ISD::BlockAddress:       return LowerBlockAddress(Op, DAG);
7447   case ISD::SHL_PARTS:
7448   case ISD::SRA_PARTS:
7449   case ISD::SRL_PARTS:          return LowerShift(Op, DAG);
7450   case ISD::SINT_TO_FP:         return LowerSINT_TO_FP(Op, DAG);
7451   case ISD::UINT_TO_FP:         return LowerUINT_TO_FP(Op, DAG);
7452   case ISD::FP_TO_SINT:         return LowerFP_TO_SINT(Op, DAG);
7453   case ISD::FP_TO_UINT:         return LowerFP_TO_UINT(Op, DAG);
7454   case ISD::FABS:               return LowerFABS(Op, DAG);
7455   case ISD::FNEG:               return LowerFNEG(Op, DAG);
7456   case ISD::FCOPYSIGN:          return LowerFCOPYSIGN(Op, DAG);
7457   case ISD::SETCC:              return LowerSETCC(Op, DAG);
7458   case ISD::VSETCC:             return LowerVSETCC(Op, DAG);
7459   case ISD::SELECT:             return LowerSELECT(Op, DAG);
7460   case ISD::BRCOND:             return LowerBRCOND(Op, DAG);
7461   case ISD::JumpTable:          return LowerJumpTable(Op, DAG);
7462   case ISD::VASTART:            return LowerVASTART(Op, DAG);
7463   case ISD::VAARG:              return LowerVAARG(Op, DAG);
7464   case ISD::VACOPY:             return LowerVACOPY(Op, DAG);
7465   case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
7466   case ISD::RETURNADDR:         return LowerRETURNADDR(Op, DAG);
7467   case ISD::FRAMEADDR:          return LowerFRAMEADDR(Op, DAG);
7468   case ISD::FRAME_TO_ARGS_OFFSET:
7469                                 return LowerFRAME_TO_ARGS_OFFSET(Op, DAG);
7470   case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG);
7471   case ISD::EH_RETURN:          return LowerEH_RETURN(Op, DAG);
7472   case ISD::TRAMPOLINE:         return LowerTRAMPOLINE(Op, DAG);
7473   case ISD::FLT_ROUNDS_:        return LowerFLT_ROUNDS_(Op, DAG);
7474   case ISD::CTLZ:               return LowerCTLZ(Op, DAG);
7475   case ISD::CTTZ:               return LowerCTTZ(Op, DAG);
7476   case ISD::MUL:                return LowerMUL_V2I64(Op, DAG);
7477   case ISD::SADDO:
7478   case ISD::UADDO:
7479   case ISD::SSUBO:
7480   case ISD::USUBO:
7481   case ISD::SMULO:
7482   case ISD::UMULO:              return LowerXALUO(Op, DAG);
7483   case ISD::READCYCLECOUNTER:   return LowerREADCYCLECOUNTER(Op, DAG);
7484   }
7485 }
7486
7487 void X86TargetLowering::
7488 ReplaceATOMIC_BINARY_64(SDNode *Node, SmallVectorImpl<SDValue>&Results,
7489                         SelectionDAG &DAG, unsigned NewOp) {
7490   EVT T = Node->getValueType(0);
7491   DebugLoc dl = Node->getDebugLoc();
7492   assert (T == MVT::i64 && "Only know how to expand i64 atomics");
7493
7494   SDValue Chain = Node->getOperand(0);
7495   SDValue In1 = Node->getOperand(1);
7496   SDValue In2L = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
7497                              Node->getOperand(2), DAG.getIntPtrConstant(0));
7498   SDValue In2H = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
7499                              Node->getOperand(2), DAG.getIntPtrConstant(1));
7500   SDValue Ops[] = { Chain, In1, In2L, In2H };
7501   SDVTList Tys = DAG.getVTList(MVT::i32, MVT::i32, MVT::Other);
7502   SDValue Result =
7503     DAG.getMemIntrinsicNode(NewOp, dl, Tys, Ops, 4, MVT::i64,
7504                             cast<MemSDNode>(Node)->getMemOperand());
7505   SDValue OpsF[] = { Result.getValue(0), Result.getValue(1)};
7506   Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, OpsF, 2));
7507   Results.push_back(Result.getValue(2));
7508 }
7509
7510 /// ReplaceNodeResults - Replace a node with an illegal result type
7511 /// with a new node built out of custom code.
7512 void X86TargetLowering::ReplaceNodeResults(SDNode *N,
7513                                            SmallVectorImpl<SDValue>&Results,
7514                                            SelectionDAG &DAG) {
7515   DebugLoc dl = N->getDebugLoc();
7516   switch (N->getOpcode()) {
7517   default:
7518     assert(false && "Do not know how to custom type legalize this operation!");
7519     return;
7520   case ISD::FP_TO_SINT: {
7521     std::pair<SDValue,SDValue> Vals =
7522         FP_TO_INTHelper(SDValue(N, 0), DAG, true);
7523     SDValue FIST = Vals.first, StackSlot = Vals.second;
7524     if (FIST.getNode() != 0) {
7525       EVT VT = N->getValueType(0);
7526       // Return a load from the stack slot.
7527       Results.push_back(DAG.getLoad(VT, dl, FIST, StackSlot, NULL, 0));
7528     }
7529     return;
7530   }
7531   case ISD::READCYCLECOUNTER: {
7532     SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Flag);
7533     SDValue TheChain = N->getOperand(0);
7534     SDValue rd = DAG.getNode(X86ISD::RDTSC_DAG, dl, Tys, &TheChain, 1);
7535     SDValue eax = DAG.getCopyFromReg(rd, dl, X86::EAX, MVT::i32,
7536                                      rd.getValue(1));
7537     SDValue edx = DAG.getCopyFromReg(eax.getValue(1), dl, X86::EDX, MVT::i32,
7538                                      eax.getValue(2));
7539     // Use a buildpair to merge the two 32-bit values into a 64-bit one.
7540     SDValue Ops[] = { eax, edx };
7541     Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Ops, 2));
7542     Results.push_back(edx.getValue(1));
7543     return;
7544   }
7545   case ISD::SDIV:
7546   case ISD::UDIV:
7547   case ISD::SREM:
7548   case ISD::UREM: {
7549     EVT WidenVT = getTypeToTransformTo(*DAG.getContext(), N->getValueType(0));
7550     Results.push_back(DAG.UnrollVectorOp(N, WidenVT.getVectorNumElements()));
7551     return;
7552   }
7553   case ISD::ATOMIC_CMP_SWAP: {
7554     EVT T = N->getValueType(0);
7555     assert (T == MVT::i64 && "Only know how to expand i64 Cmp and Swap");
7556     SDValue cpInL, cpInH;
7557     cpInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(2),
7558                         DAG.getConstant(0, MVT::i32));
7559     cpInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(2),
7560                         DAG.getConstant(1, MVT::i32));
7561     cpInL = DAG.getCopyToReg(N->getOperand(0), dl, X86::EAX, cpInL, SDValue());
7562     cpInH = DAG.getCopyToReg(cpInL.getValue(0), dl, X86::EDX, cpInH,
7563                              cpInL.getValue(1));
7564     SDValue swapInL, swapInH;
7565     swapInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(3),
7566                           DAG.getConstant(0, MVT::i32));
7567     swapInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(3),
7568                           DAG.getConstant(1, MVT::i32));
7569     swapInL = DAG.getCopyToReg(cpInH.getValue(0), dl, X86::EBX, swapInL,
7570                                cpInH.getValue(1));
7571     swapInH = DAG.getCopyToReg(swapInL.getValue(0), dl, X86::ECX, swapInH,
7572                                swapInL.getValue(1));
7573     SDValue Ops[] = { swapInH.getValue(0),
7574                       N->getOperand(1),
7575                       swapInH.getValue(1) };
7576     SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Flag);
7577     SDValue Result = DAG.getNode(X86ISD::LCMPXCHG8_DAG, dl, Tys, Ops, 3);
7578     SDValue cpOutL = DAG.getCopyFromReg(Result.getValue(0), dl, X86::EAX,
7579                                         MVT::i32, Result.getValue(1));
7580     SDValue cpOutH = DAG.getCopyFromReg(cpOutL.getValue(1), dl, X86::EDX,
7581                                         MVT::i32, cpOutL.getValue(2));
7582     SDValue OpsF[] = { cpOutL.getValue(0), cpOutH.getValue(0)};
7583     Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, OpsF, 2));
7584     Results.push_back(cpOutH.getValue(1));
7585     return;
7586   }
7587   case ISD::ATOMIC_LOAD_ADD:
7588     ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMADD64_DAG);
7589     return;
7590   case ISD::ATOMIC_LOAD_AND:
7591     ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMAND64_DAG);
7592     return;
7593   case ISD::ATOMIC_LOAD_NAND:
7594     ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMNAND64_DAG);
7595     return;
7596   case ISD::ATOMIC_LOAD_OR:
7597     ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMOR64_DAG);
7598     return;
7599   case ISD::ATOMIC_LOAD_SUB:
7600     ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMSUB64_DAG);
7601     return;
7602   case ISD::ATOMIC_LOAD_XOR:
7603     ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMXOR64_DAG);
7604     return;
7605   case ISD::ATOMIC_SWAP:
7606     ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMSWAP64_DAG);
7607     return;
7608   }
7609 }
7610
7611 const char *X86TargetLowering::getTargetNodeName(unsigned Opcode) const {
7612   switch (Opcode) {
7613   default: return NULL;
7614   case X86ISD::BSF:                return "X86ISD::BSF";
7615   case X86ISD::BSR:                return "X86ISD::BSR";
7616   case X86ISD::SHLD:               return "X86ISD::SHLD";
7617   case X86ISD::SHRD:               return "X86ISD::SHRD";
7618   case X86ISD::FAND:               return "X86ISD::FAND";
7619   case X86ISD::FOR:                return "X86ISD::FOR";
7620   case X86ISD::FXOR:               return "X86ISD::FXOR";
7621   case X86ISD::FSRL:               return "X86ISD::FSRL";
7622   case X86ISD::FILD:               return "X86ISD::FILD";
7623   case X86ISD::FILD_FLAG:          return "X86ISD::FILD_FLAG";
7624   case X86ISD::FP_TO_INT16_IN_MEM: return "X86ISD::FP_TO_INT16_IN_MEM";
7625   case X86ISD::FP_TO_INT32_IN_MEM: return "X86ISD::FP_TO_INT32_IN_MEM";
7626   case X86ISD::FP_TO_INT64_IN_MEM: return "X86ISD::FP_TO_INT64_IN_MEM";
7627   case X86ISD::FLD:                return "X86ISD::FLD";
7628   case X86ISD::FST:                return "X86ISD::FST";
7629   case X86ISD::CALL:               return "X86ISD::CALL";
7630   case X86ISD::RDTSC_DAG:          return "X86ISD::RDTSC_DAG";
7631   case X86ISD::BT:                 return "X86ISD::BT";
7632   case X86ISD::CMP:                return "X86ISD::CMP";
7633   case X86ISD::COMI:               return "X86ISD::COMI";
7634   case X86ISD::UCOMI:              return "X86ISD::UCOMI";
7635   case X86ISD::SETCC:              return "X86ISD::SETCC";
7636   case X86ISD::SETCC_CARRY:        return "X86ISD::SETCC_CARRY";
7637   case X86ISD::CMOV:               return "X86ISD::CMOV";
7638   case X86ISD::BRCOND:             return "X86ISD::BRCOND";
7639   case X86ISD::RET_FLAG:           return "X86ISD::RET_FLAG";
7640   case X86ISD::REP_STOS:           return "X86ISD::REP_STOS";
7641   case X86ISD::REP_MOVS:           return "X86ISD::REP_MOVS";
7642   case X86ISD::GlobalBaseReg:      return "X86ISD::GlobalBaseReg";
7643   case X86ISD::Wrapper:            return "X86ISD::Wrapper";
7644   case X86ISD::WrapperRIP:         return "X86ISD::WrapperRIP";
7645   case X86ISD::PEXTRB:             return "X86ISD::PEXTRB";
7646   case X86ISD::PEXTRW:             return "X86ISD::PEXTRW";
7647   case X86ISD::INSERTPS:           return "X86ISD::INSERTPS";
7648   case X86ISD::PINSRB:             return "X86ISD::PINSRB";
7649   case X86ISD::PINSRW:             return "X86ISD::PINSRW";
7650   case X86ISD::PSHUFB:             return "X86ISD::PSHUFB";
7651   case X86ISD::FMAX:               return "X86ISD::FMAX";
7652   case X86ISD::FMIN:               return "X86ISD::FMIN";
7653   case X86ISD::FRSQRT:             return "X86ISD::FRSQRT";
7654   case X86ISD::FRCP:               return "X86ISD::FRCP";
7655   case X86ISD::TLSADDR:            return "X86ISD::TLSADDR";
7656   case X86ISD::SegmentBaseAddress: return "X86ISD::SegmentBaseAddress";
7657   case X86ISD::EH_RETURN:          return "X86ISD::EH_RETURN";
7658   case X86ISD::TC_RETURN:          return "X86ISD::TC_RETURN";
7659   case X86ISD::FNSTCW16m:          return "X86ISD::FNSTCW16m";
7660   case X86ISD::LCMPXCHG_DAG:       return "X86ISD::LCMPXCHG_DAG";
7661   case X86ISD::LCMPXCHG8_DAG:      return "X86ISD::LCMPXCHG8_DAG";
7662   case X86ISD::ATOMADD64_DAG:      return "X86ISD::ATOMADD64_DAG";
7663   case X86ISD::ATOMSUB64_DAG:      return "X86ISD::ATOMSUB64_DAG";
7664   case X86ISD::ATOMOR64_DAG:       return "X86ISD::ATOMOR64_DAG";
7665   case X86ISD::ATOMXOR64_DAG:      return "X86ISD::ATOMXOR64_DAG";
7666   case X86ISD::ATOMAND64_DAG:      return "X86ISD::ATOMAND64_DAG";
7667   case X86ISD::ATOMNAND64_DAG:     return "X86ISD::ATOMNAND64_DAG";
7668   case X86ISD::VZEXT_MOVL:         return "X86ISD::VZEXT_MOVL";
7669   case X86ISD::VZEXT_LOAD:         return "X86ISD::VZEXT_LOAD";
7670   case X86ISD::VSHL:               return "X86ISD::VSHL";
7671   case X86ISD::VSRL:               return "X86ISD::VSRL";
7672   case X86ISD::CMPPD:              return "X86ISD::CMPPD";
7673   case X86ISD::CMPPS:              return "X86ISD::CMPPS";
7674   case X86ISD::PCMPEQB:            return "X86ISD::PCMPEQB";
7675   case X86ISD::PCMPEQW:            return "X86ISD::PCMPEQW";
7676   case X86ISD::PCMPEQD:            return "X86ISD::PCMPEQD";
7677   case X86ISD::PCMPEQQ:            return "X86ISD::PCMPEQQ";
7678   case X86ISD::PCMPGTB:            return "X86ISD::PCMPGTB";
7679   case X86ISD::PCMPGTW:            return "X86ISD::PCMPGTW";
7680   case X86ISD::PCMPGTD:            return "X86ISD::PCMPGTD";
7681   case X86ISD::PCMPGTQ:            return "X86ISD::PCMPGTQ";
7682   case X86ISD::ADD:                return "X86ISD::ADD";
7683   case X86ISD::SUB:                return "X86ISD::SUB";
7684   case X86ISD::SMUL:               return "X86ISD::SMUL";
7685   case X86ISD::UMUL:               return "X86ISD::UMUL";
7686   case X86ISD::INC:                return "X86ISD::INC";
7687   case X86ISD::DEC:                return "X86ISD::DEC";
7688   case X86ISD::OR:                 return "X86ISD::OR";
7689   case X86ISD::XOR:                return "X86ISD::XOR";
7690   case X86ISD::AND:                return "X86ISD::AND";
7691   case X86ISD::MUL_IMM:            return "X86ISD::MUL_IMM";
7692   case X86ISD::PTEST:              return "X86ISD::PTEST";
7693   case X86ISD::VASTART_SAVE_XMM_REGS: return "X86ISD::VASTART_SAVE_XMM_REGS";
7694   }
7695 }
7696
7697 // isLegalAddressingMode - Return true if the addressing mode represented
7698 // by AM is legal for this target, for a load/store of the specified type.
7699 bool X86TargetLowering::isLegalAddressingMode(const AddrMode &AM,
7700                                               const Type *Ty) const {
7701   // X86 supports extremely general addressing modes.
7702   CodeModel::Model M = getTargetMachine().getCodeModel();
7703
7704   // X86 allows a sign-extended 32-bit immediate field as a displacement.
7705   if (!X86::isOffsetSuitableForCodeModel(AM.BaseOffs, M, AM.BaseGV != NULL))
7706     return false;
7707
7708   if (AM.BaseGV) {
7709     unsigned GVFlags =
7710       Subtarget->ClassifyGlobalReference(AM.BaseGV, getTargetMachine());
7711
7712     // If a reference to this global requires an extra load, we can't fold it.
7713     if (isGlobalStubReference(GVFlags))
7714       return false;
7715
7716     // If BaseGV requires a register for the PIC base, we cannot also have a
7717     // BaseReg specified.
7718     if (AM.HasBaseReg && isGlobalRelativeToPICBase(GVFlags))
7719       return false;
7720
7721     // If lower 4G is not available, then we must use rip-relative addressing.
7722     if (Subtarget->is64Bit() && (AM.BaseOffs || AM.Scale > 1))
7723       return false;
7724   }
7725
7726   switch (AM.Scale) {
7727   case 0:
7728   case 1:
7729   case 2:
7730   case 4:
7731   case 8:
7732     // These scales always work.
7733     break;
7734   case 3:
7735   case 5:
7736   case 9:
7737     // These scales are formed with basereg+scalereg.  Only accept if there is
7738     // no basereg yet.
7739     if (AM.HasBaseReg)
7740       return false;
7741     break;
7742   default:  // Other stuff never works.
7743     return false;
7744   }
7745
7746   return true;
7747 }
7748
7749
7750 bool X86TargetLowering::isTruncateFree(const Type *Ty1, const Type *Ty2) const {
7751   if (!Ty1->isInteger() || !Ty2->isInteger())
7752     return false;
7753   unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
7754   unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
7755   if (NumBits1 <= NumBits2)
7756     return false;
7757   return Subtarget->is64Bit() || NumBits1 < 64;
7758 }
7759
7760 bool X86TargetLowering::isTruncateFree(EVT VT1, EVT VT2) const {
7761   if (!VT1.isInteger() || !VT2.isInteger())
7762     return false;
7763   unsigned NumBits1 = VT1.getSizeInBits();
7764   unsigned NumBits2 = VT2.getSizeInBits();
7765   if (NumBits1 <= NumBits2)
7766     return false;
7767   return Subtarget->is64Bit() || NumBits1 < 64;
7768 }
7769
7770 bool X86TargetLowering::isZExtFree(const Type *Ty1, const Type *Ty2) const {
7771   // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
7772   return Ty1->isInteger(32) && Ty2->isInteger(64) && Subtarget->is64Bit();
7773 }
7774
7775 bool X86TargetLowering::isZExtFree(EVT VT1, EVT VT2) const {
7776   // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
7777   return VT1 == MVT::i32 && VT2 == MVT::i64 && Subtarget->is64Bit();
7778 }
7779
7780 bool X86TargetLowering::isNarrowingProfitable(EVT VT1, EVT VT2) const {
7781   // i16 instructions are longer (0x66 prefix) and potentially slower.
7782   return !(VT1 == MVT::i32 && VT2 == MVT::i16);
7783 }
7784
7785 /// isShuffleMaskLegal - Targets can use this to indicate that they only
7786 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
7787 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
7788 /// are assumed to be legal.
7789 bool
7790 X86TargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M,
7791                                       EVT VT) const {
7792   // Only do shuffles on 128-bit vector types for now.
7793   if (VT.getSizeInBits() == 64)
7794     return false;
7795
7796   // FIXME: pshufb, blends, shifts.
7797   return (VT.getVectorNumElements() == 2 ||
7798           ShuffleVectorSDNode::isSplatMask(&M[0], VT) ||
7799           isMOVLMask(M, VT) ||
7800           isSHUFPMask(M, VT) ||
7801           isPSHUFDMask(M, VT) ||
7802           isPSHUFHWMask(M, VT) ||
7803           isPSHUFLWMask(M, VT) ||
7804           isPALIGNRMask(M, VT, Subtarget->hasSSSE3()) ||
7805           isUNPCKLMask(M, VT) ||
7806           isUNPCKHMask(M, VT) ||
7807           isUNPCKL_v_undef_Mask(M, VT) ||
7808           isUNPCKH_v_undef_Mask(M, VT));
7809 }
7810
7811 bool
7812 X86TargetLowering::isVectorClearMaskLegal(const SmallVectorImpl<int> &Mask,
7813                                           EVT VT) const {
7814   unsigned NumElts = VT.getVectorNumElements();
7815   // FIXME: This collection of masks seems suspect.
7816   if (NumElts == 2)
7817     return true;
7818   if (NumElts == 4 && VT.getSizeInBits() == 128) {
7819     return (isMOVLMask(Mask, VT)  ||
7820             isCommutedMOVLMask(Mask, VT, true) ||
7821             isSHUFPMask(Mask, VT) ||
7822             isCommutedSHUFPMask(Mask, VT));
7823   }
7824   return false;
7825 }
7826
7827 //===----------------------------------------------------------------------===//
7828 //                           X86 Scheduler Hooks
7829 //===----------------------------------------------------------------------===//
7830
7831 // private utility function
7832 MachineBasicBlock *
7833 X86TargetLowering::EmitAtomicBitwiseWithCustomInserter(MachineInstr *bInstr,
7834                                                        MachineBasicBlock *MBB,
7835                                                        unsigned regOpc,
7836                                                        unsigned immOpc,
7837                                                        unsigned LoadOpc,
7838                                                        unsigned CXchgOpc,
7839                                                        unsigned copyOpc,
7840                                                        unsigned notOpc,
7841                                                        unsigned EAXreg,
7842                                                        TargetRegisterClass *RC,
7843                                                        bool invSrc) const {
7844   // For the atomic bitwise operator, we generate
7845   //   thisMBB:
7846   //   newMBB:
7847   //     ld  t1 = [bitinstr.addr]
7848   //     op  t2 = t1, [bitinstr.val]
7849   //     mov EAX = t1
7850   //     lcs dest = [bitinstr.addr], t2  [EAX is implicit]
7851   //     bz  newMBB
7852   //     fallthrough -->nextMBB
7853   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
7854   const BasicBlock *LLVM_BB = MBB->getBasicBlock();
7855   MachineFunction::iterator MBBIter = MBB;
7856   ++MBBIter;
7857
7858   /// First build the CFG
7859   MachineFunction *F = MBB->getParent();
7860   MachineBasicBlock *thisMBB = MBB;
7861   MachineBasicBlock *newMBB = F->CreateMachineBasicBlock(LLVM_BB);
7862   MachineBasicBlock *nextMBB = F->CreateMachineBasicBlock(LLVM_BB);
7863   F->insert(MBBIter, newMBB);
7864   F->insert(MBBIter, nextMBB);
7865
7866   // Move all successors to thisMBB to nextMBB
7867   nextMBB->transferSuccessors(thisMBB);
7868
7869   // Update thisMBB to fall through to newMBB
7870   thisMBB->addSuccessor(newMBB);
7871
7872   // newMBB jumps to itself and fall through to nextMBB
7873   newMBB->addSuccessor(nextMBB);
7874   newMBB->addSuccessor(newMBB);
7875
7876   // Insert instructions into newMBB based on incoming instruction
7877   assert(bInstr->getNumOperands() < X86AddrNumOperands + 4 &&
7878          "unexpected number of operands");
7879   DebugLoc dl = bInstr->getDebugLoc();
7880   MachineOperand& destOper = bInstr->getOperand(0);
7881   MachineOperand* argOpers[2 + X86AddrNumOperands];
7882   int numArgs = bInstr->getNumOperands() - 1;
7883   for (int i=0; i < numArgs; ++i)
7884     argOpers[i] = &bInstr->getOperand(i+1);
7885
7886   // x86 address has 4 operands: base, index, scale, and displacement
7887   int lastAddrIndx = X86AddrNumOperands - 1; // [0,3]
7888   int valArgIndx = lastAddrIndx + 1;
7889
7890   unsigned t1 = F->getRegInfo().createVirtualRegister(RC);
7891   MachineInstrBuilder MIB = BuildMI(newMBB, dl, TII->get(LoadOpc), t1);
7892   for (int i=0; i <= lastAddrIndx; ++i)
7893     (*MIB).addOperand(*argOpers[i]);
7894
7895   unsigned tt = F->getRegInfo().createVirtualRegister(RC);
7896   if (invSrc) {
7897     MIB = BuildMI(newMBB, dl, TII->get(notOpc), tt).addReg(t1);
7898   }
7899   else
7900     tt = t1;
7901
7902   unsigned t2 = F->getRegInfo().createVirtualRegister(RC);
7903   assert((argOpers[valArgIndx]->isReg() ||
7904           argOpers[valArgIndx]->isImm()) &&
7905          "invalid operand");
7906   if (argOpers[valArgIndx]->isReg())
7907     MIB = BuildMI(newMBB, dl, TII->get(regOpc), t2);
7908   else
7909     MIB = BuildMI(newMBB, dl, TII->get(immOpc), t2);
7910   MIB.addReg(tt);
7911   (*MIB).addOperand(*argOpers[valArgIndx]);
7912
7913   MIB = BuildMI(newMBB, dl, TII->get(copyOpc), EAXreg);
7914   MIB.addReg(t1);
7915
7916   MIB = BuildMI(newMBB, dl, TII->get(CXchgOpc));
7917   for (int i=0; i <= lastAddrIndx; ++i)
7918     (*MIB).addOperand(*argOpers[i]);
7919   MIB.addReg(t2);
7920   assert(bInstr->hasOneMemOperand() && "Unexpected number of memoperand");
7921   (*MIB).setMemRefs(bInstr->memoperands_begin(),
7922                     bInstr->memoperands_end());
7923
7924   MIB = BuildMI(newMBB, dl, TII->get(copyOpc), destOper.getReg());
7925   MIB.addReg(EAXreg);
7926
7927   // insert branch
7928   BuildMI(newMBB, dl, TII->get(X86::JNE)).addMBB(newMBB);
7929
7930   F->DeleteMachineInstr(bInstr);   // The pseudo instruction is gone now.
7931   return nextMBB;
7932 }
7933
7934 // private utility function:  64 bit atomics on 32 bit host.
7935 MachineBasicBlock *
7936 X86TargetLowering::EmitAtomicBit6432WithCustomInserter(MachineInstr *bInstr,
7937                                                        MachineBasicBlock *MBB,
7938                                                        unsigned regOpcL,
7939                                                        unsigned regOpcH,
7940                                                        unsigned immOpcL,
7941                                                        unsigned immOpcH,
7942                                                        bool invSrc) const {
7943   // For the atomic bitwise operator, we generate
7944   //   thisMBB (instructions are in pairs, except cmpxchg8b)
7945   //     ld t1,t2 = [bitinstr.addr]
7946   //   newMBB:
7947   //     out1, out2 = phi (thisMBB, t1/t2) (newMBB, t3/t4)
7948   //     op  t5, t6 <- out1, out2, [bitinstr.val]
7949   //      (for SWAP, substitute:  mov t5, t6 <- [bitinstr.val])
7950   //     mov ECX, EBX <- t5, t6
7951   //     mov EAX, EDX <- t1, t2
7952   //     cmpxchg8b [bitinstr.addr]  [EAX, EDX, EBX, ECX implicit]
7953   //     mov t3, t4 <- EAX, EDX
7954   //     bz  newMBB
7955   //     result in out1, out2
7956   //     fallthrough -->nextMBB
7957
7958   const TargetRegisterClass *RC = X86::GR32RegisterClass;
7959   const unsigned LoadOpc = X86::MOV32rm;
7960   const unsigned copyOpc = X86::MOV32rr;
7961   const unsigned NotOpc = X86::NOT32r;
7962   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
7963   const BasicBlock *LLVM_BB = MBB->getBasicBlock();
7964   MachineFunction::iterator MBBIter = MBB;
7965   ++MBBIter;
7966
7967   /// First build the CFG
7968   MachineFunction *F = MBB->getParent();
7969   MachineBasicBlock *thisMBB = MBB;
7970   MachineBasicBlock *newMBB = F->CreateMachineBasicBlock(LLVM_BB);
7971   MachineBasicBlock *nextMBB = F->CreateMachineBasicBlock(LLVM_BB);
7972   F->insert(MBBIter, newMBB);
7973   F->insert(MBBIter, nextMBB);
7974
7975   // Move all successors to thisMBB to nextMBB
7976   nextMBB->transferSuccessors(thisMBB);
7977
7978   // Update thisMBB to fall through to newMBB
7979   thisMBB->addSuccessor(newMBB);
7980
7981   // newMBB jumps to itself and fall through to nextMBB
7982   newMBB->addSuccessor(nextMBB);
7983   newMBB->addSuccessor(newMBB);
7984
7985   DebugLoc dl = bInstr->getDebugLoc();
7986   // Insert instructions into newMBB based on incoming instruction
7987   // There are 8 "real" operands plus 9 implicit def/uses, ignored here.
7988   assert(bInstr->getNumOperands() < X86AddrNumOperands + 14 &&
7989          "unexpected number of operands");
7990   MachineOperand& dest1Oper = bInstr->getOperand(0);
7991   MachineOperand& dest2Oper = bInstr->getOperand(1);
7992   MachineOperand* argOpers[2 + X86AddrNumOperands];
7993   for (int i=0; i < 2 + X86AddrNumOperands; ++i)
7994     argOpers[i] = &bInstr->getOperand(i+2);
7995
7996   // x86 address has 5 operands: base, index, scale, displacement, and segment.
7997   int lastAddrIndx = X86AddrNumOperands - 1; // [0,3]
7998
7999   unsigned t1 = F->getRegInfo().createVirtualRegister(RC);
8000   MachineInstrBuilder MIB = BuildMI(thisMBB, dl, TII->get(LoadOpc), t1);
8001   for (int i=0; i <= lastAddrIndx; ++i)
8002     (*MIB).addOperand(*argOpers[i]);
8003   unsigned t2 = F->getRegInfo().createVirtualRegister(RC);
8004   MIB = BuildMI(thisMBB, dl, TII->get(LoadOpc), t2);
8005   // add 4 to displacement.
8006   for (int i=0; i <= lastAddrIndx-2; ++i)
8007     (*MIB).addOperand(*argOpers[i]);
8008   MachineOperand newOp3 = *(argOpers[3]);
8009   if (newOp3.isImm())
8010     newOp3.setImm(newOp3.getImm()+4);
8011   else
8012     newOp3.setOffset(newOp3.getOffset()+4);
8013   (*MIB).addOperand(newOp3);
8014   (*MIB).addOperand(*argOpers[lastAddrIndx]);
8015
8016   // t3/4 are defined later, at the bottom of the loop
8017   unsigned t3 = F->getRegInfo().createVirtualRegister(RC);
8018   unsigned t4 = F->getRegInfo().createVirtualRegister(RC);
8019   BuildMI(newMBB, dl, TII->get(X86::PHI), dest1Oper.getReg())
8020     .addReg(t1).addMBB(thisMBB).addReg(t3).addMBB(newMBB);
8021   BuildMI(newMBB, dl, TII->get(X86::PHI), dest2Oper.getReg())
8022     .addReg(t2).addMBB(thisMBB).addReg(t4).addMBB(newMBB);
8023
8024   // The subsequent operations should be using the destination registers of
8025   //the PHI instructions.
8026   if (invSrc) {
8027     t1 = F->getRegInfo().createVirtualRegister(RC);
8028     t2 = F->getRegInfo().createVirtualRegister(RC);
8029     MIB = BuildMI(newMBB, dl, TII->get(NotOpc), t1).addReg(dest1Oper.getReg());
8030     MIB = BuildMI(newMBB, dl, TII->get(NotOpc), t2).addReg(dest2Oper.getReg());
8031   } else {
8032     t1 = dest1Oper.getReg();
8033     t2 = dest2Oper.getReg();
8034   }
8035
8036   int valArgIndx = lastAddrIndx + 1;
8037   assert((argOpers[valArgIndx]->isReg() ||
8038           argOpers[valArgIndx]->isImm()) &&
8039          "invalid operand");
8040   unsigned t5 = F->getRegInfo().createVirtualRegister(RC);
8041   unsigned t6 = F->getRegInfo().createVirtualRegister(RC);
8042   if (argOpers[valArgIndx]->isReg())
8043     MIB = BuildMI(newMBB, dl, TII->get(regOpcL), t5);
8044   else
8045     MIB = BuildMI(newMBB, dl, TII->get(immOpcL), t5);
8046   if (regOpcL != X86::MOV32rr)
8047     MIB.addReg(t1);
8048   (*MIB).addOperand(*argOpers[valArgIndx]);
8049   assert(argOpers[valArgIndx + 1]->isReg() ==
8050          argOpers[valArgIndx]->isReg());
8051   assert(argOpers[valArgIndx + 1]->isImm() ==
8052          argOpers[valArgIndx]->isImm());
8053   if (argOpers[valArgIndx + 1]->isReg())
8054     MIB = BuildMI(newMBB, dl, TII->get(regOpcH), t6);
8055   else
8056     MIB = BuildMI(newMBB, dl, TII->get(immOpcH), t6);
8057   if (regOpcH != X86::MOV32rr)
8058     MIB.addReg(t2);
8059   (*MIB).addOperand(*argOpers[valArgIndx + 1]);
8060
8061   MIB = BuildMI(newMBB, dl, TII->get(copyOpc), X86::EAX);
8062   MIB.addReg(t1);
8063   MIB = BuildMI(newMBB, dl, TII->get(copyOpc), X86::EDX);
8064   MIB.addReg(t2);
8065
8066   MIB = BuildMI(newMBB, dl, TII->get(copyOpc), X86::EBX);
8067   MIB.addReg(t5);
8068   MIB = BuildMI(newMBB, dl, TII->get(copyOpc), X86::ECX);
8069   MIB.addReg(t6);
8070
8071   MIB = BuildMI(newMBB, dl, TII->get(X86::LCMPXCHG8B));
8072   for (int i=0; i <= lastAddrIndx; ++i)
8073     (*MIB).addOperand(*argOpers[i]);
8074
8075   assert(bInstr->hasOneMemOperand() && "Unexpected number of memoperand");
8076   (*MIB).setMemRefs(bInstr->memoperands_begin(),
8077                     bInstr->memoperands_end());
8078
8079   MIB = BuildMI(newMBB, dl, TII->get(copyOpc), t3);
8080   MIB.addReg(X86::EAX);
8081   MIB = BuildMI(newMBB, dl, TII->get(copyOpc), t4);
8082   MIB.addReg(X86::EDX);
8083
8084   // insert branch
8085   BuildMI(newMBB, dl, TII->get(X86::JNE)).addMBB(newMBB);
8086
8087   F->DeleteMachineInstr(bInstr);   // The pseudo instruction is gone now.
8088   return nextMBB;
8089 }
8090
8091 // private utility function
8092 MachineBasicBlock *
8093 X86TargetLowering::EmitAtomicMinMaxWithCustomInserter(MachineInstr *mInstr,
8094                                                       MachineBasicBlock *MBB,
8095                                                       unsigned cmovOpc) const {
8096   // For the atomic min/max operator, we generate
8097   //   thisMBB:
8098   //   newMBB:
8099   //     ld t1 = [min/max.addr]
8100   //     mov t2 = [min/max.val]
8101   //     cmp  t1, t2
8102   //     cmov[cond] t2 = t1
8103   //     mov EAX = t1
8104   //     lcs dest = [bitinstr.addr], t2  [EAX is implicit]
8105   //     bz   newMBB
8106   //     fallthrough -->nextMBB
8107   //
8108   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
8109   const BasicBlock *LLVM_BB = MBB->getBasicBlock();
8110   MachineFunction::iterator MBBIter = MBB;
8111   ++MBBIter;
8112
8113   /// First build the CFG
8114   MachineFunction *F = MBB->getParent();
8115   MachineBasicBlock *thisMBB = MBB;
8116   MachineBasicBlock *newMBB = F->CreateMachineBasicBlock(LLVM_BB);
8117   MachineBasicBlock *nextMBB = F->CreateMachineBasicBlock(LLVM_BB);
8118   F->insert(MBBIter, newMBB);
8119   F->insert(MBBIter, nextMBB);
8120
8121   // Move all successors of thisMBB to nextMBB
8122   nextMBB->transferSuccessors(thisMBB);
8123
8124   // Update thisMBB to fall through to newMBB
8125   thisMBB->addSuccessor(newMBB);
8126
8127   // newMBB jumps to newMBB and fall through to nextMBB
8128   newMBB->addSuccessor(nextMBB);
8129   newMBB->addSuccessor(newMBB);
8130
8131   DebugLoc dl = mInstr->getDebugLoc();
8132   // Insert instructions into newMBB based on incoming instruction
8133   assert(mInstr->getNumOperands() < X86AddrNumOperands + 4 &&
8134          "unexpected number of operands");
8135   MachineOperand& destOper = mInstr->getOperand(0);
8136   MachineOperand* argOpers[2 + X86AddrNumOperands];
8137   int numArgs = mInstr->getNumOperands() - 1;
8138   for (int i=0; i < numArgs; ++i)
8139     argOpers[i] = &mInstr->getOperand(i+1);
8140
8141   // x86 address has 4 operands: base, index, scale, and displacement
8142   int lastAddrIndx = X86AddrNumOperands - 1; // [0,3]
8143   int valArgIndx = lastAddrIndx + 1;
8144
8145   unsigned t1 = F->getRegInfo().createVirtualRegister(X86::GR32RegisterClass);
8146   MachineInstrBuilder MIB = BuildMI(newMBB, dl, TII->get(X86::MOV32rm), t1);
8147   for (int i=0; i <= lastAddrIndx; ++i)
8148     (*MIB).addOperand(*argOpers[i]);
8149
8150   // We only support register and immediate values
8151   assert((argOpers[valArgIndx]->isReg() ||
8152           argOpers[valArgIndx]->isImm()) &&
8153          "invalid operand");
8154
8155   unsigned t2 = F->getRegInfo().createVirtualRegister(X86::GR32RegisterClass);
8156   if (argOpers[valArgIndx]->isReg())
8157     MIB = BuildMI(newMBB, dl, TII->get(X86::MOV32rr), t2);
8158   else
8159     MIB = BuildMI(newMBB, dl, TII->get(X86::MOV32rr), t2);
8160   (*MIB).addOperand(*argOpers[valArgIndx]);
8161
8162   MIB = BuildMI(newMBB, dl, TII->get(X86::MOV32rr), X86::EAX);
8163   MIB.addReg(t1);
8164
8165   MIB = BuildMI(newMBB, dl, TII->get(X86::CMP32rr));
8166   MIB.addReg(t1);
8167   MIB.addReg(t2);
8168
8169   // Generate movc
8170   unsigned t3 = F->getRegInfo().createVirtualRegister(X86::GR32RegisterClass);
8171   MIB = BuildMI(newMBB, dl, TII->get(cmovOpc),t3);
8172   MIB.addReg(t2);
8173   MIB.addReg(t1);
8174
8175   // Cmp and exchange if none has modified the memory location
8176   MIB = BuildMI(newMBB, dl, TII->get(X86::LCMPXCHG32));
8177   for (int i=0; i <= lastAddrIndx; ++i)
8178     (*MIB).addOperand(*argOpers[i]);
8179   MIB.addReg(t3);
8180   assert(mInstr->hasOneMemOperand() && "Unexpected number of memoperand");
8181   (*MIB).setMemRefs(mInstr->memoperands_begin(),
8182                     mInstr->memoperands_end());
8183
8184   MIB = BuildMI(newMBB, dl, TII->get(X86::MOV32rr), destOper.getReg());
8185   MIB.addReg(X86::EAX);
8186
8187   // insert branch
8188   BuildMI(newMBB, dl, TII->get(X86::JNE)).addMBB(newMBB);
8189
8190   F->DeleteMachineInstr(mInstr);   // The pseudo instruction is gone now.
8191   return nextMBB;
8192 }
8193
8194 // FIXME: When we get size specific XMM0 registers, i.e. XMM0_V16I8
8195 // all of this code can be replaced with that in the .td file.
8196 MachineBasicBlock *
8197 X86TargetLowering::EmitPCMP(MachineInstr *MI, MachineBasicBlock *BB,
8198                             unsigned numArgs, bool memArg) const {
8199
8200   MachineFunction *F = BB->getParent();
8201   DebugLoc dl = MI->getDebugLoc();
8202   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
8203
8204   unsigned Opc;
8205   if (memArg)
8206     Opc = numArgs == 3 ? X86::PCMPISTRM128rm : X86::PCMPESTRM128rm;
8207   else
8208     Opc = numArgs == 3 ? X86::PCMPISTRM128rr : X86::PCMPESTRM128rr;
8209
8210   MachineInstrBuilder MIB = BuildMI(BB, dl, TII->get(Opc));
8211
8212   for (unsigned i = 0; i < numArgs; ++i) {
8213     MachineOperand &Op = MI->getOperand(i+1);
8214
8215     if (!(Op.isReg() && Op.isImplicit()))
8216       MIB.addOperand(Op);
8217   }
8218
8219   BuildMI(BB, dl, TII->get(X86::MOVAPSrr), MI->getOperand(0).getReg())
8220     .addReg(X86::XMM0);
8221
8222   F->DeleteMachineInstr(MI);
8223
8224   return BB;
8225 }
8226
8227 MachineBasicBlock *
8228 X86TargetLowering::EmitVAStartSaveXMMRegsWithCustomInserter(
8229                                                  MachineInstr *MI,
8230                                                  MachineBasicBlock *MBB) const {
8231   // Emit code to save XMM registers to the stack. The ABI says that the
8232   // number of registers to save is given in %al, so it's theoretically
8233   // possible to do an indirect jump trick to avoid saving all of them,
8234   // however this code takes a simpler approach and just executes all
8235   // of the stores if %al is non-zero. It's less code, and it's probably
8236   // easier on the hardware branch predictor, and stores aren't all that
8237   // expensive anyway.
8238
8239   // Create the new basic blocks. One block contains all the XMM stores,
8240   // and one block is the final destination regardless of whether any
8241   // stores were performed.
8242   const BasicBlock *LLVM_BB = MBB->getBasicBlock();
8243   MachineFunction *F = MBB->getParent();
8244   MachineFunction::iterator MBBIter = MBB;
8245   ++MBBIter;
8246   MachineBasicBlock *XMMSaveMBB = F->CreateMachineBasicBlock(LLVM_BB);
8247   MachineBasicBlock *EndMBB = F->CreateMachineBasicBlock(LLVM_BB);
8248   F->insert(MBBIter, XMMSaveMBB);
8249   F->insert(MBBIter, EndMBB);
8250
8251   // Set up the CFG.
8252   // Move any original successors of MBB to the end block.
8253   EndMBB->transferSuccessors(MBB);
8254   // The original block will now fall through to the XMM save block.
8255   MBB->addSuccessor(XMMSaveMBB);
8256   // The XMMSaveMBB will fall through to the end block.
8257   XMMSaveMBB->addSuccessor(EndMBB);
8258
8259   // Now add the instructions.
8260   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
8261   DebugLoc DL = MI->getDebugLoc();
8262
8263   unsigned CountReg = MI->getOperand(0).getReg();
8264   int64_t RegSaveFrameIndex = MI->getOperand(1).getImm();
8265   int64_t VarArgsFPOffset = MI->getOperand(2).getImm();
8266
8267   if (!Subtarget->isTargetWin64()) {
8268     // If %al is 0, branch around the XMM save block.
8269     BuildMI(MBB, DL, TII->get(X86::TEST8rr)).addReg(CountReg).addReg(CountReg);
8270     BuildMI(MBB, DL, TII->get(X86::JE)).addMBB(EndMBB);
8271     MBB->addSuccessor(EndMBB);
8272   }
8273
8274   // In the XMM save block, save all the XMM argument registers.
8275   for (int i = 3, e = MI->getNumOperands(); i != e; ++i) {
8276     int64_t Offset = (i - 3) * 16 + VarArgsFPOffset;
8277     MachineMemOperand *MMO =
8278       F->getMachineMemOperand(
8279         PseudoSourceValue::getFixedStack(RegSaveFrameIndex),
8280         MachineMemOperand::MOStore, Offset,
8281         /*Size=*/16, /*Align=*/16);
8282     BuildMI(XMMSaveMBB, DL, TII->get(X86::MOVAPSmr))
8283       .addFrameIndex(RegSaveFrameIndex)
8284       .addImm(/*Scale=*/1)
8285       .addReg(/*IndexReg=*/0)
8286       .addImm(/*Disp=*/Offset)
8287       .addReg(/*Segment=*/0)
8288       .addReg(MI->getOperand(i).getReg())
8289       .addMemOperand(MMO);
8290   }
8291
8292   F->DeleteMachineInstr(MI);   // The pseudo instruction is gone now.
8293
8294   return EndMBB;
8295 }
8296
8297 MachineBasicBlock *
8298 X86TargetLowering::EmitLoweredSelect(MachineInstr *MI,
8299                                      MachineBasicBlock *BB,
8300                    DenseMap<MachineBasicBlock*, MachineBasicBlock*> *EM) const {
8301   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
8302   DebugLoc DL = MI->getDebugLoc();
8303
8304   // To "insert" a SELECT_CC instruction, we actually have to insert the
8305   // diamond control-flow pattern.  The incoming instruction knows the
8306   // destination vreg to set, the condition code register to branch on, the
8307   // true/false values to select between, and a branch opcode to use.
8308   const BasicBlock *LLVM_BB = BB->getBasicBlock();
8309   MachineFunction::iterator It = BB;
8310   ++It;
8311
8312   //  thisMBB:
8313   //  ...
8314   //   TrueVal = ...
8315   //   cmpTY ccX, r1, r2
8316   //   bCC copy1MBB
8317   //   fallthrough --> copy0MBB
8318   MachineBasicBlock *thisMBB = BB;
8319   MachineFunction *F = BB->getParent();
8320   MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
8321   MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
8322   unsigned Opc =
8323     X86::GetCondBranchFromCond((X86::CondCode)MI->getOperand(3).getImm());
8324   BuildMI(BB, DL, TII->get(Opc)).addMBB(sinkMBB);
8325   F->insert(It, copy0MBB);
8326   F->insert(It, sinkMBB);
8327   // Update machine-CFG edges by first adding all successors of the current
8328   // block to the new block which will contain the Phi node for the select.
8329   // Also inform sdisel of the edge changes.
8330   for (MachineBasicBlock::succ_iterator I = BB->succ_begin(),
8331          E = BB->succ_end(); I != E; ++I) {
8332     EM->insert(std::make_pair(*I, sinkMBB));
8333     sinkMBB->addSuccessor(*I);
8334   }
8335   // Next, remove all successors of the current block, and add the true
8336   // and fallthrough blocks as its successors.
8337   while (!BB->succ_empty())
8338     BB->removeSuccessor(BB->succ_begin());
8339   // Add the true and fallthrough blocks as its successors.
8340   BB->addSuccessor(copy0MBB);
8341   BB->addSuccessor(sinkMBB);
8342
8343   //  copy0MBB:
8344   //   %FalseValue = ...
8345   //   # fallthrough to sinkMBB
8346   BB = copy0MBB;
8347
8348   // Update machine-CFG edges
8349   BB->addSuccessor(sinkMBB);
8350
8351   //  sinkMBB:
8352   //   %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
8353   //  ...
8354   BB = sinkMBB;
8355   BuildMI(BB, DL, TII->get(X86::PHI), MI->getOperand(0).getReg())
8356     .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB)
8357     .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
8358
8359   F->DeleteMachineInstr(MI);   // The pseudo instruction is gone now.
8360   return BB;
8361 }
8362
8363
8364 MachineBasicBlock *
8365 X86TargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
8366                                                MachineBasicBlock *BB,
8367                    DenseMap<MachineBasicBlock*, MachineBasicBlock*> *EM) const {
8368   switch (MI->getOpcode()) {
8369   default: assert(false && "Unexpected instr type to insert");
8370   case X86::CMOV_GR8:
8371   case X86::CMOV_V1I64:
8372   case X86::CMOV_FR32:
8373   case X86::CMOV_FR64:
8374   case X86::CMOV_V4F32:
8375   case X86::CMOV_V2F64:
8376   case X86::CMOV_V2I64:
8377     return EmitLoweredSelect(MI, BB, EM);
8378
8379   case X86::FP32_TO_INT16_IN_MEM:
8380   case X86::FP32_TO_INT32_IN_MEM:
8381   case X86::FP32_TO_INT64_IN_MEM:
8382   case X86::FP64_TO_INT16_IN_MEM:
8383   case X86::FP64_TO_INT32_IN_MEM:
8384   case X86::FP64_TO_INT64_IN_MEM:
8385   case X86::FP80_TO_INT16_IN_MEM:
8386   case X86::FP80_TO_INT32_IN_MEM:
8387   case X86::FP80_TO_INT64_IN_MEM: {
8388     const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
8389     DebugLoc DL = MI->getDebugLoc();
8390
8391     // Change the floating point control register to use "round towards zero"
8392     // mode when truncating to an integer value.
8393     MachineFunction *F = BB->getParent();
8394     int CWFrameIdx = F->getFrameInfo()->CreateStackObject(2, 2, false);
8395     addFrameReference(BuildMI(BB, DL, TII->get(X86::FNSTCW16m)), CWFrameIdx);
8396
8397     // Load the old value of the high byte of the control word...
8398     unsigned OldCW =
8399       F->getRegInfo().createVirtualRegister(X86::GR16RegisterClass);
8400     addFrameReference(BuildMI(BB, DL, TII->get(X86::MOV16rm), OldCW),
8401                       CWFrameIdx);
8402
8403     // Set the high part to be round to zero...
8404     addFrameReference(BuildMI(BB, DL, TII->get(X86::MOV16mi)), CWFrameIdx)
8405       .addImm(0xC7F);
8406
8407     // Reload the modified control word now...
8408     addFrameReference(BuildMI(BB, DL, TII->get(X86::FLDCW16m)), CWFrameIdx);
8409
8410     // Restore the memory image of control word to original value
8411     addFrameReference(BuildMI(BB, DL, TII->get(X86::MOV16mr)), CWFrameIdx)
8412       .addReg(OldCW);
8413
8414     // Get the X86 opcode to use.
8415     unsigned Opc;
8416     switch (MI->getOpcode()) {
8417     default: llvm_unreachable("illegal opcode!");
8418     case X86::FP32_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m32; break;
8419     case X86::FP32_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m32; break;
8420     case X86::FP32_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m32; break;
8421     case X86::FP64_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m64; break;
8422     case X86::FP64_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m64; break;
8423     case X86::FP64_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m64; break;
8424     case X86::FP80_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m80; break;
8425     case X86::FP80_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m80; break;
8426     case X86::FP80_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m80; break;
8427     }
8428
8429     X86AddressMode AM;
8430     MachineOperand &Op = MI->getOperand(0);
8431     if (Op.isReg()) {
8432       AM.BaseType = X86AddressMode::RegBase;
8433       AM.Base.Reg = Op.getReg();
8434     } else {
8435       AM.BaseType = X86AddressMode::FrameIndexBase;
8436       AM.Base.FrameIndex = Op.getIndex();
8437     }
8438     Op = MI->getOperand(1);
8439     if (Op.isImm())
8440       AM.Scale = Op.getImm();
8441     Op = MI->getOperand(2);
8442     if (Op.isImm())
8443       AM.IndexReg = Op.getImm();
8444     Op = MI->getOperand(3);
8445     if (Op.isGlobal()) {
8446       AM.GV = Op.getGlobal();
8447     } else {
8448       AM.Disp = Op.getImm();
8449     }
8450     addFullAddress(BuildMI(BB, DL, TII->get(Opc)), AM)
8451                       .addReg(MI->getOperand(X86AddrNumOperands).getReg());
8452
8453     // Reload the original control word now.
8454     addFrameReference(BuildMI(BB, DL, TII->get(X86::FLDCW16m)), CWFrameIdx);
8455
8456     F->DeleteMachineInstr(MI);   // The pseudo instruction is gone now.
8457     return BB;
8458   }
8459     // String/text processing lowering.
8460   case X86::PCMPISTRM128REG:
8461     return EmitPCMP(MI, BB, 3, false /* in-mem */);
8462   case X86::PCMPISTRM128MEM:
8463     return EmitPCMP(MI, BB, 3, true /* in-mem */);
8464   case X86::PCMPESTRM128REG:
8465     return EmitPCMP(MI, BB, 5, false /* in mem */);
8466   case X86::PCMPESTRM128MEM:
8467     return EmitPCMP(MI, BB, 5, true /* in mem */);
8468
8469     // Atomic Lowering.
8470   case X86::ATOMAND32:
8471     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND32rr,
8472                                                X86::AND32ri, X86::MOV32rm,
8473                                                X86::LCMPXCHG32, X86::MOV32rr,
8474                                                X86::NOT32r, X86::EAX,
8475                                                X86::GR32RegisterClass);
8476   case X86::ATOMOR32:
8477     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR32rr,
8478                                                X86::OR32ri, X86::MOV32rm,
8479                                                X86::LCMPXCHG32, X86::MOV32rr,
8480                                                X86::NOT32r, X86::EAX,
8481                                                X86::GR32RegisterClass);
8482   case X86::ATOMXOR32:
8483     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR32rr,
8484                                                X86::XOR32ri, X86::MOV32rm,
8485                                                X86::LCMPXCHG32, X86::MOV32rr,
8486                                                X86::NOT32r, X86::EAX,
8487                                                X86::GR32RegisterClass);
8488   case X86::ATOMNAND32:
8489     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND32rr,
8490                                                X86::AND32ri, X86::MOV32rm,
8491                                                X86::LCMPXCHG32, X86::MOV32rr,
8492                                                X86::NOT32r, X86::EAX,
8493                                                X86::GR32RegisterClass, true);
8494   case X86::ATOMMIN32:
8495     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVL32rr);
8496   case X86::ATOMMAX32:
8497     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVG32rr);
8498   case X86::ATOMUMIN32:
8499     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVB32rr);
8500   case X86::ATOMUMAX32:
8501     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVA32rr);
8502
8503   case X86::ATOMAND16:
8504     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND16rr,
8505                                                X86::AND16ri, X86::MOV16rm,
8506                                                X86::LCMPXCHG16, X86::MOV16rr,
8507                                                X86::NOT16r, X86::AX,
8508                                                X86::GR16RegisterClass);
8509   case X86::ATOMOR16:
8510     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR16rr,
8511                                                X86::OR16ri, X86::MOV16rm,
8512                                                X86::LCMPXCHG16, X86::MOV16rr,
8513                                                X86::NOT16r, X86::AX,
8514                                                X86::GR16RegisterClass);
8515   case X86::ATOMXOR16:
8516     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR16rr,
8517                                                X86::XOR16ri, X86::MOV16rm,
8518                                                X86::LCMPXCHG16, X86::MOV16rr,
8519                                                X86::NOT16r, X86::AX,
8520                                                X86::GR16RegisterClass);
8521   case X86::ATOMNAND16:
8522     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND16rr,
8523                                                X86::AND16ri, X86::MOV16rm,
8524                                                X86::LCMPXCHG16, X86::MOV16rr,
8525                                                X86::NOT16r, X86::AX,
8526                                                X86::GR16RegisterClass, true);
8527   case X86::ATOMMIN16:
8528     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVL16rr);
8529   case X86::ATOMMAX16:
8530     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVG16rr);
8531   case X86::ATOMUMIN16:
8532     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVB16rr);
8533   case X86::ATOMUMAX16:
8534     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVA16rr);
8535
8536   case X86::ATOMAND8:
8537     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND8rr,
8538                                                X86::AND8ri, X86::MOV8rm,
8539                                                X86::LCMPXCHG8, X86::MOV8rr,
8540                                                X86::NOT8r, X86::AL,
8541                                                X86::GR8RegisterClass);
8542   case X86::ATOMOR8:
8543     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR8rr,
8544                                                X86::OR8ri, X86::MOV8rm,
8545                                                X86::LCMPXCHG8, X86::MOV8rr,
8546                                                X86::NOT8r, X86::AL,
8547                                                X86::GR8RegisterClass);
8548   case X86::ATOMXOR8:
8549     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR8rr,
8550                                                X86::XOR8ri, X86::MOV8rm,
8551                                                X86::LCMPXCHG8, X86::MOV8rr,
8552                                                X86::NOT8r, X86::AL,
8553                                                X86::GR8RegisterClass);
8554   case X86::ATOMNAND8:
8555     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND8rr,
8556                                                X86::AND8ri, X86::MOV8rm,
8557                                                X86::LCMPXCHG8, X86::MOV8rr,
8558                                                X86::NOT8r, X86::AL,
8559                                                X86::GR8RegisterClass, true);
8560   // FIXME: There are no CMOV8 instructions; MIN/MAX need some other way.
8561   // This group is for 64-bit host.
8562   case X86::ATOMAND64:
8563     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND64rr,
8564                                                X86::AND64ri32, X86::MOV64rm,
8565                                                X86::LCMPXCHG64, X86::MOV64rr,
8566                                                X86::NOT64r, X86::RAX,
8567                                                X86::GR64RegisterClass);
8568   case X86::ATOMOR64:
8569     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR64rr,
8570                                                X86::OR64ri32, X86::MOV64rm,
8571                                                X86::LCMPXCHG64, X86::MOV64rr,
8572                                                X86::NOT64r, X86::RAX,
8573                                                X86::GR64RegisterClass);
8574   case X86::ATOMXOR64:
8575     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR64rr,
8576                                                X86::XOR64ri32, X86::MOV64rm,
8577                                                X86::LCMPXCHG64, X86::MOV64rr,
8578                                                X86::NOT64r, X86::RAX,
8579                                                X86::GR64RegisterClass);
8580   case X86::ATOMNAND64:
8581     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND64rr,
8582                                                X86::AND64ri32, X86::MOV64rm,
8583                                                X86::LCMPXCHG64, X86::MOV64rr,
8584                                                X86::NOT64r, X86::RAX,
8585                                                X86::GR64RegisterClass, true);
8586   case X86::ATOMMIN64:
8587     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVL64rr);
8588   case X86::ATOMMAX64:
8589     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVG64rr);
8590   case X86::ATOMUMIN64:
8591     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVB64rr);
8592   case X86::ATOMUMAX64:
8593     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVA64rr);
8594
8595   // This group does 64-bit operations on a 32-bit host.
8596   case X86::ATOMAND6432:
8597     return EmitAtomicBit6432WithCustomInserter(MI, BB,
8598                                                X86::AND32rr, X86::AND32rr,
8599                                                X86::AND32ri, X86::AND32ri,
8600                                                false);
8601   case X86::ATOMOR6432:
8602     return EmitAtomicBit6432WithCustomInserter(MI, BB,
8603                                                X86::OR32rr, X86::OR32rr,
8604                                                X86::OR32ri, X86::OR32ri,
8605                                                false);
8606   case X86::ATOMXOR6432:
8607     return EmitAtomicBit6432WithCustomInserter(MI, BB,
8608                                                X86::XOR32rr, X86::XOR32rr,
8609                                                X86::XOR32ri, X86::XOR32ri,
8610                                                false);
8611   case X86::ATOMNAND6432:
8612     return EmitAtomicBit6432WithCustomInserter(MI, BB,
8613                                                X86::AND32rr, X86::AND32rr,
8614                                                X86::AND32ri, X86::AND32ri,
8615                                                true);
8616   case X86::ATOMADD6432:
8617     return EmitAtomicBit6432WithCustomInserter(MI, BB,
8618                                                X86::ADD32rr, X86::ADC32rr,
8619                                                X86::ADD32ri, X86::ADC32ri,
8620                                                false);
8621   case X86::ATOMSUB6432:
8622     return EmitAtomicBit6432WithCustomInserter(MI, BB,
8623                                                X86::SUB32rr, X86::SBB32rr,
8624                                                X86::SUB32ri, X86::SBB32ri,
8625                                                false);
8626   case X86::ATOMSWAP6432:
8627     return EmitAtomicBit6432WithCustomInserter(MI, BB,
8628                                                X86::MOV32rr, X86::MOV32rr,
8629                                                X86::MOV32ri, X86::MOV32ri,
8630                                                false);
8631   case X86::VASTART_SAVE_XMM_REGS:
8632     return EmitVAStartSaveXMMRegsWithCustomInserter(MI, BB);
8633   }
8634 }
8635
8636 //===----------------------------------------------------------------------===//
8637 //                           X86 Optimization Hooks
8638 //===----------------------------------------------------------------------===//
8639
8640 void X86TargetLowering::computeMaskedBitsForTargetNode(const SDValue Op,
8641                                                        const APInt &Mask,
8642                                                        APInt &KnownZero,
8643                                                        APInt &KnownOne,
8644                                                        const SelectionDAG &DAG,
8645                                                        unsigned Depth) const {
8646   unsigned Opc = Op.getOpcode();
8647   assert((Opc >= ISD::BUILTIN_OP_END ||
8648           Opc == ISD::INTRINSIC_WO_CHAIN ||
8649           Opc == ISD::INTRINSIC_W_CHAIN ||
8650           Opc == ISD::INTRINSIC_VOID) &&
8651          "Should use MaskedValueIsZero if you don't know whether Op"
8652          " is a target node!");
8653
8654   KnownZero = KnownOne = APInt(Mask.getBitWidth(), 0);   // Don't know anything.
8655   switch (Opc) {
8656   default: break;
8657   case X86ISD::ADD:
8658   case X86ISD::SUB:
8659   case X86ISD::SMUL:
8660   case X86ISD::UMUL:
8661   case X86ISD::INC:
8662   case X86ISD::DEC:
8663   case X86ISD::OR:
8664   case X86ISD::XOR:
8665   case X86ISD::AND:
8666     // These nodes' second result is a boolean.
8667     if (Op.getResNo() == 0)
8668       break;
8669     // Fallthrough
8670   case X86ISD::SETCC:
8671     KnownZero |= APInt::getHighBitsSet(Mask.getBitWidth(),
8672                                        Mask.getBitWidth() - 1);
8673     break;
8674   }
8675 }
8676
8677 /// isGAPlusOffset - Returns true (and the GlobalValue and the offset) if the
8678 /// node is a GlobalAddress + offset.
8679 bool X86TargetLowering::isGAPlusOffset(SDNode *N,
8680                                        GlobalValue* &GA, int64_t &Offset) const{
8681   if (N->getOpcode() == X86ISD::Wrapper) {
8682     if (isa<GlobalAddressSDNode>(N->getOperand(0))) {
8683       GA = cast<GlobalAddressSDNode>(N->getOperand(0))->getGlobal();
8684       Offset = cast<GlobalAddressSDNode>(N->getOperand(0))->getOffset();
8685       return true;
8686     }
8687   }
8688   return TargetLowering::isGAPlusOffset(N, GA, Offset);
8689 }
8690
8691 static bool EltsFromConsecutiveLoads(ShuffleVectorSDNode *N, unsigned NumElems,
8692                                      EVT EltVT, LoadSDNode *&LDBase,
8693                                      unsigned &LastLoadedElt,
8694                                      SelectionDAG &DAG, MachineFrameInfo *MFI,
8695                                      const TargetLowering &TLI) {
8696   LDBase = NULL;
8697   LastLoadedElt = -1U;
8698   for (unsigned i = 0; i < NumElems; ++i) {
8699     if (N->getMaskElt(i) < 0) {
8700       if (!LDBase)
8701         return false;
8702       continue;
8703     }
8704
8705     SDValue Elt = DAG.getShuffleScalarElt(N, i);
8706     if (!Elt.getNode() ||
8707         (Elt.getOpcode() != ISD::UNDEF && !ISD::isNON_EXTLoad(Elt.getNode())))
8708       return false;
8709     if (!LDBase) {
8710       if (Elt.getNode()->getOpcode() == ISD::UNDEF)
8711         return false;
8712       LDBase = cast<LoadSDNode>(Elt.getNode());
8713       LastLoadedElt = i;
8714       continue;
8715     }
8716     if (Elt.getOpcode() == ISD::UNDEF)
8717       continue;
8718
8719     LoadSDNode *LD = cast<LoadSDNode>(Elt);
8720     if (!DAG.isConsecutiveLoad(LD, LDBase, EltVT.getSizeInBits()/8, i))
8721       return false;
8722     LastLoadedElt = i;
8723   }
8724   return true;
8725 }
8726
8727 /// PerformShuffleCombine - Combine a vector_shuffle that is equal to
8728 /// build_vector load1, load2, load3, load4, <0, 1, 2, 3> into a 128-bit load
8729 /// if the load addresses are consecutive, non-overlapping, and in the right
8730 /// order.  In the case of v2i64, it will see if it can rewrite the
8731 /// shuffle to be an appropriate build vector so it can take advantage of
8732 // performBuildVectorCombine.
8733 static SDValue PerformShuffleCombine(SDNode *N, SelectionDAG &DAG,
8734                                      const TargetLowering &TLI) {
8735   DebugLoc dl = N->getDebugLoc();
8736   EVT VT = N->getValueType(0);
8737   EVT EltVT = VT.getVectorElementType();
8738   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
8739   unsigned NumElems = VT.getVectorNumElements();
8740
8741   if (VT.getSizeInBits() != 128)
8742     return SDValue();
8743
8744   // Try to combine a vector_shuffle into a 128-bit load.
8745   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
8746   LoadSDNode *LD = NULL;
8747   unsigned LastLoadedElt;
8748   if (!EltsFromConsecutiveLoads(SVN, NumElems, EltVT, LD, LastLoadedElt, DAG,
8749                                 MFI, TLI))
8750     return SDValue();
8751
8752   if (LastLoadedElt == NumElems - 1) {
8753     if (DAG.InferPtrAlignment(LD->getBasePtr()) >= 16)
8754       return DAG.getLoad(VT, dl, LD->getChain(), LD->getBasePtr(),
8755                          LD->getSrcValue(), LD->getSrcValueOffset(),
8756                          LD->isVolatile());
8757     return DAG.getLoad(VT, dl, LD->getChain(), LD->getBasePtr(),
8758                        LD->getSrcValue(), LD->getSrcValueOffset(),
8759                        LD->isVolatile(), LD->getAlignment());
8760   } else if (NumElems == 4 && LastLoadedElt == 1) {
8761     SDVTList Tys = DAG.getVTList(MVT::v2i64, MVT::Other);
8762     SDValue Ops[] = { LD->getChain(), LD->getBasePtr() };
8763     SDValue ResNode = DAG.getNode(X86ISD::VZEXT_LOAD, dl, Tys, Ops, 2);
8764     return DAG.getNode(ISD::BIT_CONVERT, dl, VT, ResNode);
8765   }
8766   return SDValue();
8767 }
8768
8769 /// PerformSELECTCombine - Do target-specific dag combines on SELECT nodes.
8770 static SDValue PerformSELECTCombine(SDNode *N, SelectionDAG &DAG,
8771                                     const X86Subtarget *Subtarget) {
8772   DebugLoc DL = N->getDebugLoc();
8773   SDValue Cond = N->getOperand(0);
8774   // Get the LHS/RHS of the select.
8775   SDValue LHS = N->getOperand(1);
8776   SDValue RHS = N->getOperand(2);
8777
8778   // If we have SSE[12] support, try to form min/max nodes. SSE min/max
8779   // instructions have the peculiarity that if either operand is a NaN,
8780   // they chose what we call the RHS operand (and as such are not symmetric).
8781   // It happens that this matches the semantics of the common C idiom
8782   // x<y?x:y and related forms, so we can recognize these cases.
8783   if (Subtarget->hasSSE2() &&
8784       (LHS.getValueType() == MVT::f32 || LHS.getValueType() == MVT::f64) &&
8785       Cond.getOpcode() == ISD::SETCC) {
8786     ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
8787
8788     unsigned Opcode = 0;
8789     // Check for x CC y ? x : y.
8790     if (LHS == Cond.getOperand(0) && RHS == Cond.getOperand(1)) {
8791       switch (CC) {
8792       default: break;
8793       case ISD::SETULT:
8794         // This can be a min if we can prove that at least one of the operands
8795         // is not a nan.
8796         if (!FiniteOnlyFPMath()) {
8797           if (DAG.isKnownNeverNaN(RHS)) {
8798             // Put the potential NaN in the RHS so that SSE will preserve it.
8799             std::swap(LHS, RHS);
8800           } else if (!DAG.isKnownNeverNaN(LHS))
8801             break;
8802         }
8803         Opcode = X86ISD::FMIN;
8804         break;
8805       case ISD::SETOLE:
8806         // This can be a min if we can prove that at least one of the operands
8807         // is not a nan.
8808         if (!FiniteOnlyFPMath()) {
8809           if (DAG.isKnownNeverNaN(LHS)) {
8810             // Put the potential NaN in the RHS so that SSE will preserve it.
8811             std::swap(LHS, RHS);
8812           } else if (!DAG.isKnownNeverNaN(RHS))
8813             break;
8814         }
8815         Opcode = X86ISD::FMIN;
8816         break;
8817       case ISD::SETULE:
8818         // This can be a min, but if either operand is a NaN we need it to
8819         // preserve the original LHS.
8820         std::swap(LHS, RHS);
8821       case ISD::SETOLT:
8822       case ISD::SETLT:
8823       case ISD::SETLE:
8824         Opcode = X86ISD::FMIN;
8825         break;
8826
8827       case ISD::SETOGE:
8828         // This can be a max if we can prove that at least one of the operands
8829         // is not a nan.
8830         if (!FiniteOnlyFPMath()) {
8831           if (DAG.isKnownNeverNaN(LHS)) {
8832             // Put the potential NaN in the RHS so that SSE will preserve it.
8833             std::swap(LHS, RHS);
8834           } else if (!DAG.isKnownNeverNaN(RHS))
8835             break;
8836         }
8837         Opcode = X86ISD::FMAX;
8838         break;
8839       case ISD::SETUGT:
8840         // This can be a max if we can prove that at least one of the operands
8841         // is not a nan.
8842         if (!FiniteOnlyFPMath()) {
8843           if (DAG.isKnownNeverNaN(RHS)) {
8844             // Put the potential NaN in the RHS so that SSE will preserve it.
8845             std::swap(LHS, RHS);
8846           } else if (!DAG.isKnownNeverNaN(LHS))
8847             break;
8848         }
8849         Opcode = X86ISD::FMAX;
8850         break;
8851       case ISD::SETUGE:
8852         // This can be a max, but if either operand is a NaN we need it to
8853         // preserve the original LHS.
8854         std::swap(LHS, RHS);
8855       case ISD::SETOGT:
8856       case ISD::SETGT:
8857       case ISD::SETGE:
8858         Opcode = X86ISD::FMAX;
8859         break;
8860       }
8861     // Check for x CC y ? y : x -- a min/max with reversed arms.
8862     } else if (LHS == Cond.getOperand(1) && RHS == Cond.getOperand(0)) {
8863       switch (CC) {
8864       default: break;
8865       case ISD::SETOGE:
8866         // This can be a min if we can prove that at least one of the operands
8867         // is not a nan.
8868         if (!FiniteOnlyFPMath()) {
8869           if (DAG.isKnownNeverNaN(RHS)) {
8870             // Put the potential NaN in the RHS so that SSE will preserve it.
8871             std::swap(LHS, RHS);
8872           } else if (!DAG.isKnownNeverNaN(LHS))
8873             break;
8874         }
8875         Opcode = X86ISD::FMIN;
8876         break;
8877       case ISD::SETUGT:
8878         // This can be a min if we can prove that at least one of the operands
8879         // is not a nan.
8880         if (!FiniteOnlyFPMath()) {
8881           if (DAG.isKnownNeverNaN(LHS)) {
8882             // Put the potential NaN in the RHS so that SSE will preserve it.
8883             std::swap(LHS, RHS);
8884           } else if (!DAG.isKnownNeverNaN(RHS))
8885             break;
8886         }
8887         Opcode = X86ISD::FMIN;
8888         break;
8889       case ISD::SETUGE:
8890         // This can be a min, but if either operand is a NaN we need it to
8891         // preserve the original LHS.
8892         std::swap(LHS, RHS);
8893       case ISD::SETOGT:
8894       case ISD::SETGT:
8895       case ISD::SETGE:
8896         Opcode = X86ISD::FMIN;
8897         break;
8898
8899       case ISD::SETULT:
8900         // This can be a max if we can prove that at least one of the operands
8901         // is not a nan.
8902         if (!FiniteOnlyFPMath()) {
8903           if (DAG.isKnownNeverNaN(LHS)) {
8904             // Put the potential NaN in the RHS so that SSE will preserve it.
8905             std::swap(LHS, RHS);
8906           } else if (!DAG.isKnownNeverNaN(RHS))
8907             break;
8908         }
8909         Opcode = X86ISD::FMAX;
8910         break;
8911       case ISD::SETOLE:
8912         // This can be a max if we can prove that at least one of the operands
8913         // is not a nan.
8914         if (!FiniteOnlyFPMath()) {
8915           if (DAG.isKnownNeverNaN(RHS)) {
8916             // Put the potential NaN in the RHS so that SSE will preserve it.
8917             std::swap(LHS, RHS);
8918           } else if (!DAG.isKnownNeverNaN(LHS))
8919             break;
8920         }
8921         Opcode = X86ISD::FMAX;
8922         break;
8923       case ISD::SETULE:
8924         // This can be a max, but if either operand is a NaN we need it to
8925         // preserve the original LHS.
8926         std::swap(LHS, RHS);
8927       case ISD::SETOLT:
8928       case ISD::SETLT:
8929       case ISD::SETLE:
8930         Opcode = X86ISD::FMAX;
8931         break;
8932       }
8933     }
8934
8935     if (Opcode)
8936       return DAG.getNode(Opcode, DL, N->getValueType(0), LHS, RHS);
8937   }
8938
8939   // If this is a select between two integer constants, try to do some
8940   // optimizations.
8941   if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(LHS)) {
8942     if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(RHS))
8943       // Don't do this for crazy integer types.
8944       if (DAG.getTargetLoweringInfo().isTypeLegal(LHS.getValueType())) {
8945         // If this is efficiently invertible, canonicalize the LHSC/RHSC values
8946         // so that TrueC (the true value) is larger than FalseC.
8947         bool NeedsCondInvert = false;
8948
8949         if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue()) &&
8950             // Efficiently invertible.
8951             (Cond.getOpcode() == ISD::SETCC ||  // setcc -> invertible.
8952              (Cond.getOpcode() == ISD::XOR &&   // xor(X, C) -> invertible.
8953               isa<ConstantSDNode>(Cond.getOperand(1))))) {
8954           NeedsCondInvert = true;
8955           std::swap(TrueC, FalseC);
8956         }
8957
8958         // Optimize C ? 8 : 0 -> zext(C) << 3.  Likewise for any pow2/0.
8959         if (FalseC->getAPIntValue() == 0 &&
8960             TrueC->getAPIntValue().isPowerOf2()) {
8961           if (NeedsCondInvert) // Invert the condition if needed.
8962             Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
8963                                DAG.getConstant(1, Cond.getValueType()));
8964
8965           // Zero extend the condition if needed.
8966           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, LHS.getValueType(), Cond);
8967
8968           unsigned ShAmt = TrueC->getAPIntValue().logBase2();
8969           return DAG.getNode(ISD::SHL, DL, LHS.getValueType(), Cond,
8970                              DAG.getConstant(ShAmt, MVT::i8));
8971         }
8972
8973         // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.
8974         if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
8975           if (NeedsCondInvert) // Invert the condition if needed.
8976             Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
8977                                DAG.getConstant(1, Cond.getValueType()));
8978
8979           // Zero extend the condition if needed.
8980           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
8981                              FalseC->getValueType(0), Cond);
8982           return DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
8983                              SDValue(FalseC, 0));
8984         }
8985
8986         // Optimize cases that will turn into an LEA instruction.  This requires
8987         // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
8988         if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
8989           uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
8990           if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
8991
8992           bool isFastMultiplier = false;
8993           if (Diff < 10) {
8994             switch ((unsigned char)Diff) {
8995               default: break;
8996               case 1:  // result = add base, cond
8997               case 2:  // result = lea base(    , cond*2)
8998               case 3:  // result = lea base(cond, cond*2)
8999               case 4:  // result = lea base(    , cond*4)
9000               case 5:  // result = lea base(cond, cond*4)
9001               case 8:  // result = lea base(    , cond*8)
9002               case 9:  // result = lea base(cond, cond*8)
9003                 isFastMultiplier = true;
9004                 break;
9005             }
9006           }
9007
9008           if (isFastMultiplier) {
9009             APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
9010             if (NeedsCondInvert) // Invert the condition if needed.
9011               Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
9012                                  DAG.getConstant(1, Cond.getValueType()));
9013
9014             // Zero extend the condition if needed.
9015             Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
9016                                Cond);
9017             // Scale the condition by the difference.
9018             if (Diff != 1)
9019               Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
9020                                  DAG.getConstant(Diff, Cond.getValueType()));
9021
9022             // Add the base if non-zero.
9023             if (FalseC->getAPIntValue() != 0)
9024               Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
9025                                  SDValue(FalseC, 0));
9026             return Cond;
9027           }
9028         }
9029       }
9030   }
9031
9032   return SDValue();
9033 }
9034
9035 /// Optimize X86ISD::CMOV [LHS, RHS, CONDCODE (e.g. X86::COND_NE), CONDVAL]
9036 static SDValue PerformCMOVCombine(SDNode *N, SelectionDAG &DAG,
9037                                   TargetLowering::DAGCombinerInfo &DCI) {
9038   DebugLoc DL = N->getDebugLoc();
9039
9040   // If the flag operand isn't dead, don't touch this CMOV.
9041   if (N->getNumValues() == 2 && !SDValue(N, 1).use_empty())
9042     return SDValue();
9043
9044   // If this is a select between two integer constants, try to do some
9045   // optimizations.  Note that the operands are ordered the opposite of SELECT
9046   // operands.
9047   if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(N->getOperand(1))) {
9048     if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(N->getOperand(0))) {
9049       // Canonicalize the TrueC/FalseC values so that TrueC (the true value) is
9050       // larger than FalseC (the false value).
9051       X86::CondCode CC = (X86::CondCode)N->getConstantOperandVal(2);
9052
9053       if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue())) {
9054         CC = X86::GetOppositeBranchCondition(CC);
9055         std::swap(TrueC, FalseC);
9056       }
9057
9058       // Optimize C ? 8 : 0 -> zext(setcc(C)) << 3.  Likewise for any pow2/0.
9059       // This is efficient for any integer data type (including i8/i16) and
9060       // shift amount.
9061       if (FalseC->getAPIntValue() == 0 && TrueC->getAPIntValue().isPowerOf2()) {
9062         SDValue Cond = N->getOperand(3);
9063         Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
9064                            DAG.getConstant(CC, MVT::i8), Cond);
9065
9066         // Zero extend the condition if needed.
9067         Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, TrueC->getValueType(0), Cond);
9068
9069         unsigned ShAmt = TrueC->getAPIntValue().logBase2();
9070         Cond = DAG.getNode(ISD::SHL, DL, Cond.getValueType(), Cond,
9071                            DAG.getConstant(ShAmt, MVT::i8));
9072         if (N->getNumValues() == 2)  // Dead flag value?
9073           return DCI.CombineTo(N, Cond, SDValue());
9074         return Cond;
9075       }
9076
9077       // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.  This is efficient
9078       // for any integer data type, including i8/i16.
9079       if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
9080         SDValue Cond = N->getOperand(3);
9081         Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
9082                            DAG.getConstant(CC, MVT::i8), Cond);
9083
9084         // Zero extend the condition if needed.
9085         Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
9086                            FalseC->getValueType(0), Cond);
9087         Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
9088                            SDValue(FalseC, 0));
9089
9090         if (N->getNumValues() == 2)  // Dead flag value?
9091           return DCI.CombineTo(N, Cond, SDValue());
9092         return Cond;
9093       }
9094
9095       // Optimize cases that will turn into an LEA instruction.  This requires
9096       // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
9097       if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
9098         uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
9099         if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
9100
9101         bool isFastMultiplier = false;
9102         if (Diff < 10) {
9103           switch ((unsigned char)Diff) {
9104           default: break;
9105           case 1:  // result = add base, cond
9106           case 2:  // result = lea base(    , cond*2)
9107           case 3:  // result = lea base(cond, cond*2)
9108           case 4:  // result = lea base(    , cond*4)
9109           case 5:  // result = lea base(cond, cond*4)
9110           case 8:  // result = lea base(    , cond*8)
9111           case 9:  // result = lea base(cond, cond*8)
9112             isFastMultiplier = true;
9113             break;
9114           }
9115         }
9116
9117         if (isFastMultiplier) {
9118           APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
9119           SDValue Cond = N->getOperand(3);
9120           Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
9121                              DAG.getConstant(CC, MVT::i8), Cond);
9122           // Zero extend the condition if needed.
9123           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
9124                              Cond);
9125           // Scale the condition by the difference.
9126           if (Diff != 1)
9127             Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
9128                                DAG.getConstant(Diff, Cond.getValueType()));
9129
9130           // Add the base if non-zero.
9131           if (FalseC->getAPIntValue() != 0)
9132             Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
9133                                SDValue(FalseC, 0));
9134           if (N->getNumValues() == 2)  // Dead flag value?
9135             return DCI.CombineTo(N, Cond, SDValue());
9136           return Cond;
9137         }
9138       }
9139     }
9140   }
9141   return SDValue();
9142 }
9143
9144
9145 /// PerformMulCombine - Optimize a single multiply with constant into two
9146 /// in order to implement it with two cheaper instructions, e.g.
9147 /// LEA + SHL, LEA + LEA.
9148 static SDValue PerformMulCombine(SDNode *N, SelectionDAG &DAG,
9149                                  TargetLowering::DAGCombinerInfo &DCI) {
9150   if (DAG.getMachineFunction().
9151       getFunction()->hasFnAttr(Attribute::OptimizeForSize))
9152     return SDValue();
9153
9154   if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
9155     return SDValue();
9156
9157   EVT VT = N->getValueType(0);
9158   if (VT != MVT::i64)
9159     return SDValue();
9160
9161   ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
9162   if (!C)
9163     return SDValue();
9164   uint64_t MulAmt = C->getZExtValue();
9165   if (isPowerOf2_64(MulAmt) || MulAmt == 3 || MulAmt == 5 || MulAmt == 9)
9166     return SDValue();
9167
9168   uint64_t MulAmt1 = 0;
9169   uint64_t MulAmt2 = 0;
9170   if ((MulAmt % 9) == 0) {
9171     MulAmt1 = 9;
9172     MulAmt2 = MulAmt / 9;
9173   } else if ((MulAmt % 5) == 0) {
9174     MulAmt1 = 5;
9175     MulAmt2 = MulAmt / 5;
9176   } else if ((MulAmt % 3) == 0) {
9177     MulAmt1 = 3;
9178     MulAmt2 = MulAmt / 3;
9179   }
9180   if (MulAmt2 &&
9181       (isPowerOf2_64(MulAmt2) || MulAmt2 == 3 || MulAmt2 == 5 || MulAmt2 == 9)){
9182     DebugLoc DL = N->getDebugLoc();
9183
9184     if (isPowerOf2_64(MulAmt2) &&
9185         !(N->hasOneUse() && N->use_begin()->getOpcode() == ISD::ADD))
9186       // If second multiplifer is pow2, issue it first. We want the multiply by
9187       // 3, 5, or 9 to be folded into the addressing mode unless the lone use
9188       // is an add.
9189       std::swap(MulAmt1, MulAmt2);
9190
9191     SDValue NewMul;
9192     if (isPowerOf2_64(MulAmt1))
9193       NewMul = DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
9194                            DAG.getConstant(Log2_64(MulAmt1), MVT::i8));
9195     else
9196       NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, N->getOperand(0),
9197                            DAG.getConstant(MulAmt1, VT));
9198
9199     if (isPowerOf2_64(MulAmt2))
9200       NewMul = DAG.getNode(ISD::SHL, DL, VT, NewMul,
9201                            DAG.getConstant(Log2_64(MulAmt2), MVT::i8));
9202     else
9203       NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, NewMul,
9204                            DAG.getConstant(MulAmt2, VT));
9205
9206     // Do not add new nodes to DAG combiner worklist.
9207     DCI.CombineTo(N, NewMul, false);
9208   }
9209   return SDValue();
9210 }
9211
9212 static SDValue PerformSHLCombine(SDNode *N, SelectionDAG &DAG) {
9213   SDValue N0 = N->getOperand(0);
9214   SDValue N1 = N->getOperand(1);
9215   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
9216   EVT VT = N0.getValueType();
9217
9218   // fold (shl (and (setcc_c), c1), c2) -> (and setcc_c, (c1 << c2))
9219   // since the result of setcc_c is all zero's or all ones.
9220   if (N1C && N0.getOpcode() == ISD::AND &&
9221       N0.getOperand(1).getOpcode() == ISD::Constant) {
9222     SDValue N00 = N0.getOperand(0);
9223     if (N00.getOpcode() == X86ISD::SETCC_CARRY ||
9224         ((N00.getOpcode() == ISD::ANY_EXTEND ||
9225           N00.getOpcode() == ISD::ZERO_EXTEND) &&
9226          N00.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY)) {
9227       APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
9228       APInt ShAmt = N1C->getAPIntValue();
9229       Mask = Mask.shl(ShAmt);
9230       if (Mask != 0)
9231         return DAG.getNode(ISD::AND, N->getDebugLoc(), VT,
9232                            N00, DAG.getConstant(Mask, VT));
9233     }
9234   }
9235
9236   return SDValue();
9237 }
9238
9239 /// PerformShiftCombine - Transforms vector shift nodes to use vector shifts
9240 ///                       when possible.
9241 static SDValue PerformShiftCombine(SDNode* N, SelectionDAG &DAG,
9242                                    const X86Subtarget *Subtarget) {
9243   EVT VT = N->getValueType(0);
9244   if (!VT.isVector() && VT.isInteger() &&
9245       N->getOpcode() == ISD::SHL)
9246     return PerformSHLCombine(N, DAG);
9247
9248   // On X86 with SSE2 support, we can transform this to a vector shift if
9249   // all elements are shifted by the same amount.  We can't do this in legalize
9250   // because the a constant vector is typically transformed to a constant pool
9251   // so we have no knowledge of the shift amount.
9252   if (!Subtarget->hasSSE2())
9253     return SDValue();
9254
9255   if (VT != MVT::v2i64 && VT != MVT::v4i32 && VT != MVT::v8i16)
9256     return SDValue();
9257
9258   SDValue ShAmtOp = N->getOperand(1);
9259   EVT EltVT = VT.getVectorElementType();
9260   DebugLoc DL = N->getDebugLoc();
9261   SDValue BaseShAmt = SDValue();
9262   if (ShAmtOp.getOpcode() == ISD::BUILD_VECTOR) {
9263     unsigned NumElts = VT.getVectorNumElements();
9264     unsigned i = 0;
9265     for (; i != NumElts; ++i) {
9266       SDValue Arg = ShAmtOp.getOperand(i);
9267       if (Arg.getOpcode() == ISD::UNDEF) continue;
9268       BaseShAmt = Arg;
9269       break;
9270     }
9271     for (; i != NumElts; ++i) {
9272       SDValue Arg = ShAmtOp.getOperand(i);
9273       if (Arg.getOpcode() == ISD::UNDEF) continue;
9274       if (Arg != BaseShAmt) {
9275         return SDValue();
9276       }
9277     }
9278   } else if (ShAmtOp.getOpcode() == ISD::VECTOR_SHUFFLE &&
9279              cast<ShuffleVectorSDNode>(ShAmtOp)->isSplat()) {
9280     SDValue InVec = ShAmtOp.getOperand(0);
9281     if (InVec.getOpcode() == ISD::BUILD_VECTOR) {
9282       unsigned NumElts = InVec.getValueType().getVectorNumElements();
9283       unsigned i = 0;
9284       for (; i != NumElts; ++i) {
9285         SDValue Arg = InVec.getOperand(i);
9286         if (Arg.getOpcode() == ISD::UNDEF) continue;
9287         BaseShAmt = Arg;
9288         break;
9289       }
9290     } else if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT) {
9291        if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(InVec.getOperand(2))) {
9292          unsigned SplatIdx = cast<ShuffleVectorSDNode>(ShAmtOp)->getSplatIndex();
9293          if (C->getZExtValue() == SplatIdx)
9294            BaseShAmt = InVec.getOperand(1);
9295        }
9296     }
9297     if (BaseShAmt.getNode() == 0)
9298       BaseShAmt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, EltVT, ShAmtOp,
9299                               DAG.getIntPtrConstant(0));
9300   } else
9301     return SDValue();
9302
9303   // The shift amount is an i32.
9304   if (EltVT.bitsGT(MVT::i32))
9305     BaseShAmt = DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, BaseShAmt);
9306   else if (EltVT.bitsLT(MVT::i32))
9307     BaseShAmt = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, BaseShAmt);
9308
9309   // The shift amount is identical so we can do a vector shift.
9310   SDValue  ValOp = N->getOperand(0);
9311   switch (N->getOpcode()) {
9312   default:
9313     llvm_unreachable("Unknown shift opcode!");
9314     break;
9315   case ISD::SHL:
9316     if (VT == MVT::v2i64)
9317       return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
9318                          DAG.getConstant(Intrinsic::x86_sse2_pslli_q, MVT::i32),
9319                          ValOp, BaseShAmt);
9320     if (VT == MVT::v4i32)
9321       return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
9322                          DAG.getConstant(Intrinsic::x86_sse2_pslli_d, MVT::i32),
9323                          ValOp, BaseShAmt);
9324     if (VT == MVT::v8i16)
9325       return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
9326                          DAG.getConstant(Intrinsic::x86_sse2_pslli_w, MVT::i32),
9327                          ValOp, BaseShAmt);
9328     break;
9329   case ISD::SRA:
9330     if (VT == MVT::v4i32)
9331       return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
9332                          DAG.getConstant(Intrinsic::x86_sse2_psrai_d, MVT::i32),
9333                          ValOp, BaseShAmt);
9334     if (VT == MVT::v8i16)
9335       return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
9336                          DAG.getConstant(Intrinsic::x86_sse2_psrai_w, MVT::i32),
9337                          ValOp, BaseShAmt);
9338     break;
9339   case ISD::SRL:
9340     if (VT == MVT::v2i64)
9341       return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
9342                          DAG.getConstant(Intrinsic::x86_sse2_psrli_q, MVT::i32),
9343                          ValOp, BaseShAmt);
9344     if (VT == MVT::v4i32)
9345       return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
9346                          DAG.getConstant(Intrinsic::x86_sse2_psrli_d, MVT::i32),
9347                          ValOp, BaseShAmt);
9348     if (VT ==  MVT::v8i16)
9349       return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
9350                          DAG.getConstant(Intrinsic::x86_sse2_psrli_w, MVT::i32),
9351                          ValOp, BaseShAmt);
9352     break;
9353   }
9354   return SDValue();
9355 }
9356
9357 static SDValue PerformOrCombine(SDNode *N, SelectionDAG &DAG,
9358                                 const X86Subtarget *Subtarget) {
9359   EVT VT = N->getValueType(0);
9360   if (VT != MVT::i64 || !Subtarget->is64Bit())
9361     return SDValue();
9362
9363   // fold (or (x << c) | (y >> (64 - c))) ==> (shld64 x, y, c)
9364   SDValue N0 = N->getOperand(0);
9365   SDValue N1 = N->getOperand(1);
9366   if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL)
9367     std::swap(N0, N1);
9368   if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL)
9369     return SDValue();
9370
9371   SDValue ShAmt0 = N0.getOperand(1);
9372   if (ShAmt0.getValueType() != MVT::i8)
9373     return SDValue();
9374   SDValue ShAmt1 = N1.getOperand(1);
9375   if (ShAmt1.getValueType() != MVT::i8)
9376     return SDValue();
9377   if (ShAmt0.getOpcode() == ISD::TRUNCATE)
9378     ShAmt0 = ShAmt0.getOperand(0);
9379   if (ShAmt1.getOpcode() == ISD::TRUNCATE)
9380     ShAmt1 = ShAmt1.getOperand(0);
9381
9382   DebugLoc DL = N->getDebugLoc();
9383   unsigned Opc = X86ISD::SHLD;
9384   SDValue Op0 = N0.getOperand(0);
9385   SDValue Op1 = N1.getOperand(0);
9386   if (ShAmt0.getOpcode() == ISD::SUB) {
9387     Opc = X86ISD::SHRD;
9388     std::swap(Op0, Op1);
9389     std::swap(ShAmt0, ShAmt1);
9390   }
9391
9392   if (ShAmt1.getOpcode() == ISD::SUB) {
9393     SDValue Sum = ShAmt1.getOperand(0);
9394     if (ConstantSDNode *SumC = dyn_cast<ConstantSDNode>(Sum)) {
9395       if (SumC->getSExtValue() == 64 &&
9396           ShAmt1.getOperand(1) == ShAmt0)
9397         return DAG.getNode(Opc, DL, VT,
9398                            Op0, Op1,
9399                            DAG.getNode(ISD::TRUNCATE, DL,
9400                                        MVT::i8, ShAmt0));
9401     }
9402   } else if (ConstantSDNode *ShAmt1C = dyn_cast<ConstantSDNode>(ShAmt1)) {
9403     ConstantSDNode *ShAmt0C = dyn_cast<ConstantSDNode>(ShAmt0);
9404     if (ShAmt0C &&
9405         ShAmt0C->getSExtValue() + ShAmt1C->getSExtValue() == 64)
9406       return DAG.getNode(Opc, DL, VT,
9407                          N0.getOperand(0), N1.getOperand(0),
9408                          DAG.getNode(ISD::TRUNCATE, DL,
9409                                        MVT::i8, ShAmt0));
9410   }
9411
9412   return SDValue();
9413 }
9414
9415 /// PerformSTORECombine - Do target-specific dag combines on STORE nodes.
9416 static SDValue PerformSTORECombine(SDNode *N, SelectionDAG &DAG,
9417                                    const X86Subtarget *Subtarget) {
9418   // Turn load->store of MMX types into GPR load/stores.  This avoids clobbering
9419   // the FP state in cases where an emms may be missing.
9420   // A preferable solution to the general problem is to figure out the right
9421   // places to insert EMMS.  This qualifies as a quick hack.
9422
9423   // Similarly, turn load->store of i64 into double load/stores in 32-bit mode.
9424   StoreSDNode *St = cast<StoreSDNode>(N);
9425   EVT VT = St->getValue().getValueType();
9426   if (VT.getSizeInBits() != 64)
9427     return SDValue();
9428
9429   const Function *F = DAG.getMachineFunction().getFunction();
9430   bool NoImplicitFloatOps = F->hasFnAttr(Attribute::NoImplicitFloat);
9431   bool F64IsLegal = !UseSoftFloat && !NoImplicitFloatOps
9432     && Subtarget->hasSSE2();
9433   if ((VT.isVector() ||
9434        (VT == MVT::i64 && F64IsLegal && !Subtarget->is64Bit())) &&
9435       isa<LoadSDNode>(St->getValue()) &&
9436       !cast<LoadSDNode>(St->getValue())->isVolatile() &&
9437       St->getChain().hasOneUse() && !St->isVolatile()) {
9438     SDNode* LdVal = St->getValue().getNode();
9439     LoadSDNode *Ld = 0;
9440     int TokenFactorIndex = -1;
9441     SmallVector<SDValue, 8> Ops;
9442     SDNode* ChainVal = St->getChain().getNode();
9443     // Must be a store of a load.  We currently handle two cases:  the load
9444     // is a direct child, and it's under an intervening TokenFactor.  It is
9445     // possible to dig deeper under nested TokenFactors.
9446     if (ChainVal == LdVal)
9447       Ld = cast<LoadSDNode>(St->getChain());
9448     else if (St->getValue().hasOneUse() &&
9449              ChainVal->getOpcode() == ISD::TokenFactor) {
9450       for (unsigned i=0, e = ChainVal->getNumOperands(); i != e; ++i) {
9451         if (ChainVal->getOperand(i).getNode() == LdVal) {
9452           TokenFactorIndex = i;
9453           Ld = cast<LoadSDNode>(St->getValue());
9454         } else
9455           Ops.push_back(ChainVal->getOperand(i));
9456       }
9457     }
9458
9459     if (!Ld || !ISD::isNormalLoad(Ld))
9460       return SDValue();
9461
9462     // If this is not the MMX case, i.e. we are just turning i64 load/store
9463     // into f64 load/store, avoid the transformation if there are multiple
9464     // uses of the loaded value.
9465     if (!VT.isVector() && !Ld->hasNUsesOfValue(1, 0))
9466       return SDValue();
9467
9468     DebugLoc LdDL = Ld->getDebugLoc();
9469     DebugLoc StDL = N->getDebugLoc();
9470     // If we are a 64-bit capable x86, lower to a single movq load/store pair.
9471     // Otherwise, if it's legal to use f64 SSE instructions, use f64 load/store
9472     // pair instead.
9473     if (Subtarget->is64Bit() || F64IsLegal) {
9474       EVT LdVT = Subtarget->is64Bit() ? MVT::i64 : MVT::f64;
9475       SDValue NewLd = DAG.getLoad(LdVT, LdDL, Ld->getChain(),
9476                                   Ld->getBasePtr(), Ld->getSrcValue(),
9477                                   Ld->getSrcValueOffset(), Ld->isVolatile(),
9478                                   Ld->getAlignment());
9479       SDValue NewChain = NewLd.getValue(1);
9480       if (TokenFactorIndex != -1) {
9481         Ops.push_back(NewChain);
9482         NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, &Ops[0],
9483                                Ops.size());
9484       }
9485       return DAG.getStore(NewChain, StDL, NewLd, St->getBasePtr(),
9486                           St->getSrcValue(), St->getSrcValueOffset(),
9487                           St->isVolatile(), St->getAlignment());
9488     }
9489
9490     // Otherwise, lower to two pairs of 32-bit loads / stores.
9491     SDValue LoAddr = Ld->getBasePtr();
9492     SDValue HiAddr = DAG.getNode(ISD::ADD, LdDL, MVT::i32, LoAddr,
9493                                  DAG.getConstant(4, MVT::i32));
9494
9495     SDValue LoLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), LoAddr,
9496                                Ld->getSrcValue(), Ld->getSrcValueOffset(),
9497                                Ld->isVolatile(), Ld->getAlignment());
9498     SDValue HiLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), HiAddr,
9499                                Ld->getSrcValue(), Ld->getSrcValueOffset()+4,
9500                                Ld->isVolatile(),
9501                                MinAlign(Ld->getAlignment(), 4));
9502
9503     SDValue NewChain = LoLd.getValue(1);
9504     if (TokenFactorIndex != -1) {
9505       Ops.push_back(LoLd);
9506       Ops.push_back(HiLd);
9507       NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, &Ops[0],
9508                              Ops.size());
9509     }
9510
9511     LoAddr = St->getBasePtr();
9512     HiAddr = DAG.getNode(ISD::ADD, StDL, MVT::i32, LoAddr,
9513                          DAG.getConstant(4, MVT::i32));
9514
9515     SDValue LoSt = DAG.getStore(NewChain, StDL, LoLd, LoAddr,
9516                                 St->getSrcValue(), St->getSrcValueOffset(),
9517                                 St->isVolatile(), St->getAlignment());
9518     SDValue HiSt = DAG.getStore(NewChain, StDL, HiLd, HiAddr,
9519                                 St->getSrcValue(),
9520                                 St->getSrcValueOffset() + 4,
9521                                 St->isVolatile(),
9522                                 MinAlign(St->getAlignment(), 4));
9523     return DAG.getNode(ISD::TokenFactor, StDL, MVT::Other, LoSt, HiSt);
9524   }
9525   return SDValue();
9526 }
9527
9528 /// PerformFORCombine - Do target-specific dag combines on X86ISD::FOR and
9529 /// X86ISD::FXOR nodes.
9530 static SDValue PerformFORCombine(SDNode *N, SelectionDAG &DAG) {
9531   assert(N->getOpcode() == X86ISD::FOR || N->getOpcode() == X86ISD::FXOR);
9532   // F[X]OR(0.0, x) -> x
9533   // F[X]OR(x, 0.0) -> x
9534   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
9535     if (C->getValueAPF().isPosZero())
9536       return N->getOperand(1);
9537   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
9538     if (C->getValueAPF().isPosZero())
9539       return N->getOperand(0);
9540   return SDValue();
9541 }
9542
9543 /// PerformFANDCombine - Do target-specific dag combines on X86ISD::FAND nodes.
9544 static SDValue PerformFANDCombine(SDNode *N, SelectionDAG &DAG) {
9545   // FAND(0.0, x) -> 0.0
9546   // FAND(x, 0.0) -> 0.0
9547   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
9548     if (C->getValueAPF().isPosZero())
9549       return N->getOperand(0);
9550   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
9551     if (C->getValueAPF().isPosZero())
9552       return N->getOperand(1);
9553   return SDValue();
9554 }
9555
9556 static SDValue PerformBTCombine(SDNode *N,
9557                                 SelectionDAG &DAG,
9558                                 TargetLowering::DAGCombinerInfo &DCI) {
9559   // BT ignores high bits in the bit index operand.
9560   SDValue Op1 = N->getOperand(1);
9561   if (Op1.hasOneUse()) {
9562     unsigned BitWidth = Op1.getValueSizeInBits();
9563     APInt DemandedMask = APInt::getLowBitsSet(BitWidth, Log2_32(BitWidth));
9564     APInt KnownZero, KnownOne;
9565     TargetLowering::TargetLoweringOpt TLO(DAG);
9566     TargetLowering &TLI = DAG.getTargetLoweringInfo();
9567     if (TLO.ShrinkDemandedConstant(Op1, DemandedMask) ||
9568         TLI.SimplifyDemandedBits(Op1, DemandedMask, KnownZero, KnownOne, TLO))
9569       DCI.CommitTargetLoweringOpt(TLO);
9570   }
9571   return SDValue();
9572 }
9573
9574 static SDValue PerformVZEXT_MOVLCombine(SDNode *N, SelectionDAG &DAG) {
9575   SDValue Op = N->getOperand(0);
9576   if (Op.getOpcode() == ISD::BIT_CONVERT)
9577     Op = Op.getOperand(0);
9578   EVT VT = N->getValueType(0), OpVT = Op.getValueType();
9579   if (Op.getOpcode() == X86ISD::VZEXT_LOAD &&
9580       VT.getVectorElementType().getSizeInBits() ==
9581       OpVT.getVectorElementType().getSizeInBits()) {
9582     return DAG.getNode(ISD::BIT_CONVERT, N->getDebugLoc(), VT, Op);
9583   }
9584   return SDValue();
9585 }
9586
9587 // On X86 and X86-64, atomic operations are lowered to locked instructions.
9588 // Locked instructions, in turn, have implicit fence semantics (all memory
9589 // operations are flushed before issuing the locked instruction, and the
9590 // are not buffered), so we can fold away the common pattern of
9591 // fence-atomic-fence.
9592 static SDValue PerformMEMBARRIERCombine(SDNode* N, SelectionDAG &DAG) {
9593   SDValue atomic = N->getOperand(0);
9594   switch (atomic.getOpcode()) {
9595     case ISD::ATOMIC_CMP_SWAP:
9596     case ISD::ATOMIC_SWAP:
9597     case ISD::ATOMIC_LOAD_ADD:
9598     case ISD::ATOMIC_LOAD_SUB:
9599     case ISD::ATOMIC_LOAD_AND:
9600     case ISD::ATOMIC_LOAD_OR:
9601     case ISD::ATOMIC_LOAD_XOR:
9602     case ISD::ATOMIC_LOAD_NAND:
9603     case ISD::ATOMIC_LOAD_MIN:
9604     case ISD::ATOMIC_LOAD_MAX:
9605     case ISD::ATOMIC_LOAD_UMIN:
9606     case ISD::ATOMIC_LOAD_UMAX:
9607       break;
9608     default:
9609       return SDValue();
9610   }
9611
9612   SDValue fence = atomic.getOperand(0);
9613   if (fence.getOpcode() != ISD::MEMBARRIER)
9614     return SDValue();
9615
9616   switch (atomic.getOpcode()) {
9617     case ISD::ATOMIC_CMP_SWAP:
9618       return DAG.UpdateNodeOperands(atomic, fence.getOperand(0),
9619                                     atomic.getOperand(1), atomic.getOperand(2),
9620                                     atomic.getOperand(3));
9621     case ISD::ATOMIC_SWAP:
9622     case ISD::ATOMIC_LOAD_ADD:
9623     case ISD::ATOMIC_LOAD_SUB:
9624     case ISD::ATOMIC_LOAD_AND:
9625     case ISD::ATOMIC_LOAD_OR:
9626     case ISD::ATOMIC_LOAD_XOR:
9627     case ISD::ATOMIC_LOAD_NAND:
9628     case ISD::ATOMIC_LOAD_MIN:
9629     case ISD::ATOMIC_LOAD_MAX:
9630     case ISD::ATOMIC_LOAD_UMIN:
9631     case ISD::ATOMIC_LOAD_UMAX:
9632       return DAG.UpdateNodeOperands(atomic, fence.getOperand(0),
9633                                     atomic.getOperand(1), atomic.getOperand(2));
9634     default:
9635       return SDValue();
9636   }
9637 }
9638
9639 static SDValue PerformZExtCombine(SDNode *N, SelectionDAG &DAG) {
9640   // (i32 zext (and (i8  x86isd::setcc_carry), 1)) ->
9641   //           (and (i32 x86isd::setcc_carry), 1)
9642   // This eliminates the zext. This transformation is necessary because
9643   // ISD::SETCC is always legalized to i8.
9644   DebugLoc dl = N->getDebugLoc();
9645   SDValue N0 = N->getOperand(0);
9646   EVT VT = N->getValueType(0);
9647   if (N0.getOpcode() == ISD::AND &&
9648       N0.hasOneUse() &&
9649       N0.getOperand(0).hasOneUse()) {
9650     SDValue N00 = N0.getOperand(0);
9651     if (N00.getOpcode() != X86ISD::SETCC_CARRY)
9652       return SDValue();
9653     ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
9654     if (!C || C->getZExtValue() != 1)
9655       return SDValue();
9656     return DAG.getNode(ISD::AND, dl, VT,
9657                        DAG.getNode(X86ISD::SETCC_CARRY, dl, VT,
9658                                    N00.getOperand(0), N00.getOperand(1)),
9659                        DAG.getConstant(1, VT));
9660   }
9661
9662   return SDValue();
9663 }
9664
9665 SDValue X86TargetLowering::PerformDAGCombine(SDNode *N,
9666                                              DAGCombinerInfo &DCI) const {
9667   SelectionDAG &DAG = DCI.DAG;
9668   switch (N->getOpcode()) {
9669   default: break;
9670   case ISD::VECTOR_SHUFFLE: return PerformShuffleCombine(N, DAG, *this);
9671   case ISD::SELECT:         return PerformSELECTCombine(N, DAG, Subtarget);
9672   case X86ISD::CMOV:        return PerformCMOVCombine(N, DAG, DCI);
9673   case ISD::MUL:            return PerformMulCombine(N, DAG, DCI);
9674   case ISD::SHL:
9675   case ISD::SRA:
9676   case ISD::SRL:            return PerformShiftCombine(N, DAG, Subtarget);
9677   case ISD::OR:             return PerformOrCombine(N, DAG, Subtarget);
9678   case ISD::STORE:          return PerformSTORECombine(N, DAG, Subtarget);
9679   case X86ISD::FXOR:
9680   case X86ISD::FOR:         return PerformFORCombine(N, DAG);
9681   case X86ISD::FAND:        return PerformFANDCombine(N, DAG);
9682   case X86ISD::BT:          return PerformBTCombine(N, DAG, DCI);
9683   case X86ISD::VZEXT_MOVL:  return PerformVZEXT_MOVLCombine(N, DAG);
9684   case ISD::MEMBARRIER:     return PerformMEMBARRIERCombine(N, DAG);
9685   case ISD::ZERO_EXTEND:    return PerformZExtCombine(N, DAG);
9686   }
9687
9688   return SDValue();
9689 }
9690
9691 //===----------------------------------------------------------------------===//
9692 //                           X86 Inline Assembly Support
9693 //===----------------------------------------------------------------------===//
9694
9695 static bool LowerToBSwap(CallInst *CI) {
9696   // FIXME: this should verify that we are targetting a 486 or better.  If not,
9697   // we will turn this bswap into something that will be lowered to logical ops
9698   // instead of emitting the bswap asm.  For now, we don't support 486 or lower
9699   // so don't worry about this.
9700
9701   // Verify this is a simple bswap.
9702   if (CI->getNumOperands() != 2 ||
9703       CI->getType() != CI->getOperand(1)->getType() ||
9704       !CI->getType()->isInteger())
9705     return false;
9706
9707   const IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
9708   if (!Ty || Ty->getBitWidth() % 16 != 0)
9709     return false;
9710
9711   // Okay, we can do this xform, do so now.
9712   const Type *Tys[] = { Ty };
9713   Module *M = CI->getParent()->getParent()->getParent();
9714   Constant *Int = Intrinsic::getDeclaration(M, Intrinsic::bswap, Tys, 1);
9715
9716   Value *Op = CI->getOperand(1);
9717   Op = CallInst::Create(Int, Op, CI->getName(), CI);
9718
9719   CI->replaceAllUsesWith(Op);
9720   CI->eraseFromParent();
9721   return true;
9722 }
9723
9724 bool X86TargetLowering::ExpandInlineAsm(CallInst *CI) const {
9725   InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue());
9726   std::vector<InlineAsm::ConstraintInfo> Constraints = IA->ParseConstraints();
9727
9728   std::string AsmStr = IA->getAsmString();
9729
9730   // TODO: should remove alternatives from the asmstring: "foo {a|b}" -> "foo a"
9731   SmallVector<StringRef, 4> AsmPieces;
9732   SplitString(AsmStr, AsmPieces, "\n");  // ; as separator?
9733
9734   switch (AsmPieces.size()) {
9735   default: return false;
9736   case 1:
9737     AsmStr = AsmPieces[0];
9738     AsmPieces.clear();
9739     SplitString(AsmStr, AsmPieces, " \t");  // Split with whitespace.
9740
9741     // bswap $0
9742     if (AsmPieces.size() == 2 &&
9743         (AsmPieces[0] == "bswap" ||
9744          AsmPieces[0] == "bswapq" ||
9745          AsmPieces[0] == "bswapl") &&
9746         (AsmPieces[1] == "$0" ||
9747          AsmPieces[1] == "${0:q}")) {
9748       // No need to check constraints, nothing other than the equivalent of
9749       // "=r,0" would be valid here.
9750       return LowerToBSwap(CI);
9751     }
9752     // rorw $$8, ${0:w}  -->  llvm.bswap.i16
9753     if (CI->getType()->isInteger(16) &&
9754         AsmPieces.size() == 3 &&
9755         AsmPieces[0] == "rorw" &&
9756         AsmPieces[1] == "$$8," &&
9757         AsmPieces[2] == "${0:w}" &&
9758         IA->getConstraintString() == "=r,0,~{dirflag},~{fpsr},~{flags},~{cc}") {
9759       return LowerToBSwap(CI);
9760     }
9761     break;
9762   case 3:
9763     if (CI->getType()->isInteger(64) &&
9764         Constraints.size() >= 2 &&
9765         Constraints[0].Codes.size() == 1 && Constraints[0].Codes[0] == "A" &&
9766         Constraints[1].Codes.size() == 1 && Constraints[1].Codes[0] == "0") {
9767       // bswap %eax / bswap %edx / xchgl %eax, %edx  -> llvm.bswap.i64
9768       SmallVector<StringRef, 4> Words;
9769       SplitString(AsmPieces[0], Words, " \t");
9770       if (Words.size() == 2 && Words[0] == "bswap" && Words[1] == "%eax") {
9771         Words.clear();
9772         SplitString(AsmPieces[1], Words, " \t");
9773         if (Words.size() == 2 && Words[0] == "bswap" && Words[1] == "%edx") {
9774           Words.clear();
9775           SplitString(AsmPieces[2], Words, " \t,");
9776           if (Words.size() == 3 && Words[0] == "xchgl" && Words[1] == "%eax" &&
9777               Words[2] == "%edx") {
9778             return LowerToBSwap(CI);
9779           }
9780         }
9781       }
9782     }
9783     break;
9784   }
9785   return false;
9786 }
9787
9788
9789
9790 /// getConstraintType - Given a constraint letter, return the type of
9791 /// constraint it is for this target.
9792 X86TargetLowering::ConstraintType
9793 X86TargetLowering::getConstraintType(const std::string &Constraint) const {
9794   if (Constraint.size() == 1) {
9795     switch (Constraint[0]) {
9796     case 'A':
9797       return C_Register;
9798     case 'f':
9799     case 'r':
9800     case 'R':
9801     case 'l':
9802     case 'q':
9803     case 'Q':
9804     case 'x':
9805     case 'y':
9806     case 'Y':
9807       return C_RegisterClass;
9808     case 'e':
9809     case 'Z':
9810       return C_Other;
9811     default:
9812       break;
9813     }
9814   }
9815   return TargetLowering::getConstraintType(Constraint);
9816 }
9817
9818 /// LowerXConstraint - try to replace an X constraint, which matches anything,
9819 /// with another that has more specific requirements based on the type of the
9820 /// corresponding operand.
9821 const char *X86TargetLowering::
9822 LowerXConstraint(EVT ConstraintVT) const {
9823   // FP X constraints get lowered to SSE1/2 registers if available, otherwise
9824   // 'f' like normal targets.
9825   if (ConstraintVT.isFloatingPoint()) {
9826     if (Subtarget->hasSSE2())
9827       return "Y";
9828     if (Subtarget->hasSSE1())
9829       return "x";
9830   }
9831
9832   return TargetLowering::LowerXConstraint(ConstraintVT);
9833 }
9834
9835 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
9836 /// vector.  If it is invalid, don't add anything to Ops.
9837 void X86TargetLowering::LowerAsmOperandForConstraint(SDValue Op,
9838                                                      char Constraint,
9839                                                      bool hasMemory,
9840                                                      std::vector<SDValue>&Ops,
9841                                                      SelectionDAG &DAG) const {
9842   SDValue Result(0, 0);
9843
9844   switch (Constraint) {
9845   default: break;
9846   case 'I':
9847     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
9848       if (C->getZExtValue() <= 31) {
9849         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
9850         break;
9851       }
9852     }
9853     return;
9854   case 'J':
9855     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
9856       if (C->getZExtValue() <= 63) {
9857         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
9858         break;
9859       }
9860     }
9861     return;
9862   case 'K':
9863     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
9864       if ((int8_t)C->getSExtValue() == C->getSExtValue()) {
9865         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
9866         break;
9867       }
9868     }
9869     return;
9870   case 'N':
9871     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
9872       if (C->getZExtValue() <= 255) {
9873         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
9874         break;
9875       }
9876     }
9877     return;
9878   case 'e': {
9879     // 32-bit signed value
9880     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
9881       const ConstantInt *CI = C->getConstantIntValue();
9882       if (CI->isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
9883                                   C->getSExtValue())) {
9884         // Widen to 64 bits here to get it sign extended.
9885         Result = DAG.getTargetConstant(C->getSExtValue(), MVT::i64);
9886         break;
9887       }
9888     // FIXME gcc accepts some relocatable values here too, but only in certain
9889     // memory models; it's complicated.
9890     }
9891     return;
9892   }
9893   case 'Z': {
9894     // 32-bit unsigned value
9895     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
9896       const ConstantInt *CI = C->getConstantIntValue();
9897       if (CI->isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
9898                                   C->getZExtValue())) {
9899         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
9900         break;
9901       }
9902     }
9903     // FIXME gcc accepts some relocatable values here too, but only in certain
9904     // memory models; it's complicated.
9905     return;
9906   }
9907   case 'i': {
9908     // Literal immediates are always ok.
9909     if (ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op)) {
9910       // Widen to 64 bits here to get it sign extended.
9911       Result = DAG.getTargetConstant(CST->getSExtValue(), MVT::i64);
9912       break;
9913     }
9914
9915     // If we are in non-pic codegen mode, we allow the address of a global (with
9916     // an optional displacement) to be used with 'i'.
9917     GlobalAddressSDNode *GA = 0;
9918     int64_t Offset = 0;
9919
9920     // Match either (GA), (GA+C), (GA+C1+C2), etc.
9921     while (1) {
9922       if ((GA = dyn_cast<GlobalAddressSDNode>(Op))) {
9923         Offset += GA->getOffset();
9924         break;
9925       } else if (Op.getOpcode() == ISD::ADD) {
9926         if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
9927           Offset += C->getZExtValue();
9928           Op = Op.getOperand(0);
9929           continue;
9930         }
9931       } else if (Op.getOpcode() == ISD::SUB) {
9932         if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
9933           Offset += -C->getZExtValue();
9934           Op = Op.getOperand(0);
9935           continue;
9936         }
9937       }
9938
9939       // Otherwise, this isn't something we can handle, reject it.
9940       return;
9941     }
9942
9943     GlobalValue *GV = GA->getGlobal();
9944     // If we require an extra load to get this address, as in PIC mode, we
9945     // can't accept it.
9946     if (isGlobalStubReference(Subtarget->ClassifyGlobalReference(GV,
9947                                                         getTargetMachine())))
9948       return;
9949
9950     if (hasMemory)
9951       Op = LowerGlobalAddress(GV, Op.getDebugLoc(), Offset, DAG);
9952     else
9953       Op = DAG.getTargetGlobalAddress(GV, GA->getValueType(0), Offset);
9954     Result = Op;
9955     break;
9956   }
9957   }
9958
9959   if (Result.getNode()) {
9960     Ops.push_back(Result);
9961     return;
9962   }
9963   return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, hasMemory,
9964                                                       Ops, DAG);
9965 }
9966
9967 std::vector<unsigned> X86TargetLowering::
9968 getRegClassForInlineAsmConstraint(const std::string &Constraint,
9969                                   EVT VT) const {
9970   if (Constraint.size() == 1) {
9971     // FIXME: not handling fp-stack yet!
9972     switch (Constraint[0]) {      // GCC X86 Constraint Letters
9973     default: break;  // Unknown constraint letter
9974     case 'q':   // GENERAL_REGS in 64-bit mode, Q_REGS in 32-bit mode.
9975       if (Subtarget->is64Bit()) {
9976         if (VT == MVT::i32)
9977           return make_vector<unsigned>(X86::EAX, X86::EDX, X86::ECX, X86::EBX,
9978                                        X86::ESI, X86::EDI, X86::R8D, X86::R9D,
9979                                        X86::R10D,X86::R11D,X86::R12D,
9980                                        X86::R13D,X86::R14D,X86::R15D,
9981                                        X86::EBP, X86::ESP, 0);
9982         else if (VT == MVT::i16)
9983           return make_vector<unsigned>(X86::AX,  X86::DX,  X86::CX, X86::BX,
9984                                        X86::SI,  X86::DI,  X86::R8W,X86::R9W,
9985                                        X86::R10W,X86::R11W,X86::R12W,
9986                                        X86::R13W,X86::R14W,X86::R15W,
9987                                        X86::BP,  X86::SP, 0);
9988         else if (VT == MVT::i8)
9989           return make_vector<unsigned>(X86::AL,  X86::DL,  X86::CL, X86::BL,
9990                                        X86::SIL, X86::DIL, X86::R8B,X86::R9B,
9991                                        X86::R10B,X86::R11B,X86::R12B,
9992                                        X86::R13B,X86::R14B,X86::R15B,
9993                                        X86::BPL, X86::SPL, 0);
9994
9995         else if (VT == MVT::i64)
9996           return make_vector<unsigned>(X86::RAX, X86::RDX, X86::RCX, X86::RBX,
9997                                        X86::RSI, X86::RDI, X86::R8,  X86::R9,
9998                                        X86::R10, X86::R11, X86::R12,
9999                                        X86::R13, X86::R14, X86::R15,
10000                                        X86::RBP, X86::RSP, 0);
10001
10002         break;
10003       }
10004       // 32-bit fallthrough
10005     case 'Q':   // Q_REGS
10006       if (VT == MVT::i32)
10007         return make_vector<unsigned>(X86::EAX, X86::EDX, X86::ECX, X86::EBX, 0);
10008       else if (VT == MVT::i16)
10009         return make_vector<unsigned>(X86::AX, X86::DX, X86::CX, X86::BX, 0);
10010       else if (VT == MVT::i8)
10011         return make_vector<unsigned>(X86::AL, X86::DL, X86::CL, X86::BL, 0);
10012       else if (VT == MVT::i64)
10013         return make_vector<unsigned>(X86::RAX, X86::RDX, X86::RCX, X86::RBX, 0);
10014       break;
10015     }
10016   }
10017
10018   return std::vector<unsigned>();
10019 }
10020
10021 std::pair<unsigned, const TargetRegisterClass*>
10022 X86TargetLowering::getRegForInlineAsmConstraint(const std::string &Constraint,
10023                                                 EVT VT) const {
10024   // First, see if this is a constraint that directly corresponds to an LLVM
10025   // register class.
10026   if (Constraint.size() == 1) {
10027     // GCC Constraint Letters
10028     switch (Constraint[0]) {
10029     default: break;
10030     case 'r':   // GENERAL_REGS
10031     case 'l':   // INDEX_REGS
10032       if (VT == MVT::i8)
10033         return std::make_pair(0U, X86::GR8RegisterClass);
10034       if (VT == MVT::i16)
10035         return std::make_pair(0U, X86::GR16RegisterClass);
10036       if (VT == MVT::i32 || !Subtarget->is64Bit())
10037         return std::make_pair(0U, X86::GR32RegisterClass);
10038       return std::make_pair(0U, X86::GR64RegisterClass);
10039     case 'R':   // LEGACY_REGS
10040       if (VT == MVT::i8)
10041         return std::make_pair(0U, X86::GR8_NOREXRegisterClass);
10042       if (VT == MVT::i16)
10043         return std::make_pair(0U, X86::GR16_NOREXRegisterClass);
10044       if (VT == MVT::i32 || !Subtarget->is64Bit())
10045         return std::make_pair(0U, X86::GR32_NOREXRegisterClass);
10046       return std::make_pair(0U, X86::GR64_NOREXRegisterClass);
10047     case 'f':  // FP Stack registers.
10048       // If SSE is enabled for this VT, use f80 to ensure the isel moves the
10049       // value to the correct fpstack register class.
10050       if (VT == MVT::f32 && !isScalarFPTypeInSSEReg(VT))
10051         return std::make_pair(0U, X86::RFP32RegisterClass);
10052       if (VT == MVT::f64 && !isScalarFPTypeInSSEReg(VT))
10053         return std::make_pair(0U, X86::RFP64RegisterClass);
10054       return std::make_pair(0U, X86::RFP80RegisterClass);
10055     case 'y':   // MMX_REGS if MMX allowed.
10056       if (!Subtarget->hasMMX()) break;
10057       return std::make_pair(0U, X86::VR64RegisterClass);
10058     case 'Y':   // SSE_REGS if SSE2 allowed
10059       if (!Subtarget->hasSSE2()) break;
10060       // FALL THROUGH.
10061     case 'x':   // SSE_REGS if SSE1 allowed
10062       if (!Subtarget->hasSSE1()) break;
10063
10064       switch (VT.getSimpleVT().SimpleTy) {
10065       default: break;
10066       // Scalar SSE types.
10067       case MVT::f32:
10068       case MVT::i32:
10069         return std::make_pair(0U, X86::FR32RegisterClass);
10070       case MVT::f64:
10071       case MVT::i64:
10072         return std::make_pair(0U, X86::FR64RegisterClass);
10073       // Vector types.
10074       case MVT::v16i8:
10075       case MVT::v8i16:
10076       case MVT::v4i32:
10077       case MVT::v2i64:
10078       case MVT::v4f32:
10079       case MVT::v2f64:
10080         return std::make_pair(0U, X86::VR128RegisterClass);
10081       }
10082       break;
10083     }
10084   }
10085
10086   // Use the default implementation in TargetLowering to convert the register
10087   // constraint into a member of a register class.
10088   std::pair<unsigned, const TargetRegisterClass*> Res;
10089   Res = TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
10090
10091   // Not found as a standard register?
10092   if (Res.second == 0) {
10093     // Map st(0) -> st(7) -> ST0
10094     if (Constraint.size() == 7 && Constraint[0] == '{' &&
10095         tolower(Constraint[1]) == 's' &&
10096         tolower(Constraint[2]) == 't' &&
10097         Constraint[3] == '(' &&
10098         (Constraint[4] >= '0' && Constraint[4] <= '7') &&
10099         Constraint[5] == ')' &&
10100         Constraint[6] == '}') {
10101
10102       Res.first = X86::ST0+Constraint[4]-'0';
10103       Res.second = X86::RFP80RegisterClass;
10104       return Res;
10105     }
10106
10107     // GCC allows "st(0)" to be called just plain "st".
10108     if (StringRef("{st}").equals_lower(Constraint)) {
10109       Res.first = X86::ST0;
10110       Res.second = X86::RFP80RegisterClass;
10111       return Res;
10112     }
10113
10114     // flags -> EFLAGS
10115     if (StringRef("{flags}").equals_lower(Constraint)) {
10116       Res.first = X86::EFLAGS;
10117       Res.second = X86::CCRRegisterClass;
10118       return Res;
10119     }
10120
10121     // 'A' means EAX + EDX.
10122     if (Constraint == "A") {
10123       Res.first = X86::EAX;
10124       Res.second = X86::GR32_ADRegisterClass;
10125       return Res;
10126     }
10127     return Res;
10128   }
10129
10130   // Otherwise, check to see if this is a register class of the wrong value
10131   // type.  For example, we want to map "{ax},i32" -> {eax}, we don't want it to
10132   // turn into {ax},{dx}.
10133   if (Res.second->hasType(VT))
10134     return Res;   // Correct type already, nothing to do.
10135
10136   // All of the single-register GCC register classes map their values onto
10137   // 16-bit register pieces "ax","dx","cx","bx","si","di","bp","sp".  If we
10138   // really want an 8-bit or 32-bit register, map to the appropriate register
10139   // class and return the appropriate register.
10140   if (Res.second == X86::GR16RegisterClass) {
10141     if (VT == MVT::i8) {
10142       unsigned DestReg = 0;
10143       switch (Res.first) {
10144       default: break;
10145       case X86::AX: DestReg = X86::AL; break;
10146       case X86::DX: DestReg = X86::DL; break;
10147       case X86::CX: DestReg = X86::CL; break;
10148       case X86::BX: DestReg = X86::BL; break;
10149       }
10150       if (DestReg) {
10151         Res.first = DestReg;
10152         Res.second = X86::GR8RegisterClass;
10153       }
10154     } else if (VT == MVT::i32) {
10155       unsigned DestReg = 0;
10156       switch (Res.first) {
10157       default: break;
10158       case X86::AX: DestReg = X86::EAX; break;
10159       case X86::DX: DestReg = X86::EDX; break;
10160       case X86::CX: DestReg = X86::ECX; break;
10161       case X86::BX: DestReg = X86::EBX; break;
10162       case X86::SI: DestReg = X86::ESI; break;
10163       case X86::DI: DestReg = X86::EDI; break;
10164       case X86::BP: DestReg = X86::EBP; break;
10165       case X86::SP: DestReg = X86::ESP; break;
10166       }
10167       if (DestReg) {
10168         Res.first = DestReg;
10169         Res.second = X86::GR32RegisterClass;
10170       }
10171     } else if (VT == MVT::i64) {
10172       unsigned DestReg = 0;
10173       switch (Res.first) {
10174       default: break;
10175       case X86::AX: DestReg = X86::RAX; break;
10176       case X86::DX: DestReg = X86::RDX; break;
10177       case X86::CX: DestReg = X86::RCX; break;
10178       case X86::BX: DestReg = X86::RBX; break;
10179       case X86::SI: DestReg = X86::RSI; break;
10180       case X86::DI: DestReg = X86::RDI; break;
10181       case X86::BP: DestReg = X86::RBP; break;
10182       case X86::SP: DestReg = X86::RSP; break;
10183       }
10184       if (DestReg) {
10185         Res.first = DestReg;
10186         Res.second = X86::GR64RegisterClass;
10187       }
10188     }
10189   } else if (Res.second == X86::FR32RegisterClass ||
10190              Res.second == X86::FR64RegisterClass ||
10191              Res.second == X86::VR128RegisterClass) {
10192     // Handle references to XMM physical registers that got mapped into the
10193     // wrong class.  This can happen with constraints like {xmm0} where the
10194     // target independent register mapper will just pick the first match it can
10195     // find, ignoring the required type.
10196     if (VT == MVT::f32)
10197       Res.second = X86::FR32RegisterClass;
10198     else if (VT == MVT::f64)
10199       Res.second = X86::FR64RegisterClass;
10200     else if (X86::VR128RegisterClass->hasType(VT))
10201       Res.second = X86::VR128RegisterClass;
10202   }
10203
10204   return Res;
10205 }
10206
10207 //===----------------------------------------------------------------------===//
10208 //                           X86 Widen vector type
10209 //===----------------------------------------------------------------------===//
10210
10211 /// getWidenVectorType: given a vector type, returns the type to widen
10212 /// to (e.g., v7i8 to v8i8). If the vector type is legal, it returns itself.
10213 /// If there is no vector type that we want to widen to, returns MVT::Other
10214 /// When and where to widen is target dependent based on the cost of
10215 /// scalarizing vs using the wider vector type.
10216
10217 EVT X86TargetLowering::getWidenVectorType(EVT VT) const {
10218   assert(VT.isVector());
10219   if (isTypeLegal(VT))
10220     return VT;
10221
10222   // TODO: In computeRegisterProperty, we can compute the list of legal vector
10223   //       type based on element type.  This would speed up our search (though
10224   //       it may not be worth it since the size of the list is relatively
10225   //       small).
10226   EVT EltVT = VT.getVectorElementType();
10227   unsigned NElts = VT.getVectorNumElements();
10228
10229   // On X86, it make sense to widen any vector wider than 1
10230   if (NElts <= 1)
10231     return MVT::Other;
10232
10233   for (unsigned nVT = MVT::FIRST_VECTOR_VALUETYPE;
10234        nVT <= MVT::LAST_VECTOR_VALUETYPE; ++nVT) {
10235     EVT SVT = (MVT::SimpleValueType)nVT;
10236
10237     if (isTypeLegal(SVT) &&
10238         SVT.getVectorElementType() == EltVT &&
10239         SVT.getVectorNumElements() > NElts)
10240       return SVT;
10241   }
10242   return MVT::Other;
10243 }