fix PR6605, X86ISD::CMP always returns i32 (EFLAGS), not
[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 "X86MCTargetExpr.h"
20 #include "X86TargetMachine.h"
21 #include "X86TargetObjectFile.h"
22 #include "llvm/CallingConv.h"
23 #include "llvm/Constants.h"
24 #include "llvm/DerivedTypes.h"
25 #include "llvm/GlobalAlias.h"
26 #include "llvm/GlobalVariable.h"
27 #include "llvm/Function.h"
28 #include "llvm/Instructions.h"
29 #include "llvm/Intrinsics.h"
30 #include "llvm/LLVMContext.h"
31 #include "llvm/CodeGen/MachineFrameInfo.h"
32 #include "llvm/CodeGen/MachineFunction.h"
33 #include "llvm/CodeGen/MachineInstrBuilder.h"
34 #include "llvm/CodeGen/MachineJumpTableInfo.h"
35 #include "llvm/CodeGen/MachineModuleInfo.h"
36 #include "llvm/CodeGen/MachineRegisterInfo.h"
37 #include "llvm/CodeGen/PseudoSourceValue.h"
38 #include "llvm/MC/MCAsmInfo.h"
39 #include "llvm/MC/MCContext.h"
40 #include "llvm/MC/MCSectionMachO.h"
41 #include "llvm/MC/MCSymbol.h"
42 #include "llvm/ADT/BitVector.h"
43 #include "llvm/ADT/SmallSet.h"
44 #include "llvm/ADT/Statistic.h"
45 #include "llvm/ADT/StringExtras.h"
46 #include "llvm/ADT/VectorExtras.h"
47 #include "llvm/Support/CommandLine.h"
48 #include "llvm/Support/Debug.h"
49 #include "llvm/Support/Dwarf.h"
50 #include "llvm/Support/ErrorHandling.h"
51 #include "llvm/Support/MathExtras.h"
52 #include "llvm/Support/raw_ostream.h"
53 using namespace llvm;
54 using namespace dwarf;
55
56 STATISTIC(NumTailCalls, "Number of tail calls");
57
58 static cl::opt<bool>
59 DisableMMX("disable-mmx", cl::Hidden, cl::desc("Disable use of MMX"));
60
61 // Disable16Bit - 16-bit operations typically have a larger encoding than
62 // corresponding 32-bit instructions, and 16-bit code is slow on some
63 // processors. This is an experimental flag to disable 16-bit operations
64 // (which forces them to be Legalized to 32-bit operations).
65 static cl::opt<bool>
66 Disable16Bit("disable-16bit", cl::Hidden,
67              cl::desc("Disable use of 16-bit instructions"));
68
69 // Forward declarations.
70 static SDValue getMOVL(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
71                        SDValue V2);
72
73 // FIXME: This is for a test.
74 static cl::opt<bool>
75 EnableX86EHTest("enable-x86-eh-test", cl::Hidden);
76
77 namespace llvm {
78   class X86_test_MachoTargetObjectFile : public TargetLoweringObjectFileMachO {
79   public:
80     virtual void Initialize(MCContext &Ctx, const TargetMachine &TM) {
81       TargetLoweringObjectFileMachO::Initialize(Ctx, TM);
82
83       // Exception Handling.
84       LSDASection = getMachOSection("__TEXT", "__gcc_except_tab", 0,
85                                     SectionKind::getReadOnlyWithRel());
86     }
87
88     virtual unsigned getTTypeEncoding() const {
89       return DW_EH_PE_indirect | DW_EH_PE_pcrel | DW_EH_PE_sdata4;
90     }
91   };
92
93   class X8664_test_MachoTargetObjectFile : public X8664_MachoTargetObjectFile {
94   public:
95     virtual void Initialize(MCContext &Ctx, const TargetMachine &TM) {
96       TargetLoweringObjectFileMachO::Initialize(Ctx, TM);
97
98       // Exception Handling.
99       LSDASection = getMachOSection("__TEXT", "__gcc_except_tab", 0,
100                                     SectionKind::getReadOnlyWithRel());
101     }
102
103     virtual unsigned getTTypeEncoding() const {
104       return DW_EH_PE_indirect | DW_EH_PE_pcrel | DW_EH_PE_sdata4;
105     }
106   };
107 }
108
109 static TargetLoweringObjectFile *createTLOF(X86TargetMachine &TM) {
110   switch (TM.getSubtarget<X86Subtarget>().TargetType) {
111   default: llvm_unreachable("unknown subtarget type");
112   case X86Subtarget::isDarwin:
113     // FIXME: This is for an EH test.
114     if (EnableX86EHTest) {
115       if (TM.getSubtarget<X86Subtarget>().is64Bit())
116         return new X8664_test_MachoTargetObjectFile();
117       else
118         return new X86_test_MachoTargetObjectFile();
119     }
120
121     if (TM.getSubtarget<X86Subtarget>().is64Bit())
122       return new X8664_MachoTargetObjectFile();
123     return new TargetLoweringObjectFileMachO();
124   case X86Subtarget::isELF:
125    if (TM.getSubtarget<X86Subtarget>().is64Bit())
126      return new X8664_ELFTargetObjectFile(TM);
127     return new X8632_ELFTargetObjectFile(TM);
128   case X86Subtarget::isMingw:
129   case X86Subtarget::isCygwin:
130   case X86Subtarget::isWindows:
131     return new TargetLoweringObjectFileCOFF();
132   }
133 }
134
135 X86TargetLowering::X86TargetLowering(X86TargetMachine &TM)
136   : TargetLowering(TM, createTLOF(TM)) {
137   Subtarget = &TM.getSubtarget<X86Subtarget>();
138   X86ScalarSSEf64 = Subtarget->hasSSE2();
139   X86ScalarSSEf32 = Subtarget->hasSSE1();
140   X86StackPtr = Subtarget->is64Bit() ? X86::RSP : X86::ESP;
141
142   RegInfo = TM.getRegisterInfo();
143   TD = getTargetData();
144
145   // Set up the TargetLowering object.
146
147   // X86 is weird, it always uses i8 for shift amounts and setcc results.
148   setShiftAmountType(MVT::i8);
149   setBooleanContents(ZeroOrOneBooleanContent);
150   setSchedulingPreference(SchedulingForRegPressure);
151   setStackPointerRegisterToSaveRestore(X86StackPtr);
152
153   if (Subtarget->isTargetDarwin()) {
154     // Darwin should use _setjmp/_longjmp instead of setjmp/longjmp.
155     setUseUnderscoreSetJmp(false);
156     setUseUnderscoreLongJmp(false);
157   } else if (Subtarget->isTargetMingw()) {
158     // MS runtime is weird: it exports _setjmp, but longjmp!
159     setUseUnderscoreSetJmp(true);
160     setUseUnderscoreLongJmp(false);
161   } else {
162     setUseUnderscoreSetJmp(true);
163     setUseUnderscoreLongJmp(true);
164   }
165
166   // Set up the register classes.
167   addRegisterClass(MVT::i8, X86::GR8RegisterClass);
168   if (!Disable16Bit)
169     addRegisterClass(MVT::i16, X86::GR16RegisterClass);
170   addRegisterClass(MVT::i32, X86::GR32RegisterClass);
171   if (Subtarget->is64Bit())
172     addRegisterClass(MVT::i64, X86::GR64RegisterClass);
173
174   setLoadExtAction(ISD::SEXTLOAD, MVT::i1, Promote);
175
176   // We don't accept any truncstore of integer registers.
177   setTruncStoreAction(MVT::i64, MVT::i32, Expand);
178   if (!Disable16Bit)
179     setTruncStoreAction(MVT::i64, MVT::i16, Expand);
180   setTruncStoreAction(MVT::i64, MVT::i8 , Expand);
181   if (!Disable16Bit)
182     setTruncStoreAction(MVT::i32, MVT::i16, Expand);
183   setTruncStoreAction(MVT::i32, MVT::i8 , Expand);
184   setTruncStoreAction(MVT::i16, MVT::i8,  Expand);
185
186   // SETOEQ and SETUNE require checking two conditions.
187   setCondCodeAction(ISD::SETOEQ, MVT::f32, Expand);
188   setCondCodeAction(ISD::SETOEQ, MVT::f64, Expand);
189   setCondCodeAction(ISD::SETOEQ, MVT::f80, Expand);
190   setCondCodeAction(ISD::SETUNE, MVT::f32, Expand);
191   setCondCodeAction(ISD::SETUNE, MVT::f64, Expand);
192   setCondCodeAction(ISD::SETUNE, MVT::f80, Expand);
193
194   // Promote all UINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have this
195   // operation.
196   setOperationAction(ISD::UINT_TO_FP       , MVT::i1   , Promote);
197   setOperationAction(ISD::UINT_TO_FP       , MVT::i8   , Promote);
198   setOperationAction(ISD::UINT_TO_FP       , MVT::i16  , Promote);
199
200   if (Subtarget->is64Bit()) {
201     setOperationAction(ISD::UINT_TO_FP     , MVT::i32  , Promote);
202     setOperationAction(ISD::UINT_TO_FP     , MVT::i64  , Expand);
203   } else if (!UseSoftFloat) {
204     if (X86ScalarSSEf64) {
205       // We have an impenetrably clever algorithm for ui64->double only.
206       setOperationAction(ISD::UINT_TO_FP   , MVT::i64  , Custom);
207     }
208     // We have an algorithm for SSE2, and we turn this into a 64-bit
209     // FILD for other targets.
210     setOperationAction(ISD::UINT_TO_FP   , MVT::i32  , Custom);
211   }
212
213   // Promote i1/i8 SINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have
214   // this operation.
215   setOperationAction(ISD::SINT_TO_FP       , MVT::i1   , Promote);
216   setOperationAction(ISD::SINT_TO_FP       , MVT::i8   , Promote);
217
218   if (!UseSoftFloat) {
219     // SSE has no i16 to fp conversion, only i32
220     if (X86ScalarSSEf32) {
221       setOperationAction(ISD::SINT_TO_FP     , MVT::i16  , Promote);
222       // f32 and f64 cases are Legal, f80 case is not
223       setOperationAction(ISD::SINT_TO_FP     , MVT::i32  , Custom);
224     } else {
225       setOperationAction(ISD::SINT_TO_FP     , MVT::i16  , Custom);
226       setOperationAction(ISD::SINT_TO_FP     , MVT::i32  , Custom);
227     }
228   } else {
229     setOperationAction(ISD::SINT_TO_FP     , MVT::i16  , Promote);
230     setOperationAction(ISD::SINT_TO_FP     , MVT::i32  , Promote);
231   }
232
233   // In 32-bit mode these are custom lowered.  In 64-bit mode F32 and F64
234   // are Legal, f80 is custom lowered.
235   setOperationAction(ISD::FP_TO_SINT     , MVT::i64  , Custom);
236   setOperationAction(ISD::SINT_TO_FP     , MVT::i64  , Custom);
237
238   // Promote i1/i8 FP_TO_SINT to larger FP_TO_SINTS's, as X86 doesn't have
239   // this operation.
240   setOperationAction(ISD::FP_TO_SINT       , MVT::i1   , Promote);
241   setOperationAction(ISD::FP_TO_SINT       , MVT::i8   , Promote);
242
243   if (X86ScalarSSEf32) {
244     setOperationAction(ISD::FP_TO_SINT     , MVT::i16  , Promote);
245     // f32 and f64 cases are Legal, f80 case is not
246     setOperationAction(ISD::FP_TO_SINT     , MVT::i32  , Custom);
247   } else {
248     setOperationAction(ISD::FP_TO_SINT     , MVT::i16  , Custom);
249     setOperationAction(ISD::FP_TO_SINT     , MVT::i32  , Custom);
250   }
251
252   // Handle FP_TO_UINT by promoting the destination to a larger signed
253   // conversion.
254   setOperationAction(ISD::FP_TO_UINT       , MVT::i1   , Promote);
255   setOperationAction(ISD::FP_TO_UINT       , MVT::i8   , Promote);
256   setOperationAction(ISD::FP_TO_UINT       , MVT::i16  , Promote);
257
258   if (Subtarget->is64Bit()) {
259     setOperationAction(ISD::FP_TO_UINT     , MVT::i64  , Expand);
260     setOperationAction(ISD::FP_TO_UINT     , MVT::i32  , Promote);
261   } else if (!UseSoftFloat) {
262     if (X86ScalarSSEf32 && !Subtarget->hasSSE3())
263       // Expand FP_TO_UINT into a select.
264       // FIXME: We would like to use a Custom expander here eventually to do
265       // the optimal thing for SSE vs. the default expansion in the legalizer.
266       setOperationAction(ISD::FP_TO_UINT   , MVT::i32  , Expand);
267     else
268       // With SSE3 we can use fisttpll to convert to a signed i64; without
269       // SSE, we're stuck with a fistpll.
270       setOperationAction(ISD::FP_TO_UINT   , MVT::i32  , Custom);
271   }
272
273   // TODO: when we have SSE, these could be more efficient, by using movd/movq.
274   if (!X86ScalarSSEf64) {
275     setOperationAction(ISD::BIT_CONVERT      , MVT::f32  , Expand);
276     setOperationAction(ISD::BIT_CONVERT      , MVT::i32  , Expand);
277   }
278
279   // Scalar integer divide and remainder are lowered to use operations that
280   // produce two results, to match the available instructions. This exposes
281   // the two-result form to trivial CSE, which is able to combine x/y and x%y
282   // into a single instruction.
283   //
284   // Scalar integer multiply-high is also lowered to use two-result
285   // operations, to match the available instructions. However, plain multiply
286   // (low) operations are left as Legal, as there are single-result
287   // instructions for this in x86. Using the two-result multiply instructions
288   // when both high and low results are needed must be arranged by dagcombine.
289   setOperationAction(ISD::MULHS           , MVT::i8    , Expand);
290   setOperationAction(ISD::MULHU           , MVT::i8    , Expand);
291   setOperationAction(ISD::SDIV            , MVT::i8    , Expand);
292   setOperationAction(ISD::UDIV            , MVT::i8    , Expand);
293   setOperationAction(ISD::SREM            , MVT::i8    , Expand);
294   setOperationAction(ISD::UREM            , MVT::i8    , Expand);
295   setOperationAction(ISD::MULHS           , MVT::i16   , Expand);
296   setOperationAction(ISD::MULHU           , MVT::i16   , Expand);
297   setOperationAction(ISD::SDIV            , MVT::i16   , Expand);
298   setOperationAction(ISD::UDIV            , MVT::i16   , Expand);
299   setOperationAction(ISD::SREM            , MVT::i16   , Expand);
300   setOperationAction(ISD::UREM            , MVT::i16   , Expand);
301   setOperationAction(ISD::MULHS           , MVT::i32   , Expand);
302   setOperationAction(ISD::MULHU           , MVT::i32   , Expand);
303   setOperationAction(ISD::SDIV            , MVT::i32   , Expand);
304   setOperationAction(ISD::UDIV            , MVT::i32   , Expand);
305   setOperationAction(ISD::SREM            , MVT::i32   , Expand);
306   setOperationAction(ISD::UREM            , MVT::i32   , Expand);
307   setOperationAction(ISD::MULHS           , MVT::i64   , Expand);
308   setOperationAction(ISD::MULHU           , MVT::i64   , Expand);
309   setOperationAction(ISD::SDIV            , MVT::i64   , Expand);
310   setOperationAction(ISD::UDIV            , MVT::i64   , Expand);
311   setOperationAction(ISD::SREM            , MVT::i64   , Expand);
312   setOperationAction(ISD::UREM            , MVT::i64   , Expand);
313
314   setOperationAction(ISD::BR_JT            , MVT::Other, Expand);
315   setOperationAction(ISD::BRCOND           , MVT::Other, Custom);
316   setOperationAction(ISD::BR_CC            , MVT::Other, Expand);
317   setOperationAction(ISD::SELECT_CC        , MVT::Other, Expand);
318   if (Subtarget->is64Bit())
319     setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i32, Legal);
320   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16  , Legal);
321   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8   , Legal);
322   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1   , Expand);
323   setOperationAction(ISD::FP_ROUND_INREG   , MVT::f32  , Expand);
324   setOperationAction(ISD::FREM             , MVT::f32  , Expand);
325   setOperationAction(ISD::FREM             , MVT::f64  , Expand);
326   setOperationAction(ISD::FREM             , MVT::f80  , Expand);
327   setOperationAction(ISD::FLT_ROUNDS_      , MVT::i32  , Custom);
328
329   setOperationAction(ISD::CTPOP            , MVT::i8   , Expand);
330   setOperationAction(ISD::CTTZ             , MVT::i8   , Custom);
331   setOperationAction(ISD::CTLZ             , MVT::i8   , Custom);
332   setOperationAction(ISD::CTPOP            , MVT::i16  , Expand);
333   if (Disable16Bit) {
334     setOperationAction(ISD::CTTZ           , MVT::i16  , Expand);
335     setOperationAction(ISD::CTLZ           , MVT::i16  , Expand);
336   } else {
337     setOperationAction(ISD::CTTZ           , MVT::i16  , Custom);
338     setOperationAction(ISD::CTLZ           , MVT::i16  , Custom);
339   }
340   setOperationAction(ISD::CTPOP            , MVT::i32  , Expand);
341   setOperationAction(ISD::CTTZ             , MVT::i32  , Custom);
342   setOperationAction(ISD::CTLZ             , MVT::i32  , Custom);
343   if (Subtarget->is64Bit()) {
344     setOperationAction(ISD::CTPOP          , MVT::i64  , Expand);
345     setOperationAction(ISD::CTTZ           , MVT::i64  , Custom);
346     setOperationAction(ISD::CTLZ           , MVT::i64  , Custom);
347   }
348
349   setOperationAction(ISD::READCYCLECOUNTER , MVT::i64  , Custom);
350   setOperationAction(ISD::BSWAP            , MVT::i16  , Expand);
351
352   // These should be promoted to a larger select which is supported.
353   setOperationAction(ISD::SELECT          , MVT::i1   , Promote);
354   // X86 wants to expand cmov itself.
355   setOperationAction(ISD::SELECT          , MVT::i8   , Custom);
356   if (Disable16Bit)
357     setOperationAction(ISD::SELECT        , MVT::i16  , Expand);
358   else
359     setOperationAction(ISD::SELECT        , MVT::i16  , Custom);
360   setOperationAction(ISD::SELECT          , MVT::i32  , Custom);
361   setOperationAction(ISD::SELECT          , MVT::f32  , Custom);
362   setOperationAction(ISD::SELECT          , MVT::f64  , Custom);
363   setOperationAction(ISD::SELECT          , MVT::f80  , Custom);
364   setOperationAction(ISD::SETCC           , MVT::i8   , Custom);
365   if (Disable16Bit)
366     setOperationAction(ISD::SETCC         , MVT::i16  , Expand);
367   else
368     setOperationAction(ISD::SETCC         , MVT::i16  , Custom);
369   setOperationAction(ISD::SETCC           , MVT::i32  , Custom);
370   setOperationAction(ISD::SETCC           , MVT::f32  , Custom);
371   setOperationAction(ISD::SETCC           , MVT::f64  , Custom);
372   setOperationAction(ISD::SETCC           , MVT::f80  , Custom);
373   if (Subtarget->is64Bit()) {
374     setOperationAction(ISD::SELECT        , MVT::i64  , Custom);
375     setOperationAction(ISD::SETCC         , MVT::i64  , Custom);
376   }
377   setOperationAction(ISD::EH_RETURN       , MVT::Other, Custom);
378
379   // Darwin ABI issue.
380   setOperationAction(ISD::ConstantPool    , MVT::i32  , Custom);
381   setOperationAction(ISD::JumpTable       , MVT::i32  , Custom);
382   setOperationAction(ISD::GlobalAddress   , MVT::i32  , Custom);
383   setOperationAction(ISD::GlobalTLSAddress, MVT::i32  , Custom);
384   if (Subtarget->is64Bit())
385     setOperationAction(ISD::GlobalTLSAddress, MVT::i64, Custom);
386   setOperationAction(ISD::ExternalSymbol  , MVT::i32  , Custom);
387   setOperationAction(ISD::BlockAddress    , MVT::i32  , Custom);
388   if (Subtarget->is64Bit()) {
389     setOperationAction(ISD::ConstantPool  , MVT::i64  , Custom);
390     setOperationAction(ISD::JumpTable     , MVT::i64  , Custom);
391     setOperationAction(ISD::GlobalAddress , MVT::i64  , Custom);
392     setOperationAction(ISD::ExternalSymbol, MVT::i64  , Custom);
393     setOperationAction(ISD::BlockAddress  , MVT::i64  , Custom);
394   }
395   // 64-bit addm sub, shl, sra, srl (iff 32-bit x86)
396   setOperationAction(ISD::SHL_PARTS       , MVT::i32  , Custom);
397   setOperationAction(ISD::SRA_PARTS       , MVT::i32  , Custom);
398   setOperationAction(ISD::SRL_PARTS       , MVT::i32  , Custom);
399   if (Subtarget->is64Bit()) {
400     setOperationAction(ISD::SHL_PARTS     , MVT::i64  , Custom);
401     setOperationAction(ISD::SRA_PARTS     , MVT::i64  , Custom);
402     setOperationAction(ISD::SRL_PARTS     , MVT::i64  , Custom);
403   }
404
405   if (Subtarget->hasSSE1())
406     setOperationAction(ISD::PREFETCH      , MVT::Other, Legal);
407
408   if (!Subtarget->hasSSE2())
409     setOperationAction(ISD::MEMBARRIER    , MVT::Other, Expand);
410
411   // Expand certain atomics
412   setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i8, Custom);
413   setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i16, Custom);
414   setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i32, Custom);
415   setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i64, Custom);
416
417   setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i8, Custom);
418   setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i16, Custom);
419   setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i32, Custom);
420   setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i64, Custom);
421
422   if (!Subtarget->is64Bit()) {
423     setOperationAction(ISD::ATOMIC_LOAD_ADD, MVT::i64, Custom);
424     setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i64, Custom);
425     setOperationAction(ISD::ATOMIC_LOAD_AND, MVT::i64, Custom);
426     setOperationAction(ISD::ATOMIC_LOAD_OR, MVT::i64, Custom);
427     setOperationAction(ISD::ATOMIC_LOAD_XOR, MVT::i64, Custom);
428     setOperationAction(ISD::ATOMIC_LOAD_NAND, MVT::i64, Custom);
429     setOperationAction(ISD::ATOMIC_SWAP, MVT::i64, Custom);
430   }
431
432   // FIXME - use subtarget debug flags
433   if (!Subtarget->isTargetDarwin() &&
434       !Subtarget->isTargetELF() &&
435       !Subtarget->isTargetCygMing()) {
436     setOperationAction(ISD::EH_LABEL, MVT::Other, Expand);
437   }
438
439   setOperationAction(ISD::EXCEPTIONADDR, MVT::i64, Expand);
440   setOperationAction(ISD::EHSELECTION,   MVT::i64, Expand);
441   setOperationAction(ISD::EXCEPTIONADDR, MVT::i32, Expand);
442   setOperationAction(ISD::EHSELECTION,   MVT::i32, Expand);
443   if (Subtarget->is64Bit()) {
444     setExceptionPointerRegister(X86::RAX);
445     setExceptionSelectorRegister(X86::RDX);
446   } else {
447     setExceptionPointerRegister(X86::EAX);
448     setExceptionSelectorRegister(X86::EDX);
449   }
450   setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i32, Custom);
451   setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i64, Custom);
452
453   setOperationAction(ISD::TRAMPOLINE, MVT::Other, Custom);
454
455   setOperationAction(ISD::TRAP, MVT::Other, Legal);
456
457   // VASTART needs to be custom lowered to use the VarArgsFrameIndex
458   setOperationAction(ISD::VASTART           , MVT::Other, Custom);
459   setOperationAction(ISD::VAEND             , MVT::Other, Expand);
460   if (Subtarget->is64Bit()) {
461     setOperationAction(ISD::VAARG           , MVT::Other, Custom);
462     setOperationAction(ISD::VACOPY          , MVT::Other, Custom);
463   } else {
464     setOperationAction(ISD::VAARG           , MVT::Other, Expand);
465     setOperationAction(ISD::VACOPY          , MVT::Other, Expand);
466   }
467
468   setOperationAction(ISD::STACKSAVE,          MVT::Other, Expand);
469   setOperationAction(ISD::STACKRESTORE,       MVT::Other, Expand);
470   if (Subtarget->is64Bit())
471     setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i64, Expand);
472   if (Subtarget->isTargetCygMing())
473     setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Custom);
474   else
475     setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Expand);
476
477   if (!UseSoftFloat && X86ScalarSSEf64) {
478     // f32 and f64 use SSE.
479     // Set up the FP register classes.
480     addRegisterClass(MVT::f32, X86::FR32RegisterClass);
481     addRegisterClass(MVT::f64, X86::FR64RegisterClass);
482
483     // Use ANDPD to simulate FABS.
484     setOperationAction(ISD::FABS , MVT::f64, Custom);
485     setOperationAction(ISD::FABS , MVT::f32, Custom);
486
487     // Use XORP to simulate FNEG.
488     setOperationAction(ISD::FNEG , MVT::f64, Custom);
489     setOperationAction(ISD::FNEG , MVT::f32, Custom);
490
491     // Use ANDPD and ORPD to simulate FCOPYSIGN.
492     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
493     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
494
495     // We don't support sin/cos/fmod
496     setOperationAction(ISD::FSIN , MVT::f64, Expand);
497     setOperationAction(ISD::FCOS , MVT::f64, Expand);
498     setOperationAction(ISD::FSIN , MVT::f32, Expand);
499     setOperationAction(ISD::FCOS , MVT::f32, Expand);
500
501     // Expand FP immediates into loads from the stack, except for the special
502     // cases we handle.
503     addLegalFPImmediate(APFloat(+0.0)); // xorpd
504     addLegalFPImmediate(APFloat(+0.0f)); // xorps
505   } else if (!UseSoftFloat && X86ScalarSSEf32) {
506     // Use SSE for f32, x87 for f64.
507     // Set up the FP register classes.
508     addRegisterClass(MVT::f32, X86::FR32RegisterClass);
509     addRegisterClass(MVT::f64, X86::RFP64RegisterClass);
510
511     // Use ANDPS to simulate FABS.
512     setOperationAction(ISD::FABS , MVT::f32, Custom);
513
514     // Use XORP to simulate FNEG.
515     setOperationAction(ISD::FNEG , MVT::f32, Custom);
516
517     setOperationAction(ISD::UNDEF,     MVT::f64, Expand);
518
519     // Use ANDPS and ORPS to simulate FCOPYSIGN.
520     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
521     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
522
523     // We don't support sin/cos/fmod
524     setOperationAction(ISD::FSIN , MVT::f32, Expand);
525     setOperationAction(ISD::FCOS , MVT::f32, Expand);
526
527     // Special cases we handle for FP constants.
528     addLegalFPImmediate(APFloat(+0.0f)); // xorps
529     addLegalFPImmediate(APFloat(+0.0)); // FLD0
530     addLegalFPImmediate(APFloat(+1.0)); // FLD1
531     addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
532     addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
533
534     if (!UnsafeFPMath) {
535       setOperationAction(ISD::FSIN           , MVT::f64  , Expand);
536       setOperationAction(ISD::FCOS           , MVT::f64  , Expand);
537     }
538   } else if (!UseSoftFloat) {
539     // f32 and f64 in x87.
540     // Set up the FP register classes.
541     addRegisterClass(MVT::f64, X86::RFP64RegisterClass);
542     addRegisterClass(MVT::f32, X86::RFP32RegisterClass);
543
544     setOperationAction(ISD::UNDEF,     MVT::f64, Expand);
545     setOperationAction(ISD::UNDEF,     MVT::f32, Expand);
546     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
547     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand);
548
549     if (!UnsafeFPMath) {
550       setOperationAction(ISD::FSIN           , MVT::f64  , Expand);
551       setOperationAction(ISD::FCOS           , MVT::f64  , Expand);
552     }
553     addLegalFPImmediate(APFloat(+0.0)); // FLD0
554     addLegalFPImmediate(APFloat(+1.0)); // FLD1
555     addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
556     addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
557     addLegalFPImmediate(APFloat(+0.0f)); // FLD0
558     addLegalFPImmediate(APFloat(+1.0f)); // FLD1
559     addLegalFPImmediate(APFloat(-0.0f)); // FLD0/FCHS
560     addLegalFPImmediate(APFloat(-1.0f)); // FLD1/FCHS
561   }
562
563   // Long double always uses X87.
564   if (!UseSoftFloat) {
565     addRegisterClass(MVT::f80, X86::RFP80RegisterClass);
566     setOperationAction(ISD::UNDEF,     MVT::f80, Expand);
567     setOperationAction(ISD::FCOPYSIGN, MVT::f80, Expand);
568     {
569       bool ignored;
570       APFloat TmpFlt(+0.0);
571       TmpFlt.convert(APFloat::x87DoubleExtended, APFloat::rmNearestTiesToEven,
572                      &ignored);
573       addLegalFPImmediate(TmpFlt);  // FLD0
574       TmpFlt.changeSign();
575       addLegalFPImmediate(TmpFlt);  // FLD0/FCHS
576       APFloat TmpFlt2(+1.0);
577       TmpFlt2.convert(APFloat::x87DoubleExtended, APFloat::rmNearestTiesToEven,
578                       &ignored);
579       addLegalFPImmediate(TmpFlt2);  // FLD1
580       TmpFlt2.changeSign();
581       addLegalFPImmediate(TmpFlt2);  // FLD1/FCHS
582     }
583
584     if (!UnsafeFPMath) {
585       setOperationAction(ISD::FSIN           , MVT::f80  , Expand);
586       setOperationAction(ISD::FCOS           , MVT::f80  , Expand);
587     }
588   }
589
590   // Always use a library call for pow.
591   setOperationAction(ISD::FPOW             , MVT::f32  , Expand);
592   setOperationAction(ISD::FPOW             , MVT::f64  , Expand);
593   setOperationAction(ISD::FPOW             , MVT::f80  , Expand);
594
595   setOperationAction(ISD::FLOG, MVT::f80, Expand);
596   setOperationAction(ISD::FLOG2, MVT::f80, Expand);
597   setOperationAction(ISD::FLOG10, MVT::f80, Expand);
598   setOperationAction(ISD::FEXP, MVT::f80, Expand);
599   setOperationAction(ISD::FEXP2, MVT::f80, Expand);
600
601   // First set operation action for all vector types to either promote
602   // (for widening) or expand (for scalarization). Then we will selectively
603   // turn on ones that can be effectively codegen'd.
604   for (unsigned VT = (unsigned)MVT::FIRST_VECTOR_VALUETYPE;
605        VT <= (unsigned)MVT::LAST_VECTOR_VALUETYPE; ++VT) {
606     setOperationAction(ISD::ADD , (MVT::SimpleValueType)VT, Expand);
607     setOperationAction(ISD::SUB , (MVT::SimpleValueType)VT, Expand);
608     setOperationAction(ISD::FADD, (MVT::SimpleValueType)VT, Expand);
609     setOperationAction(ISD::FNEG, (MVT::SimpleValueType)VT, Expand);
610     setOperationAction(ISD::FSUB, (MVT::SimpleValueType)VT, Expand);
611     setOperationAction(ISD::MUL , (MVT::SimpleValueType)VT, Expand);
612     setOperationAction(ISD::FMUL, (MVT::SimpleValueType)VT, Expand);
613     setOperationAction(ISD::SDIV, (MVT::SimpleValueType)VT, Expand);
614     setOperationAction(ISD::UDIV, (MVT::SimpleValueType)VT, Expand);
615     setOperationAction(ISD::FDIV, (MVT::SimpleValueType)VT, Expand);
616     setOperationAction(ISD::SREM, (MVT::SimpleValueType)VT, Expand);
617     setOperationAction(ISD::UREM, (MVT::SimpleValueType)VT, Expand);
618     setOperationAction(ISD::LOAD, (MVT::SimpleValueType)VT, Expand);
619     setOperationAction(ISD::VECTOR_SHUFFLE, (MVT::SimpleValueType)VT, Expand);
620     setOperationAction(ISD::EXTRACT_VECTOR_ELT,(MVT::SimpleValueType)VT,Expand);
621     setOperationAction(ISD::EXTRACT_SUBVECTOR,(MVT::SimpleValueType)VT,Expand);
622     setOperationAction(ISD::INSERT_VECTOR_ELT,(MVT::SimpleValueType)VT, Expand);
623     setOperationAction(ISD::FABS, (MVT::SimpleValueType)VT, Expand);
624     setOperationAction(ISD::FSIN, (MVT::SimpleValueType)VT, Expand);
625     setOperationAction(ISD::FCOS, (MVT::SimpleValueType)VT, Expand);
626     setOperationAction(ISD::FREM, (MVT::SimpleValueType)VT, Expand);
627     setOperationAction(ISD::FPOWI, (MVT::SimpleValueType)VT, Expand);
628     setOperationAction(ISD::FSQRT, (MVT::SimpleValueType)VT, Expand);
629     setOperationAction(ISD::FCOPYSIGN, (MVT::SimpleValueType)VT, Expand);
630     setOperationAction(ISD::SMUL_LOHI, (MVT::SimpleValueType)VT, Expand);
631     setOperationAction(ISD::UMUL_LOHI, (MVT::SimpleValueType)VT, Expand);
632     setOperationAction(ISD::SDIVREM, (MVT::SimpleValueType)VT, Expand);
633     setOperationAction(ISD::UDIVREM, (MVT::SimpleValueType)VT, Expand);
634     setOperationAction(ISD::FPOW, (MVT::SimpleValueType)VT, Expand);
635     setOperationAction(ISD::CTPOP, (MVT::SimpleValueType)VT, Expand);
636     setOperationAction(ISD::CTTZ, (MVT::SimpleValueType)VT, Expand);
637     setOperationAction(ISD::CTLZ, (MVT::SimpleValueType)VT, Expand);
638     setOperationAction(ISD::SHL, (MVT::SimpleValueType)VT, Expand);
639     setOperationAction(ISD::SRA, (MVT::SimpleValueType)VT, Expand);
640     setOperationAction(ISD::SRL, (MVT::SimpleValueType)VT, Expand);
641     setOperationAction(ISD::ROTL, (MVT::SimpleValueType)VT, Expand);
642     setOperationAction(ISD::ROTR, (MVT::SimpleValueType)VT, Expand);
643     setOperationAction(ISD::BSWAP, (MVT::SimpleValueType)VT, Expand);
644     setOperationAction(ISD::VSETCC, (MVT::SimpleValueType)VT, Expand);
645     setOperationAction(ISD::FLOG, (MVT::SimpleValueType)VT, Expand);
646     setOperationAction(ISD::FLOG2, (MVT::SimpleValueType)VT, Expand);
647     setOperationAction(ISD::FLOG10, (MVT::SimpleValueType)VT, Expand);
648     setOperationAction(ISD::FEXP, (MVT::SimpleValueType)VT, Expand);
649     setOperationAction(ISD::FEXP2, (MVT::SimpleValueType)VT, Expand);
650     setOperationAction(ISD::FP_TO_UINT, (MVT::SimpleValueType)VT, Expand);
651     setOperationAction(ISD::FP_TO_SINT, (MVT::SimpleValueType)VT, Expand);
652     setOperationAction(ISD::UINT_TO_FP, (MVT::SimpleValueType)VT, Expand);
653     setOperationAction(ISD::SINT_TO_FP, (MVT::SimpleValueType)VT, Expand);
654     setOperationAction(ISD::SIGN_EXTEND_INREG, (MVT::SimpleValueType)VT,Expand);
655     setOperationAction(ISD::TRUNCATE,  (MVT::SimpleValueType)VT, Expand);
656     setOperationAction(ISD::SIGN_EXTEND,  (MVT::SimpleValueType)VT, Expand);
657     setOperationAction(ISD::ZERO_EXTEND,  (MVT::SimpleValueType)VT, Expand);
658     setOperationAction(ISD::ANY_EXTEND,  (MVT::SimpleValueType)VT, Expand);
659     for (unsigned InnerVT = (unsigned)MVT::FIRST_VECTOR_VALUETYPE;
660          InnerVT <= (unsigned)MVT::LAST_VECTOR_VALUETYPE; ++InnerVT)
661       setTruncStoreAction((MVT::SimpleValueType)VT,
662                           (MVT::SimpleValueType)InnerVT, Expand);
663     setLoadExtAction(ISD::SEXTLOAD, (MVT::SimpleValueType)VT, Expand);
664     setLoadExtAction(ISD::ZEXTLOAD, (MVT::SimpleValueType)VT, Expand);
665     setLoadExtAction(ISD::EXTLOAD, (MVT::SimpleValueType)VT, Expand);
666   }
667
668   // FIXME: In order to prevent SSE instructions being expanded to MMX ones
669   // with -msoft-float, disable use of MMX as well.
670   if (!UseSoftFloat && !DisableMMX && Subtarget->hasMMX()) {
671     addRegisterClass(MVT::v8i8,  X86::VR64RegisterClass);
672     addRegisterClass(MVT::v4i16, X86::VR64RegisterClass);
673     addRegisterClass(MVT::v2i32, X86::VR64RegisterClass);
674     addRegisterClass(MVT::v2f32, X86::VR64RegisterClass);
675     addRegisterClass(MVT::v1i64, X86::VR64RegisterClass);
676
677     setOperationAction(ISD::ADD,                MVT::v8i8,  Legal);
678     setOperationAction(ISD::ADD,                MVT::v4i16, Legal);
679     setOperationAction(ISD::ADD,                MVT::v2i32, Legal);
680     setOperationAction(ISD::ADD,                MVT::v1i64, Legal);
681
682     setOperationAction(ISD::SUB,                MVT::v8i8,  Legal);
683     setOperationAction(ISD::SUB,                MVT::v4i16, Legal);
684     setOperationAction(ISD::SUB,                MVT::v2i32, Legal);
685     setOperationAction(ISD::SUB,                MVT::v1i64, Legal);
686
687     setOperationAction(ISD::MULHS,              MVT::v4i16, Legal);
688     setOperationAction(ISD::MUL,                MVT::v4i16, Legal);
689
690     setOperationAction(ISD::AND,                MVT::v8i8,  Promote);
691     AddPromotedToType (ISD::AND,                MVT::v8i8,  MVT::v1i64);
692     setOperationAction(ISD::AND,                MVT::v4i16, Promote);
693     AddPromotedToType (ISD::AND,                MVT::v4i16, MVT::v1i64);
694     setOperationAction(ISD::AND,                MVT::v2i32, Promote);
695     AddPromotedToType (ISD::AND,                MVT::v2i32, MVT::v1i64);
696     setOperationAction(ISD::AND,                MVT::v1i64, Legal);
697
698     setOperationAction(ISD::OR,                 MVT::v8i8,  Promote);
699     AddPromotedToType (ISD::OR,                 MVT::v8i8,  MVT::v1i64);
700     setOperationAction(ISD::OR,                 MVT::v4i16, Promote);
701     AddPromotedToType (ISD::OR,                 MVT::v4i16, MVT::v1i64);
702     setOperationAction(ISD::OR,                 MVT::v2i32, Promote);
703     AddPromotedToType (ISD::OR,                 MVT::v2i32, MVT::v1i64);
704     setOperationAction(ISD::OR,                 MVT::v1i64, Legal);
705
706     setOperationAction(ISD::XOR,                MVT::v8i8,  Promote);
707     AddPromotedToType (ISD::XOR,                MVT::v8i8,  MVT::v1i64);
708     setOperationAction(ISD::XOR,                MVT::v4i16, Promote);
709     AddPromotedToType (ISD::XOR,                MVT::v4i16, MVT::v1i64);
710     setOperationAction(ISD::XOR,                MVT::v2i32, Promote);
711     AddPromotedToType (ISD::XOR,                MVT::v2i32, MVT::v1i64);
712     setOperationAction(ISD::XOR,                MVT::v1i64, Legal);
713
714     setOperationAction(ISD::LOAD,               MVT::v8i8,  Promote);
715     AddPromotedToType (ISD::LOAD,               MVT::v8i8,  MVT::v1i64);
716     setOperationAction(ISD::LOAD,               MVT::v4i16, Promote);
717     AddPromotedToType (ISD::LOAD,               MVT::v4i16, MVT::v1i64);
718     setOperationAction(ISD::LOAD,               MVT::v2i32, Promote);
719     AddPromotedToType (ISD::LOAD,               MVT::v2i32, MVT::v1i64);
720     setOperationAction(ISD::LOAD,               MVT::v2f32, Promote);
721     AddPromotedToType (ISD::LOAD,               MVT::v2f32, MVT::v1i64);
722     setOperationAction(ISD::LOAD,               MVT::v1i64, Legal);
723
724     setOperationAction(ISD::BUILD_VECTOR,       MVT::v8i8,  Custom);
725     setOperationAction(ISD::BUILD_VECTOR,       MVT::v4i16, Custom);
726     setOperationAction(ISD::BUILD_VECTOR,       MVT::v2i32, Custom);
727     setOperationAction(ISD::BUILD_VECTOR,       MVT::v2f32, Custom);
728     setOperationAction(ISD::BUILD_VECTOR,       MVT::v1i64, Custom);
729
730     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v8i8,  Custom);
731     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v4i16, Custom);
732     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v2i32, Custom);
733     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v1i64, Custom);
734
735     setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v2f32, Custom);
736     setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v8i8,  Custom);
737     setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v4i16, Custom);
738     setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v1i64, Custom);
739
740     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4i16, Custom);
741
742     setOperationAction(ISD::SELECT,             MVT::v8i8, Promote);
743     setOperationAction(ISD::SELECT,             MVT::v4i16, Promote);
744     setOperationAction(ISD::SELECT,             MVT::v2i32, Promote);
745     setOperationAction(ISD::SELECT,             MVT::v1i64, Custom);
746     setOperationAction(ISD::VSETCC,             MVT::v8i8, Custom);
747     setOperationAction(ISD::VSETCC,             MVT::v4i16, Custom);
748     setOperationAction(ISD::VSETCC,             MVT::v2i32, Custom);
749   }
750
751   if (!UseSoftFloat && Subtarget->hasSSE1()) {
752     addRegisterClass(MVT::v4f32, X86::VR128RegisterClass);
753
754     setOperationAction(ISD::FADD,               MVT::v4f32, Legal);
755     setOperationAction(ISD::FSUB,               MVT::v4f32, Legal);
756     setOperationAction(ISD::FMUL,               MVT::v4f32, Legal);
757     setOperationAction(ISD::FDIV,               MVT::v4f32, Legal);
758     setOperationAction(ISD::FSQRT,              MVT::v4f32, Legal);
759     setOperationAction(ISD::FNEG,               MVT::v4f32, Custom);
760     setOperationAction(ISD::LOAD,               MVT::v4f32, Legal);
761     setOperationAction(ISD::BUILD_VECTOR,       MVT::v4f32, Custom);
762     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v4f32, Custom);
763     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
764     setOperationAction(ISD::SELECT,             MVT::v4f32, Custom);
765     setOperationAction(ISD::VSETCC,             MVT::v4f32, Custom);
766   }
767
768   if (!UseSoftFloat && Subtarget->hasSSE2()) {
769     addRegisterClass(MVT::v2f64, X86::VR128RegisterClass);
770
771     // FIXME: Unfortunately -soft-float and -no-implicit-float means XMM
772     // registers cannot be used even for integer operations.
773     addRegisterClass(MVT::v16i8, X86::VR128RegisterClass);
774     addRegisterClass(MVT::v8i16, X86::VR128RegisterClass);
775     addRegisterClass(MVT::v4i32, X86::VR128RegisterClass);
776     addRegisterClass(MVT::v2i64, X86::VR128RegisterClass);
777
778     setOperationAction(ISD::ADD,                MVT::v16i8, Legal);
779     setOperationAction(ISD::ADD,                MVT::v8i16, Legal);
780     setOperationAction(ISD::ADD,                MVT::v4i32, Legal);
781     setOperationAction(ISD::ADD,                MVT::v2i64, Legal);
782     setOperationAction(ISD::MUL,                MVT::v2i64, Custom);
783     setOperationAction(ISD::SUB,                MVT::v16i8, Legal);
784     setOperationAction(ISD::SUB,                MVT::v8i16, Legal);
785     setOperationAction(ISD::SUB,                MVT::v4i32, Legal);
786     setOperationAction(ISD::SUB,                MVT::v2i64, Legal);
787     setOperationAction(ISD::MUL,                MVT::v8i16, Legal);
788     setOperationAction(ISD::FADD,               MVT::v2f64, Legal);
789     setOperationAction(ISD::FSUB,               MVT::v2f64, Legal);
790     setOperationAction(ISD::FMUL,               MVT::v2f64, Legal);
791     setOperationAction(ISD::FDIV,               MVT::v2f64, Legal);
792     setOperationAction(ISD::FSQRT,              MVT::v2f64, Legal);
793     setOperationAction(ISD::FNEG,               MVT::v2f64, Custom);
794
795     setOperationAction(ISD::VSETCC,             MVT::v2f64, Custom);
796     setOperationAction(ISD::VSETCC,             MVT::v16i8, Custom);
797     setOperationAction(ISD::VSETCC,             MVT::v8i16, Custom);
798     setOperationAction(ISD::VSETCC,             MVT::v4i32, Custom);
799
800     setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v16i8, Custom);
801     setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v8i16, Custom);
802     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v8i16, Custom);
803     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4i32, Custom);
804     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4f32, Custom);
805
806     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v2f64, Custom);
807     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v2i64, Custom);
808     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v16i8, Custom);
809     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v8i16, Custom);
810     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v4i32, Custom);
811
812     // Custom lower build_vector, vector_shuffle, and extract_vector_elt.
813     for (unsigned i = (unsigned)MVT::v16i8; i != (unsigned)MVT::v2i64; ++i) {
814       EVT VT = (MVT::SimpleValueType)i;
815       // Do not attempt to custom lower non-power-of-2 vectors
816       if (!isPowerOf2_32(VT.getVectorNumElements()))
817         continue;
818       // Do not attempt to custom lower non-128-bit vectors
819       if (!VT.is128BitVector())
820         continue;
821       setOperationAction(ISD::BUILD_VECTOR,
822                          VT.getSimpleVT().SimpleTy, Custom);
823       setOperationAction(ISD::VECTOR_SHUFFLE,
824                          VT.getSimpleVT().SimpleTy, Custom);
825       setOperationAction(ISD::EXTRACT_VECTOR_ELT,
826                          VT.getSimpleVT().SimpleTy, Custom);
827     }
828
829     setOperationAction(ISD::BUILD_VECTOR,       MVT::v2f64, Custom);
830     setOperationAction(ISD::BUILD_VECTOR,       MVT::v2i64, Custom);
831     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v2f64, Custom);
832     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v2i64, Custom);
833     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2f64, Custom);
834     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Custom);
835
836     if (Subtarget->is64Bit()) {
837       setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2i64, Custom);
838       setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
839     }
840
841     // Promote v16i8, v8i16, v4i32 load, select, and, or, xor to v2i64.
842     for (unsigned i = (unsigned)MVT::v16i8; i != (unsigned)MVT::v2i64; i++) {
843       MVT::SimpleValueType SVT = (MVT::SimpleValueType)i;
844       EVT VT = SVT;
845
846       // Do not attempt to promote non-128-bit vectors
847       if (!VT.is128BitVector()) {
848         continue;
849       }
850       setOperationAction(ISD::AND,    SVT, Promote);
851       AddPromotedToType (ISD::AND,    SVT, MVT::v2i64);
852       setOperationAction(ISD::OR,     SVT, Promote);
853       AddPromotedToType (ISD::OR,     SVT, MVT::v2i64);
854       setOperationAction(ISD::XOR,    SVT, Promote);
855       AddPromotedToType (ISD::XOR,    SVT, MVT::v2i64);
856       setOperationAction(ISD::LOAD,   SVT, Promote);
857       AddPromotedToType (ISD::LOAD,   SVT, MVT::v2i64);
858       setOperationAction(ISD::SELECT, SVT, Promote);
859       AddPromotedToType (ISD::SELECT, SVT, MVT::v2i64);
860     }
861
862     setTruncStoreAction(MVT::f64, MVT::f32, Expand);
863
864     // Custom lower v2i64 and v2f64 selects.
865     setOperationAction(ISD::LOAD,               MVT::v2f64, Legal);
866     setOperationAction(ISD::LOAD,               MVT::v2i64, Legal);
867     setOperationAction(ISD::SELECT,             MVT::v2f64, Custom);
868     setOperationAction(ISD::SELECT,             MVT::v2i64, Custom);
869
870     setOperationAction(ISD::FP_TO_SINT,         MVT::v4i32, Legal);
871     setOperationAction(ISD::SINT_TO_FP,         MVT::v4i32, Legal);
872     if (!DisableMMX && Subtarget->hasMMX()) {
873       setOperationAction(ISD::FP_TO_SINT,         MVT::v2i32, Custom);
874       setOperationAction(ISD::SINT_TO_FP,         MVT::v2i32, Custom);
875     }
876   }
877
878   if (Subtarget->hasSSE41()) {
879     // FIXME: Do we need to handle scalar-to-vector here?
880     setOperationAction(ISD::MUL,                MVT::v4i32, Legal);
881
882     // i8 and i16 vectors are custom , because the source register and source
883     // source memory operand types are not the same width.  f32 vectors are
884     // custom since the immediate controlling the insert encodes additional
885     // information.
886     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v16i8, Custom);
887     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v8i16, Custom);
888     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4i32, Custom);
889     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4f32, Custom);
890
891     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i8, Custom);
892     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i16, Custom);
893     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i32, Custom);
894     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
895
896     if (Subtarget->is64Bit()) {
897       setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2i64, Legal);
898       setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Legal);
899     }
900   }
901
902   if (Subtarget->hasSSE42()) {
903     setOperationAction(ISD::VSETCC,             MVT::v2i64, Custom);
904   }
905
906   if (!UseSoftFloat && Subtarget->hasAVX()) {
907     addRegisterClass(MVT::v8f32, X86::VR256RegisterClass);
908     addRegisterClass(MVT::v4f64, X86::VR256RegisterClass);
909     addRegisterClass(MVT::v8i32, X86::VR256RegisterClass);
910     addRegisterClass(MVT::v4i64, X86::VR256RegisterClass);
911
912     setOperationAction(ISD::LOAD,               MVT::v8f32, Legal);
913     setOperationAction(ISD::LOAD,               MVT::v8i32, Legal);
914     setOperationAction(ISD::LOAD,               MVT::v4f64, Legal);
915     setOperationAction(ISD::LOAD,               MVT::v4i64, Legal);
916     setOperationAction(ISD::FADD,               MVT::v8f32, Legal);
917     setOperationAction(ISD::FSUB,               MVT::v8f32, Legal);
918     setOperationAction(ISD::FMUL,               MVT::v8f32, Legal);
919     setOperationAction(ISD::FDIV,               MVT::v8f32, Legal);
920     setOperationAction(ISD::FSQRT,              MVT::v8f32, Legal);
921     setOperationAction(ISD::FNEG,               MVT::v8f32, Custom);
922     //setOperationAction(ISD::BUILD_VECTOR,       MVT::v8f32, Custom);
923     //setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v8f32, Custom);
924     //setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8f32, Custom);
925     //setOperationAction(ISD::SELECT,             MVT::v8f32, Custom);
926     //setOperationAction(ISD::VSETCC,             MVT::v8f32, Custom);
927
928     // Operations to consider commented out -v16i16 v32i8
929     //setOperationAction(ISD::ADD,                MVT::v16i16, Legal);
930     setOperationAction(ISD::ADD,                MVT::v8i32, Custom);
931     setOperationAction(ISD::ADD,                MVT::v4i64, Custom);
932     //setOperationAction(ISD::SUB,                MVT::v32i8, Legal);
933     //setOperationAction(ISD::SUB,                MVT::v16i16, Legal);
934     setOperationAction(ISD::SUB,                MVT::v8i32, Custom);
935     setOperationAction(ISD::SUB,                MVT::v4i64, Custom);
936     //setOperationAction(ISD::MUL,                MVT::v16i16, Legal);
937     setOperationAction(ISD::FADD,               MVT::v4f64, Legal);
938     setOperationAction(ISD::FSUB,               MVT::v4f64, Legal);
939     setOperationAction(ISD::FMUL,               MVT::v4f64, Legal);
940     setOperationAction(ISD::FDIV,               MVT::v4f64, Legal);
941     setOperationAction(ISD::FSQRT,              MVT::v4f64, Legal);
942     setOperationAction(ISD::FNEG,               MVT::v4f64, Custom);
943
944     setOperationAction(ISD::VSETCC,             MVT::v4f64, Custom);
945     // setOperationAction(ISD::VSETCC,             MVT::v32i8, Custom);
946     // setOperationAction(ISD::VSETCC,             MVT::v16i16, Custom);
947     setOperationAction(ISD::VSETCC,             MVT::v8i32, Custom);
948
949     // setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v32i8, Custom);
950     // setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v16i16, Custom);
951     // setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v16i16, Custom);
952     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v8i32, Custom);
953     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v8f32, Custom);
954
955     setOperationAction(ISD::BUILD_VECTOR,       MVT::v4f64, Custom);
956     setOperationAction(ISD::BUILD_VECTOR,       MVT::v4i64, Custom);
957     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v4f64, Custom);
958     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v4i64, Custom);
959     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4f64, Custom);
960     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f64, Custom);
961
962 #if 0
963     // Not sure we want to do this since there are no 256-bit integer
964     // operations in AVX
965
966     // Custom lower build_vector, vector_shuffle, and extract_vector_elt.
967     // This includes 256-bit vectors
968     for (unsigned i = (unsigned)MVT::v16i8; i != (unsigned)MVT::v4i64; ++i) {
969       EVT VT = (MVT::SimpleValueType)i;
970
971       // Do not attempt to custom lower non-power-of-2 vectors
972       if (!isPowerOf2_32(VT.getVectorNumElements()))
973         continue;
974
975       setOperationAction(ISD::BUILD_VECTOR,       VT, Custom);
976       setOperationAction(ISD::VECTOR_SHUFFLE,     VT, Custom);
977       setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
978     }
979
980     if (Subtarget->is64Bit()) {
981       setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4i64, Custom);
982       setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i64, Custom);
983     }
984 #endif
985
986 #if 0
987     // Not sure we want to do this since there are no 256-bit integer
988     // operations in AVX
989
990     // Promote v32i8, v16i16, v8i32 load, select, and, or, xor to v4i64.
991     // Including 256-bit vectors
992     for (unsigned i = (unsigned)MVT::v16i8; i != (unsigned)MVT::v4i64; i++) {
993       EVT VT = (MVT::SimpleValueType)i;
994
995       if (!VT.is256BitVector()) {
996         continue;
997       }
998       setOperationAction(ISD::AND,    VT, Promote);
999       AddPromotedToType (ISD::AND,    VT, MVT::v4i64);
1000       setOperationAction(ISD::OR,     VT, Promote);
1001       AddPromotedToType (ISD::OR,     VT, MVT::v4i64);
1002       setOperationAction(ISD::XOR,    VT, Promote);
1003       AddPromotedToType (ISD::XOR,    VT, MVT::v4i64);
1004       setOperationAction(ISD::LOAD,   VT, Promote);
1005       AddPromotedToType (ISD::LOAD,   VT, MVT::v4i64);
1006       setOperationAction(ISD::SELECT, VT, Promote);
1007       AddPromotedToType (ISD::SELECT, VT, MVT::v4i64);
1008     }
1009
1010     setTruncStoreAction(MVT::f64, MVT::f32, Expand);
1011 #endif
1012   }
1013
1014   // We want to custom lower some of our intrinsics.
1015   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
1016
1017   // Add/Sub/Mul with overflow operations are custom lowered.
1018   setOperationAction(ISD::SADDO, MVT::i32, Custom);
1019   setOperationAction(ISD::SADDO, MVT::i64, Custom);
1020   setOperationAction(ISD::UADDO, MVT::i32, Custom);
1021   setOperationAction(ISD::UADDO, MVT::i64, Custom);
1022   setOperationAction(ISD::SSUBO, MVT::i32, Custom);
1023   setOperationAction(ISD::SSUBO, MVT::i64, Custom);
1024   setOperationAction(ISD::USUBO, MVT::i32, Custom);
1025   setOperationAction(ISD::USUBO, MVT::i64, Custom);
1026   setOperationAction(ISD::SMULO, MVT::i32, Custom);
1027   setOperationAction(ISD::SMULO, MVT::i64, Custom);
1028
1029   if (!Subtarget->is64Bit()) {
1030     // These libcalls are not available in 32-bit.
1031     setLibcallName(RTLIB::SHL_I128, 0);
1032     setLibcallName(RTLIB::SRL_I128, 0);
1033     setLibcallName(RTLIB::SRA_I128, 0);
1034   }
1035
1036   // We have target-specific dag combine patterns for the following nodes:
1037   setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
1038   setTargetDAGCombine(ISD::BUILD_VECTOR);
1039   setTargetDAGCombine(ISD::SELECT);
1040   setTargetDAGCombine(ISD::SHL);
1041   setTargetDAGCombine(ISD::SRA);
1042   setTargetDAGCombine(ISD::SRL);
1043   setTargetDAGCombine(ISD::OR);
1044   setTargetDAGCombine(ISD::STORE);
1045   setTargetDAGCombine(ISD::MEMBARRIER);
1046   setTargetDAGCombine(ISD::ZERO_EXTEND);
1047   if (Subtarget->is64Bit())
1048     setTargetDAGCombine(ISD::MUL);
1049
1050   computeRegisterProperties();
1051
1052   // FIXME: These should be based on subtarget info. Plus, the values should
1053   // be smaller when we are in optimizing for size mode.
1054   maxStoresPerMemset = 16; // For @llvm.memset -> sequence of stores
1055   maxStoresPerMemcpy = 16; // For @llvm.memcpy -> sequence of stores
1056   maxStoresPerMemmove = 3; // For @llvm.memmove -> sequence of stores
1057   setPrefLoopAlignment(16);
1058   benefitFromCodePlacementOpt = true;
1059 }
1060
1061
1062 MVT::SimpleValueType X86TargetLowering::getSetCCResultType(EVT VT) const {
1063   return MVT::i8;
1064 }
1065
1066
1067 /// getMaxByValAlign - Helper for getByValTypeAlignment to determine
1068 /// the desired ByVal argument alignment.
1069 static void getMaxByValAlign(const Type *Ty, unsigned &MaxAlign) {
1070   if (MaxAlign == 16)
1071     return;
1072   if (const VectorType *VTy = dyn_cast<VectorType>(Ty)) {
1073     if (VTy->getBitWidth() == 128)
1074       MaxAlign = 16;
1075   } else if (const ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
1076     unsigned EltAlign = 0;
1077     getMaxByValAlign(ATy->getElementType(), EltAlign);
1078     if (EltAlign > MaxAlign)
1079       MaxAlign = EltAlign;
1080   } else if (const StructType *STy = dyn_cast<StructType>(Ty)) {
1081     for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
1082       unsigned EltAlign = 0;
1083       getMaxByValAlign(STy->getElementType(i), EltAlign);
1084       if (EltAlign > MaxAlign)
1085         MaxAlign = EltAlign;
1086       if (MaxAlign == 16)
1087         break;
1088     }
1089   }
1090   return;
1091 }
1092
1093 /// getByValTypeAlignment - Return the desired alignment for ByVal aggregate
1094 /// function arguments in the caller parameter area. For X86, aggregates
1095 /// that contain SSE vectors are placed at 16-byte boundaries while the rest
1096 /// are at 4-byte boundaries.
1097 unsigned X86TargetLowering::getByValTypeAlignment(const Type *Ty) const {
1098   if (Subtarget->is64Bit()) {
1099     // Max of 8 and alignment of type.
1100     unsigned TyAlign = TD->getABITypeAlignment(Ty);
1101     if (TyAlign > 8)
1102       return TyAlign;
1103     return 8;
1104   }
1105
1106   unsigned Align = 4;
1107   if (Subtarget->hasSSE1())
1108     getMaxByValAlign(Ty, Align);
1109   return Align;
1110 }
1111
1112 /// getOptimalMemOpType - Returns the target specific optimal type for load
1113 /// and store operations as a result of memset, memcpy, and memmove
1114 /// lowering. It returns MVT::iAny if SelectionDAG should be responsible for
1115 /// determining it.
1116 EVT
1117 X86TargetLowering::getOptimalMemOpType(uint64_t Size, unsigned Align,
1118                                        bool isSrcConst, bool isSrcStr,
1119                                        SelectionDAG &DAG) const {
1120   // FIXME: This turns off use of xmm stores for memset/memcpy on targets like
1121   // linux.  This is because the stack realignment code can't handle certain
1122   // cases like PR2962.  This should be removed when PR2962 is fixed.
1123   const Function *F = DAG.getMachineFunction().getFunction();
1124   bool NoImplicitFloatOps = F->hasFnAttr(Attribute::NoImplicitFloat);
1125   if (!NoImplicitFloatOps && Subtarget->getStackAlignment() >= 16) {
1126     if ((isSrcConst || isSrcStr) && Subtarget->hasSSE2() && Size >= 16)
1127       return MVT::v4i32;
1128     if ((isSrcConst || isSrcStr) && Subtarget->hasSSE1() && Size >= 16)
1129       return MVT::v4f32;
1130   }
1131   if (Subtarget->is64Bit() && Size >= 8)
1132     return MVT::i64;
1133   return MVT::i32;
1134 }
1135
1136 /// getJumpTableEncoding - Return the entry encoding for a jump table in the
1137 /// current function.  The returned value is a member of the
1138 /// MachineJumpTableInfo::JTEntryKind enum.
1139 unsigned X86TargetLowering::getJumpTableEncoding() const {
1140   // In GOT pic mode, each entry in the jump table is emitted as a @GOTOFF
1141   // symbol.
1142   if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1143       Subtarget->isPICStyleGOT())
1144     return MachineJumpTableInfo::EK_Custom32;
1145   
1146   // Otherwise, use the normal jump table encoding heuristics.
1147   return TargetLowering::getJumpTableEncoding();
1148 }
1149
1150 /// getPICBaseSymbol - Return the X86-32 PIC base.
1151 MCSymbol *
1152 X86TargetLowering::getPICBaseSymbol(const MachineFunction *MF,
1153                                     MCContext &Ctx) const {
1154   const MCAsmInfo &MAI = *getTargetMachine().getMCAsmInfo();
1155   return Ctx.GetOrCreateTemporarySymbol(Twine(MAI.getPrivateGlobalPrefix())+
1156                                         Twine(MF->getFunctionNumber())+"$pb");
1157 }
1158
1159
1160 const MCExpr *
1161 X86TargetLowering::LowerCustomJumpTableEntry(const MachineJumpTableInfo *MJTI,
1162                                              const MachineBasicBlock *MBB,
1163                                              unsigned uid,MCContext &Ctx) const{
1164   assert(getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1165          Subtarget->isPICStyleGOT());
1166   // In 32-bit ELF systems, our jump table entries are formed with @GOTOFF
1167   // entries.
1168   return X86MCTargetExpr::Create(MBB->getSymbol(),
1169                                  X86MCTargetExpr::GOTOFF, Ctx);
1170 }
1171
1172 /// getPICJumpTableRelocaBase - Returns relocation base for the given PIC
1173 /// jumptable.
1174 SDValue X86TargetLowering::getPICJumpTableRelocBase(SDValue Table,
1175                                                     SelectionDAG &DAG) const {
1176   if (!Subtarget->is64Bit())
1177     // This doesn't have DebugLoc associated with it, but is not really the
1178     // same as a Register.
1179     return DAG.getNode(X86ISD::GlobalBaseReg, DebugLoc::getUnknownLoc(),
1180                        getPointerTy());
1181   return Table;
1182 }
1183
1184 /// getPICJumpTableRelocBaseExpr - This returns the relocation base for the
1185 /// given PIC jumptable, the same as getPICJumpTableRelocBase, but as an
1186 /// MCExpr.
1187 const MCExpr *X86TargetLowering::
1188 getPICJumpTableRelocBaseExpr(const MachineFunction *MF, unsigned JTI,
1189                              MCContext &Ctx) const {
1190   // X86-64 uses RIP relative addressing based on the jump table label.
1191   if (Subtarget->isPICStyleRIPRel())
1192     return TargetLowering::getPICJumpTableRelocBaseExpr(MF, JTI, Ctx);
1193
1194   // Otherwise, the reference is relative to the PIC base.
1195   return MCSymbolRefExpr::Create(getPICBaseSymbol(MF, Ctx), Ctx);
1196 }
1197
1198 /// getFunctionAlignment - Return the Log2 alignment of this function.
1199 unsigned X86TargetLowering::getFunctionAlignment(const Function *F) const {
1200   return F->hasFnAttr(Attribute::OptimizeForSize) ? 0 : 4;
1201 }
1202
1203 //===----------------------------------------------------------------------===//
1204 //               Return Value Calling Convention Implementation
1205 //===----------------------------------------------------------------------===//
1206
1207 #include "X86GenCallingConv.inc"
1208
1209 bool 
1210 X86TargetLowering::CanLowerReturn(CallingConv::ID CallConv, bool isVarArg,
1211                         const SmallVectorImpl<EVT> &OutTys,
1212                         const SmallVectorImpl<ISD::ArgFlagsTy> &ArgsFlags,
1213                         SelectionDAG &DAG) {
1214   SmallVector<CCValAssign, 16> RVLocs;
1215   CCState CCInfo(CallConv, isVarArg, getTargetMachine(),
1216                  RVLocs, *DAG.getContext());
1217   return CCInfo.CheckReturn(OutTys, ArgsFlags, RetCC_X86);
1218 }
1219
1220 SDValue
1221 X86TargetLowering::LowerReturn(SDValue Chain,
1222                                CallingConv::ID CallConv, bool isVarArg,
1223                                const SmallVectorImpl<ISD::OutputArg> &Outs,
1224                                DebugLoc dl, SelectionDAG &DAG) {
1225
1226   SmallVector<CCValAssign, 16> RVLocs;
1227   CCState CCInfo(CallConv, isVarArg, getTargetMachine(),
1228                  RVLocs, *DAG.getContext());
1229   CCInfo.AnalyzeReturn(Outs, RetCC_X86);
1230
1231   // Add the regs to the liveout set for the function.
1232   MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo();
1233   for (unsigned i = 0; i != RVLocs.size(); ++i)
1234     if (RVLocs[i].isRegLoc() && !MRI.isLiveOut(RVLocs[i].getLocReg()))
1235       MRI.addLiveOut(RVLocs[i].getLocReg());
1236
1237   SDValue Flag;
1238
1239   SmallVector<SDValue, 6> RetOps;
1240   RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
1241   // Operand #1 = Bytes To Pop
1242   RetOps.push_back(DAG.getTargetConstant(getBytesToPopOnReturn(), MVT::i16));
1243
1244   // Copy the result values into the output registers.
1245   for (unsigned i = 0; i != RVLocs.size(); ++i) {
1246     CCValAssign &VA = RVLocs[i];
1247     assert(VA.isRegLoc() && "Can only return in registers!");
1248     SDValue ValToCopy = Outs[i].Val;
1249
1250     // Returns in ST0/ST1 are handled specially: these are pushed as operands to
1251     // the RET instruction and handled by the FP Stackifier.
1252     if (VA.getLocReg() == X86::ST0 ||
1253         VA.getLocReg() == X86::ST1) {
1254       // If this is a copy from an xmm register to ST(0), use an FPExtend to
1255       // change the value to the FP stack register class.
1256       if (isScalarFPTypeInSSEReg(VA.getValVT()))
1257         ValToCopy = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f80, ValToCopy);
1258       RetOps.push_back(ValToCopy);
1259       // Don't emit a copytoreg.
1260       continue;
1261     }
1262
1263     // 64-bit vector (MMX) values are returned in XMM0 / XMM1 except for v1i64
1264     // which is returned in RAX / RDX.
1265     if (Subtarget->is64Bit()) {
1266       EVT ValVT = ValToCopy.getValueType();
1267       if (ValVT.isVector() && ValVT.getSizeInBits() == 64) {
1268         ValToCopy = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::i64, ValToCopy);
1269         if (VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1)
1270           ValToCopy = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64, ValToCopy);
1271       }
1272     }
1273
1274     Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), ValToCopy, Flag);
1275     Flag = Chain.getValue(1);
1276   }
1277
1278   // The x86-64 ABI for returning structs by value requires that we copy
1279   // the sret argument into %rax for the return. We saved the argument into
1280   // a virtual register in the entry block, so now we copy the value out
1281   // and into %rax.
1282   if (Subtarget->is64Bit() &&
1283       DAG.getMachineFunction().getFunction()->hasStructRetAttr()) {
1284     MachineFunction &MF = DAG.getMachineFunction();
1285     X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1286     unsigned Reg = FuncInfo->getSRetReturnReg();
1287     if (!Reg) {
1288       Reg = MRI.createVirtualRegister(getRegClassFor(MVT::i64));
1289       FuncInfo->setSRetReturnReg(Reg);
1290     }
1291     SDValue Val = DAG.getCopyFromReg(Chain, dl, Reg, getPointerTy());
1292
1293     Chain = DAG.getCopyToReg(Chain, dl, X86::RAX, Val, Flag);
1294     Flag = Chain.getValue(1);
1295
1296     // RAX now acts like a return value.
1297     MRI.addLiveOut(X86::RAX);
1298   }
1299
1300   RetOps[0] = Chain;  // Update chain.
1301
1302   // Add the flag if we have it.
1303   if (Flag.getNode())
1304     RetOps.push_back(Flag);
1305
1306   return DAG.getNode(X86ISD::RET_FLAG, dl,
1307                      MVT::Other, &RetOps[0], RetOps.size());
1308 }
1309
1310 /// LowerCallResult - Lower the result values of a call into the
1311 /// appropriate copies out of appropriate physical registers.
1312 ///
1313 SDValue
1314 X86TargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
1315                                    CallingConv::ID CallConv, bool isVarArg,
1316                                    const SmallVectorImpl<ISD::InputArg> &Ins,
1317                                    DebugLoc dl, SelectionDAG &DAG,
1318                                    SmallVectorImpl<SDValue> &InVals) {
1319
1320   // Assign locations to each value returned by this call.
1321   SmallVector<CCValAssign, 16> RVLocs;
1322   bool Is64Bit = Subtarget->is64Bit();
1323   CCState CCInfo(CallConv, isVarArg, getTargetMachine(),
1324                  RVLocs, *DAG.getContext());
1325   CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
1326
1327   // Copy all of the result registers out of their specified physreg.
1328   for (unsigned i = 0; i != RVLocs.size(); ++i) {
1329     CCValAssign &VA = RVLocs[i];
1330     EVT CopyVT = VA.getValVT();
1331
1332     // If this is x86-64, and we disabled SSE, we can't return FP values
1333     if ((CopyVT == MVT::f32 || CopyVT == MVT::f64) &&
1334         ((Is64Bit || Ins[i].Flags.isInReg()) && !Subtarget->hasSSE1())) {
1335       llvm_report_error("SSE register return with SSE disabled");
1336     }
1337
1338     // If this is a call to a function that returns an fp value on the floating
1339     // point stack, but where we prefer to use the value in xmm registers, copy
1340     // it out as F80 and use a truncate to move it from fp stack reg to xmm reg.
1341     if ((VA.getLocReg() == X86::ST0 ||
1342          VA.getLocReg() == X86::ST1) &&
1343         isScalarFPTypeInSSEReg(VA.getValVT())) {
1344       CopyVT = MVT::f80;
1345     }
1346
1347     SDValue Val;
1348     if (Is64Bit && CopyVT.isVector() && CopyVT.getSizeInBits() == 64) {
1349       // For x86-64, MMX values are returned in XMM0 / XMM1 except for v1i64.
1350       if (VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) {
1351         Chain = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(),
1352                                    MVT::v2i64, InFlag).getValue(1);
1353         Val = Chain.getValue(0);
1354         Val = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i64,
1355                           Val, DAG.getConstant(0, MVT::i64));
1356       } else {
1357         Chain = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(),
1358                                    MVT::i64, InFlag).getValue(1);
1359         Val = Chain.getValue(0);
1360       }
1361       Val = DAG.getNode(ISD::BIT_CONVERT, dl, CopyVT, Val);
1362     } else {
1363       Chain = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(),
1364                                  CopyVT, InFlag).getValue(1);
1365       Val = Chain.getValue(0);
1366     }
1367     InFlag = Chain.getValue(2);
1368
1369     if (CopyVT != VA.getValVT()) {
1370       // Round the F80 the right size, which also moves to the appropriate xmm
1371       // register.
1372       Val = DAG.getNode(ISD::FP_ROUND, dl, VA.getValVT(), Val,
1373                         // This truncation won't change the value.
1374                         DAG.getIntPtrConstant(1));
1375     }
1376
1377     InVals.push_back(Val);
1378   }
1379
1380   return Chain;
1381 }
1382
1383
1384 //===----------------------------------------------------------------------===//
1385 //                C & StdCall & Fast Calling Convention implementation
1386 //===----------------------------------------------------------------------===//
1387 //  StdCall calling convention seems to be standard for many Windows' API
1388 //  routines and around. It differs from C calling convention just a little:
1389 //  callee should clean up the stack, not caller. Symbols should be also
1390 //  decorated in some fancy way :) It doesn't support any vector arguments.
1391 //  For info on fast calling convention see Fast Calling Convention (tail call)
1392 //  implementation LowerX86_32FastCCCallTo.
1393
1394 /// CallIsStructReturn - Determines whether a call uses struct return
1395 /// semantics.
1396 static bool CallIsStructReturn(const SmallVectorImpl<ISD::OutputArg> &Outs) {
1397   if (Outs.empty())
1398     return false;
1399
1400   return Outs[0].Flags.isSRet();
1401 }
1402
1403 /// ArgsAreStructReturn - Determines whether a function uses struct
1404 /// return semantics.
1405 static bool
1406 ArgsAreStructReturn(const SmallVectorImpl<ISD::InputArg> &Ins) {
1407   if (Ins.empty())
1408     return false;
1409
1410   return Ins[0].Flags.isSRet();
1411 }
1412
1413 /// IsCalleePop - Determines whether the callee is required to pop its
1414 /// own arguments. Callee pop is necessary to support tail calls.
1415 bool X86TargetLowering::IsCalleePop(bool IsVarArg, CallingConv::ID CallingConv){
1416   if (IsVarArg)
1417     return false;
1418
1419   switch (CallingConv) {
1420   default:
1421     return false;
1422   case CallingConv::X86_StdCall:
1423     return !Subtarget->is64Bit();
1424   case CallingConv::X86_FastCall:
1425     return !Subtarget->is64Bit();
1426   case CallingConv::Fast:
1427     return GuaranteedTailCallOpt;
1428   case CallingConv::GHC:
1429     return GuaranteedTailCallOpt;
1430   }
1431 }
1432
1433 /// CCAssignFnForNode - Selects the correct CCAssignFn for a the
1434 /// given CallingConvention value.
1435 CCAssignFn *X86TargetLowering::CCAssignFnForNode(CallingConv::ID CC) const {
1436   if (Subtarget->is64Bit()) {
1437     if (CC == CallingConv::GHC)
1438       return CC_X86_64_GHC;
1439     else if (Subtarget->isTargetWin64())
1440       return CC_X86_Win64_C;
1441     else
1442       return CC_X86_64_C;
1443   }
1444
1445   if (CC == CallingConv::X86_FastCall)
1446     return CC_X86_32_FastCall;
1447   else if (CC == CallingConv::Fast)
1448     return CC_X86_32_FastCC;
1449   else if (CC == CallingConv::GHC)
1450     return CC_X86_32_GHC;
1451   else
1452     return CC_X86_32_C;
1453 }
1454
1455 /// CreateCopyOfByValArgument - Make a copy of an aggregate at address specified
1456 /// by "Src" to address "Dst" with size and alignment information specified by
1457 /// the specific parameter attribute. The copy will be passed as a byval
1458 /// function parameter.
1459 static SDValue
1460 CreateCopyOfByValArgument(SDValue Src, SDValue Dst, SDValue Chain,
1461                           ISD::ArgFlagsTy Flags, SelectionDAG &DAG,
1462                           DebugLoc dl) {
1463   SDValue SizeNode     = DAG.getConstant(Flags.getByValSize(), MVT::i32);
1464   return DAG.getMemcpy(Chain, dl, Dst, Src, SizeNode, Flags.getByValAlign(),
1465                        /*AlwaysInline=*/true, NULL, 0, NULL, 0);
1466 }
1467
1468 /// IsTailCallConvention - Return true if the calling convention is one that
1469 /// supports tail call optimization.
1470 static bool IsTailCallConvention(CallingConv::ID CC) {
1471   return (CC == CallingConv::Fast || CC == CallingConv::GHC);
1472 }
1473
1474 /// FuncIsMadeTailCallSafe - Return true if the function is being made into
1475 /// a tailcall target by changing its ABI.
1476 static bool FuncIsMadeTailCallSafe(CallingConv::ID CC) {
1477   return GuaranteedTailCallOpt && IsTailCallConvention(CC);
1478 }
1479
1480 SDValue
1481 X86TargetLowering::LowerMemArgument(SDValue Chain,
1482                                     CallingConv::ID CallConv,
1483                                     const SmallVectorImpl<ISD::InputArg> &Ins,
1484                                     DebugLoc dl, SelectionDAG &DAG,
1485                                     const CCValAssign &VA,
1486                                     MachineFrameInfo *MFI,
1487                                     unsigned i) {
1488   // Create the nodes corresponding to a load from this parameter slot.
1489   ISD::ArgFlagsTy Flags = Ins[i].Flags;
1490   bool AlwaysUseMutable = FuncIsMadeTailCallSafe(CallConv);
1491   bool isImmutable = !AlwaysUseMutable && !Flags.isByVal();
1492   EVT ValVT;
1493
1494   // If value is passed by pointer we have address passed instead of the value
1495   // itself.
1496   if (VA.getLocInfo() == CCValAssign::Indirect)
1497     ValVT = VA.getLocVT();
1498   else
1499     ValVT = VA.getValVT();
1500
1501   // FIXME: For now, all byval parameter objects are marked mutable. This can be
1502   // changed with more analysis.
1503   // In case of tail call optimization mark all arguments mutable. Since they
1504   // could be overwritten by lowering of arguments in case of a tail call.
1505   if (Flags.isByVal()) {
1506     int FI = MFI->CreateFixedObject(Flags.getByValSize(),
1507                                     VA.getLocMemOffset(), isImmutable, false);
1508     return DAG.getFrameIndex(FI, getPointerTy());
1509   } else {
1510     int FI = MFI->CreateFixedObject(ValVT.getSizeInBits()/8,
1511                                     VA.getLocMemOffset(), isImmutable, false);
1512     SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
1513     return DAG.getLoad(ValVT, dl, Chain, FIN,
1514                        PseudoSourceValue::getFixedStack(FI), 0,
1515                        false, false, 0);
1516   }
1517 }
1518
1519 SDValue
1520 X86TargetLowering::LowerFormalArguments(SDValue Chain,
1521                                         CallingConv::ID CallConv,
1522                                         bool isVarArg,
1523                                       const SmallVectorImpl<ISD::InputArg> &Ins,
1524                                         DebugLoc dl,
1525                                         SelectionDAG &DAG,
1526                                         SmallVectorImpl<SDValue> &InVals) {
1527
1528   MachineFunction &MF = DAG.getMachineFunction();
1529   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1530
1531   const Function* Fn = MF.getFunction();
1532   if (Fn->hasExternalLinkage() &&
1533       Subtarget->isTargetCygMing() &&
1534       Fn->getName() == "main")
1535     FuncInfo->setForceFramePointer(true);
1536
1537   MachineFrameInfo *MFI = MF.getFrameInfo();
1538   bool Is64Bit = Subtarget->is64Bit();
1539   bool IsWin64 = Subtarget->isTargetWin64();
1540
1541   assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
1542          "Var args not supported with calling convention fastcc or ghc");
1543
1544   // Assign locations to all of the incoming arguments.
1545   SmallVector<CCValAssign, 16> ArgLocs;
1546   CCState CCInfo(CallConv, isVarArg, getTargetMachine(),
1547                  ArgLocs, *DAG.getContext());
1548   CCInfo.AnalyzeFormalArguments(Ins, CCAssignFnForNode(CallConv));
1549
1550   unsigned LastVal = ~0U;
1551   SDValue ArgValue;
1552   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
1553     CCValAssign &VA = ArgLocs[i];
1554     // TODO: If an arg is passed in two places (e.g. reg and stack), skip later
1555     // places.
1556     assert(VA.getValNo() != LastVal &&
1557            "Don't support value assigned to multiple locs yet");
1558     LastVal = VA.getValNo();
1559
1560     if (VA.isRegLoc()) {
1561       EVT RegVT = VA.getLocVT();
1562       TargetRegisterClass *RC = NULL;
1563       if (RegVT == MVT::i32)
1564         RC = X86::GR32RegisterClass;
1565       else if (Is64Bit && RegVT == MVT::i64)
1566         RC = X86::GR64RegisterClass;
1567       else if (RegVT == MVT::f32)
1568         RC = X86::FR32RegisterClass;
1569       else if (RegVT == MVT::f64)
1570         RC = X86::FR64RegisterClass;
1571       else if (RegVT.isVector() && RegVT.getSizeInBits() == 128)
1572         RC = X86::VR128RegisterClass;
1573       else if (RegVT.isVector() && RegVT.getSizeInBits() == 64)
1574         RC = X86::VR64RegisterClass;
1575       else
1576         llvm_unreachable("Unknown argument type!");
1577
1578       unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
1579       ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
1580
1581       // If this is an 8 or 16-bit value, it is really passed promoted to 32
1582       // bits.  Insert an assert[sz]ext to capture this, then truncate to the
1583       // right size.
1584       if (VA.getLocInfo() == CCValAssign::SExt)
1585         ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
1586                                DAG.getValueType(VA.getValVT()));
1587       else if (VA.getLocInfo() == CCValAssign::ZExt)
1588         ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
1589                                DAG.getValueType(VA.getValVT()));
1590       else if (VA.getLocInfo() == CCValAssign::BCvt)
1591         ArgValue = DAG.getNode(ISD::BIT_CONVERT, dl, VA.getValVT(), ArgValue);
1592
1593       if (VA.isExtInLoc()) {
1594         // Handle MMX values passed in XMM regs.
1595         if (RegVT.isVector()) {
1596           ArgValue = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i64,
1597                                  ArgValue, DAG.getConstant(0, MVT::i64));
1598           ArgValue = DAG.getNode(ISD::BIT_CONVERT, dl, VA.getValVT(), ArgValue);
1599         } else
1600           ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
1601       }
1602     } else {
1603       assert(VA.isMemLoc());
1604       ArgValue = LowerMemArgument(Chain, CallConv, Ins, dl, DAG, VA, MFI, i);
1605     }
1606
1607     // If value is passed via pointer - do a load.
1608     if (VA.getLocInfo() == CCValAssign::Indirect)
1609       ArgValue = DAG.getLoad(VA.getValVT(), dl, Chain, ArgValue, NULL, 0,
1610                              false, false, 0);
1611
1612     InVals.push_back(ArgValue);
1613   }
1614
1615   // The x86-64 ABI for returning structs by value requires that we copy
1616   // the sret argument into %rax for the return. Save the argument into
1617   // a virtual register so that we can access it from the return points.
1618   if (Is64Bit && MF.getFunction()->hasStructRetAttr()) {
1619     X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1620     unsigned Reg = FuncInfo->getSRetReturnReg();
1621     if (!Reg) {
1622       Reg = MF.getRegInfo().createVirtualRegister(getRegClassFor(MVT::i64));
1623       FuncInfo->setSRetReturnReg(Reg);
1624     }
1625     SDValue Copy = DAG.getCopyToReg(DAG.getEntryNode(), dl, Reg, InVals[0]);
1626     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Copy, Chain);
1627   }
1628
1629   unsigned StackSize = CCInfo.getNextStackOffset();
1630   // Align stack specially for tail calls.
1631   if (FuncIsMadeTailCallSafe(CallConv))
1632     StackSize = GetAlignedArgumentStackSize(StackSize, DAG);
1633
1634   // If the function takes variable number of arguments, make a frame index for
1635   // the start of the first vararg value... for expansion of llvm.va_start.
1636   if (isVarArg) {
1637     if (Is64Bit || CallConv != CallingConv::X86_FastCall) {
1638       VarArgsFrameIndex = MFI->CreateFixedObject(1, StackSize, true, false);
1639     }
1640     if (Is64Bit) {
1641       unsigned TotalNumIntRegs = 0, TotalNumXMMRegs = 0;
1642
1643       // FIXME: We should really autogenerate these arrays
1644       static const unsigned GPR64ArgRegsWin64[] = {
1645         X86::RCX, X86::RDX, X86::R8,  X86::R9
1646       };
1647       static const unsigned XMMArgRegsWin64[] = {
1648         X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3
1649       };
1650       static const unsigned GPR64ArgRegs64Bit[] = {
1651         X86::RDI, X86::RSI, X86::RDX, X86::RCX, X86::R8, X86::R9
1652       };
1653       static const unsigned XMMArgRegs64Bit[] = {
1654         X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
1655         X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
1656       };
1657       const unsigned *GPR64ArgRegs, *XMMArgRegs;
1658
1659       if (IsWin64) {
1660         TotalNumIntRegs = 4; TotalNumXMMRegs = 4;
1661         GPR64ArgRegs = GPR64ArgRegsWin64;
1662         XMMArgRegs = XMMArgRegsWin64;
1663       } else {
1664         TotalNumIntRegs = 6; TotalNumXMMRegs = 8;
1665         GPR64ArgRegs = GPR64ArgRegs64Bit;
1666         XMMArgRegs = XMMArgRegs64Bit;
1667       }
1668       unsigned NumIntRegs = CCInfo.getFirstUnallocated(GPR64ArgRegs,
1669                                                        TotalNumIntRegs);
1670       unsigned NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs,
1671                                                        TotalNumXMMRegs);
1672
1673       bool NoImplicitFloatOps = Fn->hasFnAttr(Attribute::NoImplicitFloat);
1674       assert(!(NumXMMRegs && !Subtarget->hasSSE1()) &&
1675              "SSE register cannot be used when SSE is disabled!");
1676       assert(!(NumXMMRegs && UseSoftFloat && NoImplicitFloatOps) &&
1677              "SSE register cannot be used when SSE is disabled!");
1678       if (UseSoftFloat || NoImplicitFloatOps || !Subtarget->hasSSE1())
1679         // Kernel mode asks for SSE to be disabled, so don't push them
1680         // on the stack.
1681         TotalNumXMMRegs = 0;
1682
1683       // For X86-64, if there are vararg parameters that are passed via
1684       // registers, then we must store them to their spots on the stack so they
1685       // may be loaded by deferencing the result of va_next.
1686       VarArgsGPOffset = NumIntRegs * 8;
1687       VarArgsFPOffset = TotalNumIntRegs * 8 + NumXMMRegs * 16;
1688       RegSaveFrameIndex = MFI->CreateStackObject(TotalNumIntRegs * 8 +
1689                                                  TotalNumXMMRegs * 16, 16,
1690                                                  false);
1691
1692       // Store the integer parameter registers.
1693       SmallVector<SDValue, 8> MemOps;
1694       SDValue RSFIN = DAG.getFrameIndex(RegSaveFrameIndex, getPointerTy());
1695       unsigned Offset = VarArgsGPOffset;
1696       for (; NumIntRegs != TotalNumIntRegs; ++NumIntRegs) {
1697         SDValue FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(), RSFIN,
1698                                   DAG.getIntPtrConstant(Offset));
1699         unsigned VReg = MF.addLiveIn(GPR64ArgRegs[NumIntRegs],
1700                                      X86::GR64RegisterClass);
1701         SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
1702         SDValue Store =
1703           DAG.getStore(Val.getValue(1), dl, Val, FIN,
1704                        PseudoSourceValue::getFixedStack(RegSaveFrameIndex),
1705                        Offset, false, false, 0);
1706         MemOps.push_back(Store);
1707         Offset += 8;
1708       }
1709
1710       if (TotalNumXMMRegs != 0 && NumXMMRegs != TotalNumXMMRegs) {
1711         // Now store the XMM (fp + vector) parameter registers.
1712         SmallVector<SDValue, 11> SaveXMMOps;
1713         SaveXMMOps.push_back(Chain);
1714
1715         unsigned AL = MF.addLiveIn(X86::AL, X86::GR8RegisterClass);
1716         SDValue ALVal = DAG.getCopyFromReg(DAG.getEntryNode(), dl, AL, MVT::i8);
1717         SaveXMMOps.push_back(ALVal);
1718
1719         SaveXMMOps.push_back(DAG.getIntPtrConstant(RegSaveFrameIndex));
1720         SaveXMMOps.push_back(DAG.getIntPtrConstant(VarArgsFPOffset));
1721
1722         for (; NumXMMRegs != TotalNumXMMRegs; ++NumXMMRegs) {
1723           unsigned VReg = MF.addLiveIn(XMMArgRegs[NumXMMRegs],
1724                                        X86::VR128RegisterClass);
1725           SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::v4f32);
1726           SaveXMMOps.push_back(Val);
1727         }
1728         MemOps.push_back(DAG.getNode(X86ISD::VASTART_SAVE_XMM_REGS, dl,
1729                                      MVT::Other,
1730                                      &SaveXMMOps[0], SaveXMMOps.size()));
1731       }
1732
1733       if (!MemOps.empty())
1734         Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
1735                             &MemOps[0], MemOps.size());
1736     }
1737   }
1738
1739   // Some CCs need callee pop.
1740   if (IsCalleePop(isVarArg, CallConv)) {
1741     BytesToPopOnReturn  = StackSize; // Callee pops everything.
1742   } else {
1743     BytesToPopOnReturn  = 0; // Callee pops nothing.
1744     // If this is an sret function, the return should pop the hidden pointer.
1745     if (!Is64Bit && !IsTailCallConvention(CallConv) && ArgsAreStructReturn(Ins))
1746       BytesToPopOnReturn = 4;
1747   }
1748
1749   if (!Is64Bit) {
1750     RegSaveFrameIndex = 0xAAAAAAA;   // RegSaveFrameIndex is X86-64 only.
1751     if (CallConv == CallingConv::X86_FastCall)
1752       VarArgsFrameIndex = 0xAAAAAAA;   // fastcc functions can't have varargs.
1753   }
1754
1755   FuncInfo->setBytesToPopOnReturn(BytesToPopOnReturn);
1756
1757   return Chain;
1758 }
1759
1760 SDValue
1761 X86TargetLowering::LowerMemOpCallTo(SDValue Chain,
1762                                     SDValue StackPtr, SDValue Arg,
1763                                     DebugLoc dl, SelectionDAG &DAG,
1764                                     const CCValAssign &VA,
1765                                     ISD::ArgFlagsTy Flags) {
1766   const unsigned FirstStackArgOffset = (Subtarget->isTargetWin64() ? 32 : 0);
1767   unsigned LocMemOffset = FirstStackArgOffset + VA.getLocMemOffset();
1768   SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset);
1769   PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, PtrOff);
1770   if (Flags.isByVal()) {
1771     return CreateCopyOfByValArgument(Arg, PtrOff, Chain, Flags, DAG, dl);
1772   }
1773   return DAG.getStore(Chain, dl, Arg, PtrOff,
1774                       PseudoSourceValue::getStack(), LocMemOffset,
1775                       false, false, 0);
1776 }
1777
1778 /// EmitTailCallLoadRetAddr - Emit a load of return address if tail call
1779 /// optimization is performed and it is required.
1780 SDValue
1781 X86TargetLowering::EmitTailCallLoadRetAddr(SelectionDAG &DAG,
1782                                            SDValue &OutRetAddr, SDValue Chain,
1783                                            bool IsTailCall, bool Is64Bit,
1784                                            int FPDiff, DebugLoc dl) {
1785   // Adjust the Return address stack slot.
1786   EVT VT = getPointerTy();
1787   OutRetAddr = getReturnAddressFrameIndex(DAG);
1788
1789   // Load the "old" Return address.
1790   OutRetAddr = DAG.getLoad(VT, dl, Chain, OutRetAddr, NULL, 0, false, false, 0);
1791   return SDValue(OutRetAddr.getNode(), 1);
1792 }
1793
1794 /// EmitTailCallStoreRetAddr - Emit a store of the return adress if tail call
1795 /// optimization is performed and it is required (FPDiff!=0).
1796 static SDValue
1797 EmitTailCallStoreRetAddr(SelectionDAG & DAG, MachineFunction &MF,
1798                          SDValue Chain, SDValue RetAddrFrIdx,
1799                          bool Is64Bit, int FPDiff, DebugLoc dl) {
1800   // Store the return address to the appropriate stack slot.
1801   if (!FPDiff) return Chain;
1802   // Calculate the new stack slot for the return address.
1803   int SlotSize = Is64Bit ? 8 : 4;
1804   int NewReturnAddrFI =
1805     MF.getFrameInfo()->CreateFixedObject(SlotSize, FPDiff-SlotSize, false, false);
1806   EVT VT = Is64Bit ? MVT::i64 : MVT::i32;
1807   SDValue NewRetAddrFrIdx = DAG.getFrameIndex(NewReturnAddrFI, VT);
1808   Chain = DAG.getStore(Chain, dl, RetAddrFrIdx, NewRetAddrFrIdx,
1809                        PseudoSourceValue::getFixedStack(NewReturnAddrFI), 0,
1810                        false, false, 0);
1811   return Chain;
1812 }
1813
1814 SDValue
1815 X86TargetLowering::LowerCall(SDValue Chain, SDValue Callee,
1816                              CallingConv::ID CallConv, bool isVarArg,
1817                              bool &isTailCall,
1818                              const SmallVectorImpl<ISD::OutputArg> &Outs,
1819                              const SmallVectorImpl<ISD::InputArg> &Ins,
1820                              DebugLoc dl, SelectionDAG &DAG,
1821                              SmallVectorImpl<SDValue> &InVals) {
1822   MachineFunction &MF = DAG.getMachineFunction();
1823   bool Is64Bit        = Subtarget->is64Bit();
1824   bool IsStructRet    = CallIsStructReturn(Outs);
1825   bool IsSibcall      = false;
1826
1827   if (isTailCall) {
1828     // Check if it's really possible to do a tail call.
1829     isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv, isVarArg,
1830                                                    Outs, Ins, DAG);
1831
1832     // Sibcalls are automatically detected tailcalls which do not require
1833     // ABI changes.
1834     if (!GuaranteedTailCallOpt && isTailCall)
1835       IsSibcall = true;
1836
1837     if (isTailCall)
1838       ++NumTailCalls;
1839   }
1840
1841   assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
1842          "Var args not supported with calling convention fastcc or ghc");
1843
1844   // Analyze operands of the call, assigning locations to each operand.
1845   SmallVector<CCValAssign, 16> ArgLocs;
1846   CCState CCInfo(CallConv, isVarArg, getTargetMachine(),
1847                  ArgLocs, *DAG.getContext());
1848   CCInfo.AnalyzeCallOperands(Outs, CCAssignFnForNode(CallConv));
1849
1850   // Get a count of how many bytes are to be pushed on the stack.
1851   unsigned NumBytes = CCInfo.getNextStackOffset();
1852   if (IsSibcall)
1853     // This is a sibcall. The memory operands are available in caller's
1854     // own caller's stack.
1855     NumBytes = 0;
1856   else if (GuaranteedTailCallOpt && IsTailCallConvention(CallConv))
1857     NumBytes = GetAlignedArgumentStackSize(NumBytes, DAG);
1858
1859   int FPDiff = 0;
1860   if (isTailCall && !IsSibcall) {
1861     // Lower arguments at fp - stackoffset + fpdiff.
1862     unsigned NumBytesCallerPushed =
1863       MF.getInfo<X86MachineFunctionInfo>()->getBytesToPopOnReturn();
1864     FPDiff = NumBytesCallerPushed - NumBytes;
1865
1866     // Set the delta of movement of the returnaddr stackslot.
1867     // But only set if delta is greater than previous delta.
1868     if (FPDiff < (MF.getInfo<X86MachineFunctionInfo>()->getTCReturnAddrDelta()))
1869       MF.getInfo<X86MachineFunctionInfo>()->setTCReturnAddrDelta(FPDiff);
1870   }
1871
1872   if (!IsSibcall)
1873     Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes, true));
1874
1875   SDValue RetAddrFrIdx;
1876   // Load return adress for tail calls.
1877   if (isTailCall && FPDiff)
1878     Chain = EmitTailCallLoadRetAddr(DAG, RetAddrFrIdx, Chain, isTailCall,
1879                                     Is64Bit, FPDiff, dl);
1880
1881   SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
1882   SmallVector<SDValue, 8> MemOpChains;
1883   SDValue StackPtr;
1884
1885   // Walk the register/memloc assignments, inserting copies/loads.  In the case
1886   // of tail call optimization arguments are handle later.
1887   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
1888     CCValAssign &VA = ArgLocs[i];
1889     EVT RegVT = VA.getLocVT();
1890     SDValue Arg = Outs[i].Val;
1891     ISD::ArgFlagsTy Flags = Outs[i].Flags;
1892     bool isByVal = Flags.isByVal();
1893
1894     // Promote the value if needed.
1895     switch (VA.getLocInfo()) {
1896     default: llvm_unreachable("Unknown loc info!");
1897     case CCValAssign::Full: break;
1898     case CCValAssign::SExt:
1899       Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, RegVT, Arg);
1900       break;
1901     case CCValAssign::ZExt:
1902       Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, RegVT, Arg);
1903       break;
1904     case CCValAssign::AExt:
1905       if (RegVT.isVector() && RegVT.getSizeInBits() == 128) {
1906         // Special case: passing MMX values in XMM registers.
1907         Arg = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::i64, Arg);
1908         Arg = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64, Arg);
1909         Arg = getMOVL(DAG, dl, MVT::v2i64, DAG.getUNDEF(MVT::v2i64), Arg);
1910       } else
1911         Arg = DAG.getNode(ISD::ANY_EXTEND, dl, RegVT, Arg);
1912       break;
1913     case CCValAssign::BCvt:
1914       Arg = DAG.getNode(ISD::BIT_CONVERT, dl, RegVT, Arg);
1915       break;
1916     case CCValAssign::Indirect: {
1917       // Store the argument.
1918       SDValue SpillSlot = DAG.CreateStackTemporary(VA.getValVT());
1919       int FI = cast<FrameIndexSDNode>(SpillSlot)->getIndex();
1920       Chain = DAG.getStore(Chain, dl, Arg, SpillSlot,
1921                            PseudoSourceValue::getFixedStack(FI), 0,
1922                            false, false, 0);
1923       Arg = SpillSlot;
1924       break;
1925     }
1926     }
1927
1928     if (VA.isRegLoc()) {
1929       RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
1930     } else if (!IsSibcall && (!isTailCall || isByVal)) {
1931       assert(VA.isMemLoc());
1932       if (StackPtr.getNode() == 0)
1933         StackPtr = DAG.getCopyFromReg(Chain, dl, X86StackPtr, getPointerTy());
1934       MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg,
1935                                              dl, DAG, VA, Flags));
1936     }
1937   }
1938
1939   if (!MemOpChains.empty())
1940     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
1941                         &MemOpChains[0], MemOpChains.size());
1942
1943   // Build a sequence of copy-to-reg nodes chained together with token chain
1944   // and flag operands which copy the outgoing args into registers.
1945   SDValue InFlag;
1946   // Tail call byval lowering might overwrite argument registers so in case of
1947   // tail call optimization the copies to registers are lowered later.
1948   if (!isTailCall)
1949     for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
1950       Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
1951                                RegsToPass[i].second, InFlag);
1952       InFlag = Chain.getValue(1);
1953     }
1954
1955   if (Subtarget->isPICStyleGOT()) {
1956     // ELF / PIC requires GOT in the EBX register before function calls via PLT
1957     // GOT pointer.
1958     if (!isTailCall) {
1959       Chain = DAG.getCopyToReg(Chain, dl, X86::EBX,
1960                                DAG.getNode(X86ISD::GlobalBaseReg,
1961                                            DebugLoc::getUnknownLoc(),
1962                                            getPointerTy()),
1963                                InFlag);
1964       InFlag = Chain.getValue(1);
1965     } else {
1966       // If we are tail calling and generating PIC/GOT style code load the
1967       // address of the callee into ECX. The value in ecx is used as target of
1968       // the tail jump. This is done to circumvent the ebx/callee-saved problem
1969       // for tail calls on PIC/GOT architectures. Normally we would just put the
1970       // address of GOT into ebx and then call target@PLT. But for tail calls
1971       // ebx would be restored (since ebx is callee saved) before jumping to the
1972       // target@PLT.
1973
1974       // Note: The actual moving to ECX is done further down.
1975       GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee);
1976       if (G && !G->getGlobal()->hasHiddenVisibility() &&
1977           !G->getGlobal()->hasProtectedVisibility())
1978         Callee = LowerGlobalAddress(Callee, DAG);
1979       else if (isa<ExternalSymbolSDNode>(Callee))
1980         Callee = LowerExternalSymbol(Callee, DAG);
1981     }
1982   }
1983
1984   if (Is64Bit && isVarArg) {
1985     // From AMD64 ABI document:
1986     // For calls that may call functions that use varargs or stdargs
1987     // (prototype-less calls or calls to functions containing ellipsis (...) in
1988     // the declaration) %al is used as hidden argument to specify the number
1989     // of SSE registers used. The contents of %al do not need to match exactly
1990     // the number of registers, but must be an ubound on the number of SSE
1991     // registers used and is in the range 0 - 8 inclusive.
1992
1993     // FIXME: Verify this on Win64
1994     // Count the number of XMM registers allocated.
1995     static const unsigned XMMArgRegs[] = {
1996       X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
1997       X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
1998     };
1999     unsigned NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs, 8);
2000     assert((Subtarget->hasSSE1() || !NumXMMRegs)
2001            && "SSE registers cannot be used when SSE is disabled");
2002
2003     Chain = DAG.getCopyToReg(Chain, dl, X86::AL,
2004                              DAG.getConstant(NumXMMRegs, MVT::i8), InFlag);
2005     InFlag = Chain.getValue(1);
2006   }
2007
2008
2009   // For tail calls lower the arguments to the 'real' stack slot.
2010   if (isTailCall) {
2011     // Force all the incoming stack arguments to be loaded from the stack
2012     // before any new outgoing arguments are stored to the stack, because the
2013     // outgoing stack slots may alias the incoming argument stack slots, and
2014     // the alias isn't otherwise explicit. This is slightly more conservative
2015     // than necessary, because it means that each store effectively depends
2016     // on every argument instead of just those arguments it would clobber.
2017     SDValue ArgChain = DAG.getStackArgumentTokenFactor(Chain);
2018
2019     SmallVector<SDValue, 8> MemOpChains2;
2020     SDValue FIN;
2021     int FI = 0;
2022     // Do not flag preceeding copytoreg stuff together with the following stuff.
2023     InFlag = SDValue();
2024     if (GuaranteedTailCallOpt) {
2025       for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2026         CCValAssign &VA = ArgLocs[i];
2027         if (VA.isRegLoc())
2028           continue;
2029         assert(VA.isMemLoc());
2030         SDValue Arg = Outs[i].Val;
2031         ISD::ArgFlagsTy Flags = Outs[i].Flags;
2032         // Create frame index.
2033         int32_t Offset = VA.getLocMemOffset()+FPDiff;
2034         uint32_t OpSize = (VA.getLocVT().getSizeInBits()+7)/8;
2035         FI = MF.getFrameInfo()->CreateFixedObject(OpSize, Offset, true, false);
2036         FIN = DAG.getFrameIndex(FI, getPointerTy());
2037
2038         if (Flags.isByVal()) {
2039           // Copy relative to framepointer.
2040           SDValue Source = DAG.getIntPtrConstant(VA.getLocMemOffset());
2041           if (StackPtr.getNode() == 0)
2042             StackPtr = DAG.getCopyFromReg(Chain, dl, X86StackPtr,
2043                                           getPointerTy());
2044           Source = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, Source);
2045
2046           MemOpChains2.push_back(CreateCopyOfByValArgument(Source, FIN,
2047                                                            ArgChain,
2048                                                            Flags, DAG, dl));
2049         } else {
2050           // Store relative to framepointer.
2051           MemOpChains2.push_back(
2052             DAG.getStore(ArgChain, dl, Arg, FIN,
2053                          PseudoSourceValue::getFixedStack(FI), 0,
2054                          false, false, 0));
2055         }
2056       }
2057     }
2058
2059     if (!MemOpChains2.empty())
2060       Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
2061                           &MemOpChains2[0], MemOpChains2.size());
2062
2063     // Copy arguments to their registers.
2064     for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
2065       Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
2066                                RegsToPass[i].second, InFlag);
2067       InFlag = Chain.getValue(1);
2068     }
2069     InFlag =SDValue();
2070
2071     // Store the return address to the appropriate stack slot.
2072     Chain = EmitTailCallStoreRetAddr(DAG, MF, Chain, RetAddrFrIdx, Is64Bit,
2073                                      FPDiff, dl);
2074   }
2075
2076   bool WasGlobalOrExternal = false;
2077   if (getTargetMachine().getCodeModel() == CodeModel::Large) {
2078     assert(Is64Bit && "Large code model is only legal in 64-bit mode.");
2079     // In the 64-bit large code model, we have to make all calls
2080     // through a register, since the call instruction's 32-bit
2081     // pc-relative offset may not be large enough to hold the whole
2082     // address.
2083   } else if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
2084     WasGlobalOrExternal = true;
2085     // If the callee is a GlobalAddress node (quite common, every direct call
2086     // is) turn it into a TargetGlobalAddress node so that legalize doesn't hack
2087     // it.
2088
2089     // We should use extra load for direct calls to dllimported functions in
2090     // non-JIT mode.
2091     GlobalValue *GV = G->getGlobal();
2092     if (!GV->hasDLLImportLinkage()) {
2093       unsigned char OpFlags = 0;
2094
2095       // On ELF targets, in both X86-64 and X86-32 mode, direct calls to
2096       // external symbols most go through the PLT in PIC mode.  If the symbol
2097       // has hidden or protected visibility, or if it is static or local, then
2098       // we don't need to use the PLT - we can directly call it.
2099       if (Subtarget->isTargetELF() &&
2100           getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
2101           GV->hasDefaultVisibility() && !GV->hasLocalLinkage()) {
2102         OpFlags = X86II::MO_PLT;
2103       } else if (Subtarget->isPICStyleStubAny() &&
2104                (GV->isDeclaration() || GV->isWeakForLinker()) &&
2105                Subtarget->getDarwinVers() < 9) {
2106         // PC-relative references to external symbols should go through $stub,
2107         // unless we're building with the leopard linker or later, which
2108         // automatically synthesizes these stubs.
2109         OpFlags = X86II::MO_DARWIN_STUB;
2110       }
2111
2112       Callee = DAG.getTargetGlobalAddress(GV, getPointerTy(),
2113                                           G->getOffset(), OpFlags);
2114     }
2115   } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
2116     WasGlobalOrExternal = true;
2117     unsigned char OpFlags = 0;
2118
2119     // On ELF targets, in either X86-64 or X86-32 mode, direct calls to external
2120     // symbols should go through the PLT.
2121     if (Subtarget->isTargetELF() &&
2122         getTargetMachine().getRelocationModel() == Reloc::PIC_) {
2123       OpFlags = X86II::MO_PLT;
2124     } else if (Subtarget->isPICStyleStubAny() &&
2125              Subtarget->getDarwinVers() < 9) {
2126       // PC-relative references to external symbols should go through $stub,
2127       // unless we're building with the leopard linker or later, which
2128       // automatically synthesizes these stubs.
2129       OpFlags = X86II::MO_DARWIN_STUB;
2130     }
2131
2132     Callee = DAG.getTargetExternalSymbol(S->getSymbol(), getPointerTy(),
2133                                          OpFlags);
2134   }
2135
2136   // Returns a chain & a flag for retval copy to use.
2137   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Flag);
2138   SmallVector<SDValue, 8> Ops;
2139
2140   if (!IsSibcall && isTailCall) {
2141     Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, true),
2142                            DAG.getIntPtrConstant(0, true), InFlag);
2143     InFlag = Chain.getValue(1);
2144   }
2145
2146   Ops.push_back(Chain);
2147   Ops.push_back(Callee);
2148
2149   if (isTailCall)
2150     Ops.push_back(DAG.getConstant(FPDiff, MVT::i32));
2151
2152   // Add argument registers to the end of the list so that they are known live
2153   // into the call.
2154   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
2155     Ops.push_back(DAG.getRegister(RegsToPass[i].first,
2156                                   RegsToPass[i].second.getValueType()));
2157
2158   // Add an implicit use GOT pointer in EBX.
2159   if (!isTailCall && Subtarget->isPICStyleGOT())
2160     Ops.push_back(DAG.getRegister(X86::EBX, getPointerTy()));
2161
2162   // Add an implicit use of AL for x86 vararg functions.
2163   if (Is64Bit && isVarArg)
2164     Ops.push_back(DAG.getRegister(X86::AL, MVT::i8));
2165
2166   if (InFlag.getNode())
2167     Ops.push_back(InFlag);
2168
2169   if (isTailCall) {
2170     // If this is the first return lowered for this function, add the regs
2171     // to the liveout set for the function.
2172     if (MF.getRegInfo().liveout_empty()) {
2173       SmallVector<CCValAssign, 16> RVLocs;
2174       CCState CCInfo(CallConv, isVarArg, getTargetMachine(), RVLocs,
2175                      *DAG.getContext());
2176       CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
2177       for (unsigned i = 0; i != RVLocs.size(); ++i)
2178         if (RVLocs[i].isRegLoc())
2179           MF.getRegInfo().addLiveOut(RVLocs[i].getLocReg());
2180     }
2181     return DAG.getNode(X86ISD::TC_RETURN, dl,
2182                        NodeTys, &Ops[0], Ops.size());
2183   }
2184
2185   Chain = DAG.getNode(X86ISD::CALL, dl, NodeTys, &Ops[0], Ops.size());
2186   InFlag = Chain.getValue(1);
2187
2188   // Create the CALLSEQ_END node.
2189   unsigned NumBytesForCalleeToPush;
2190   if (IsCalleePop(isVarArg, CallConv))
2191     NumBytesForCalleeToPush = NumBytes;    // Callee pops everything
2192   else if (!Is64Bit && !IsTailCallConvention(CallConv) && IsStructRet)
2193     // If this is a call to a struct-return function, the callee
2194     // pops the hidden struct pointer, so we have to push it back.
2195     // This is common for Darwin/X86, Linux & Mingw32 targets.
2196     NumBytesForCalleeToPush = 4;
2197   else
2198     NumBytesForCalleeToPush = 0;  // Callee pops nothing.
2199
2200   // Returns a flag for retval copy to use.
2201   if (!IsSibcall) {
2202     Chain = DAG.getCALLSEQ_END(Chain,
2203                                DAG.getIntPtrConstant(NumBytes, true),
2204                                DAG.getIntPtrConstant(NumBytesForCalleeToPush,
2205                                                      true),
2206                                InFlag);
2207     InFlag = Chain.getValue(1);
2208   }
2209
2210   // Handle result values, copying them out of physregs into vregs that we
2211   // return.
2212   return LowerCallResult(Chain, InFlag, CallConv, isVarArg,
2213                          Ins, dl, DAG, InVals);
2214 }
2215
2216
2217 //===----------------------------------------------------------------------===//
2218 //                Fast Calling Convention (tail call) implementation
2219 //===----------------------------------------------------------------------===//
2220
2221 //  Like std call, callee cleans arguments, convention except that ECX is
2222 //  reserved for storing the tail called function address. Only 2 registers are
2223 //  free for argument passing (inreg). Tail call optimization is performed
2224 //  provided:
2225 //                * tailcallopt is enabled
2226 //                * caller/callee are fastcc
2227 //  On X86_64 architecture with GOT-style position independent code only local
2228 //  (within module) calls are supported at the moment.
2229 //  To keep the stack aligned according to platform abi the function
2230 //  GetAlignedArgumentStackSize ensures that argument delta is always multiples
2231 //  of stack alignment. (Dynamic linkers need this - darwin's dyld for example)
2232 //  If a tail called function callee has more arguments than the caller the
2233 //  caller needs to make sure that there is room to move the RETADDR to. This is
2234 //  achieved by reserving an area the size of the argument delta right after the
2235 //  original REtADDR, but before the saved framepointer or the spilled registers
2236 //  e.g. caller(arg1, arg2) calls callee(arg1, arg2,arg3,arg4)
2237 //  stack layout:
2238 //    arg1
2239 //    arg2
2240 //    RETADDR
2241 //    [ new RETADDR
2242 //      move area ]
2243 //    (possible EBP)
2244 //    ESI
2245 //    EDI
2246 //    local1 ..
2247
2248 /// GetAlignedArgumentStackSize - Make the stack size align e.g 16n + 12 aligned
2249 /// for a 16 byte align requirement.
2250 unsigned X86TargetLowering::GetAlignedArgumentStackSize(unsigned StackSize,
2251                                                         SelectionDAG& DAG) {
2252   MachineFunction &MF = DAG.getMachineFunction();
2253   const TargetMachine &TM = MF.getTarget();
2254   const TargetFrameInfo &TFI = *TM.getFrameInfo();
2255   unsigned StackAlignment = TFI.getStackAlignment();
2256   uint64_t AlignMask = StackAlignment - 1;
2257   int64_t Offset = StackSize;
2258   uint64_t SlotSize = TD->getPointerSize();
2259   if ( (Offset & AlignMask) <= (StackAlignment - SlotSize) ) {
2260     // Number smaller than 12 so just add the difference.
2261     Offset += ((StackAlignment - SlotSize) - (Offset & AlignMask));
2262   } else {
2263     // Mask out lower bits, add stackalignment once plus the 12 bytes.
2264     Offset = ((~AlignMask) & Offset) + StackAlignment +
2265       (StackAlignment-SlotSize);
2266   }
2267   return Offset;
2268 }
2269
2270 /// MatchingStackOffset - Return true if the given stack call argument is
2271 /// already available in the same position (relatively) of the caller's
2272 /// incoming argument stack.
2273 static
2274 bool MatchingStackOffset(SDValue Arg, unsigned Offset, ISD::ArgFlagsTy Flags,
2275                          MachineFrameInfo *MFI, const MachineRegisterInfo *MRI,
2276                          const X86InstrInfo *TII) {
2277   unsigned Bytes = Arg.getValueType().getSizeInBits() / 8;
2278   int FI = INT_MAX;
2279   if (Arg.getOpcode() == ISD::CopyFromReg) {
2280     unsigned VR = cast<RegisterSDNode>(Arg.getOperand(1))->getReg();
2281     if (!VR || TargetRegisterInfo::isPhysicalRegister(VR))
2282       return false;
2283     MachineInstr *Def = MRI->getVRegDef(VR);
2284     if (!Def)
2285       return false;
2286     if (!Flags.isByVal()) {
2287       if (!TII->isLoadFromStackSlot(Def, FI))
2288         return false;
2289     } else {
2290       unsigned Opcode = Def->getOpcode();
2291       if ((Opcode == X86::LEA32r || Opcode == X86::LEA64r) &&
2292           Def->getOperand(1).isFI()) {
2293         FI = Def->getOperand(1).getIndex();
2294         Bytes = Flags.getByValSize();
2295       } else
2296         return false;
2297     }
2298   } else if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Arg)) {
2299     if (Flags.isByVal())
2300       // ByVal argument is passed in as a pointer but it's now being
2301       // dereferenced. e.g.
2302       // define @foo(%struct.X* %A) {
2303       //   tail call @bar(%struct.X* byval %A)
2304       // }
2305       return false;
2306     SDValue Ptr = Ld->getBasePtr();
2307     FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr);
2308     if (!FINode)
2309       return false;
2310     FI = FINode->getIndex();
2311   } else
2312     return false;
2313
2314   assert(FI != INT_MAX);
2315   if (!MFI->isFixedObjectIndex(FI))
2316     return false;
2317   return Offset == MFI->getObjectOffset(FI) && Bytes == MFI->getObjectSize(FI);
2318 }
2319
2320 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
2321 /// for tail call optimization. Targets which want to do tail call
2322 /// optimization should implement this function.
2323 bool
2324 X86TargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
2325                                                      CallingConv::ID CalleeCC,
2326                                                      bool isVarArg,
2327                                     const SmallVectorImpl<ISD::OutputArg> &Outs,
2328                                     const SmallVectorImpl<ISD::InputArg> &Ins,
2329                                                      SelectionDAG& DAG) const {
2330   if (!IsTailCallConvention(CalleeCC) &&
2331       CalleeCC != CallingConv::C)
2332     return false;
2333
2334   // If -tailcallopt is specified, make fastcc functions tail-callable.
2335   const Function *CallerF = DAG.getMachineFunction().getFunction();
2336   if (GuaranteedTailCallOpt) {
2337     if (IsTailCallConvention(CalleeCC) &&
2338         CallerF->getCallingConv() == CalleeCC)
2339       return true;
2340     return false;
2341   }
2342
2343   // Look for obvious safe cases to perform tail call optimization that does not
2344   // requite ABI changes. This is what gcc calls sibcall.
2345
2346   // Do not tail call optimize vararg calls for now.
2347   if (isVarArg)
2348     return false;
2349
2350   // If the callee takes no arguments then go on to check the results of the
2351   // call.
2352   if (!Outs.empty()) {
2353     // Check if stack adjustment is needed. For now, do not do this if any
2354     // argument is passed on the stack.
2355     SmallVector<CCValAssign, 16> ArgLocs;
2356     CCState CCInfo(CalleeCC, isVarArg, getTargetMachine(),
2357                    ArgLocs, *DAG.getContext());
2358     CCInfo.AnalyzeCallOperands(Outs, CCAssignFnForNode(CalleeCC));
2359     if (CCInfo.getNextStackOffset()) {
2360       MachineFunction &MF = DAG.getMachineFunction();
2361       if (MF.getInfo<X86MachineFunctionInfo>()->getBytesToPopOnReturn())
2362         return false;
2363       if (Subtarget->isTargetWin64())
2364         // Win64 ABI has additional complications.
2365         return false;
2366
2367       // Check if the arguments are already laid out in the right way as
2368       // the caller's fixed stack objects.
2369       MachineFrameInfo *MFI = MF.getFrameInfo();
2370       const MachineRegisterInfo *MRI = &MF.getRegInfo();
2371       const X86InstrInfo *TII =
2372         ((X86TargetMachine&)getTargetMachine()).getInstrInfo();
2373       for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2374         CCValAssign &VA = ArgLocs[i];
2375         EVT RegVT = VA.getLocVT();
2376         SDValue Arg = Outs[i].Val;
2377         ISD::ArgFlagsTy Flags = Outs[i].Flags;
2378         if (VA.getLocInfo() == CCValAssign::Indirect)
2379           return false;
2380         if (!VA.isRegLoc()) {
2381           if (!MatchingStackOffset(Arg, VA.getLocMemOffset(), Flags,
2382                                    MFI, MRI, TII))
2383             return false;
2384         }
2385       }
2386     }
2387   }
2388
2389   return true;
2390 }
2391
2392 FastISel *
2393 X86TargetLowering::createFastISel(MachineFunction &mf, MachineModuleInfo *mmo,
2394                             DwarfWriter *dw,
2395                             DenseMap<const Value *, unsigned> &vm,
2396                             DenseMap<const BasicBlock*, MachineBasicBlock*> &bm,
2397                             DenseMap<const AllocaInst *, int> &am
2398 #ifndef NDEBUG
2399                           , SmallSet<Instruction*, 8> &cil
2400 #endif
2401                                   ) {
2402   return X86::createFastISel(mf, mmo, dw, vm, bm, am
2403 #ifndef NDEBUG
2404                              , cil
2405 #endif
2406                              );
2407 }
2408
2409
2410 //===----------------------------------------------------------------------===//
2411 //                           Other Lowering Hooks
2412 //===----------------------------------------------------------------------===//
2413
2414
2415 SDValue X86TargetLowering::getReturnAddressFrameIndex(SelectionDAG &DAG) {
2416   MachineFunction &MF = DAG.getMachineFunction();
2417   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
2418   int ReturnAddrIndex = FuncInfo->getRAIndex();
2419
2420   if (ReturnAddrIndex == 0) {
2421     // Set up a frame object for the return address.
2422     uint64_t SlotSize = TD->getPointerSize();
2423     ReturnAddrIndex = MF.getFrameInfo()->CreateFixedObject(SlotSize, -SlotSize,
2424                                                            false, false);
2425     FuncInfo->setRAIndex(ReturnAddrIndex);
2426   }
2427
2428   return DAG.getFrameIndex(ReturnAddrIndex, getPointerTy());
2429 }
2430
2431
2432 bool X86::isOffsetSuitableForCodeModel(int64_t Offset, CodeModel::Model M,
2433                                        bool hasSymbolicDisplacement) {
2434   // Offset should fit into 32 bit immediate field.
2435   if (!isInt32(Offset))
2436     return false;
2437
2438   // If we don't have a symbolic displacement - we don't have any extra
2439   // restrictions.
2440   if (!hasSymbolicDisplacement)
2441     return true;
2442
2443   // FIXME: Some tweaks might be needed for medium code model.
2444   if (M != CodeModel::Small && M != CodeModel::Kernel)
2445     return false;
2446
2447   // For small code model we assume that latest object is 16MB before end of 31
2448   // bits boundary. We may also accept pretty large negative constants knowing
2449   // that all objects are in the positive half of address space.
2450   if (M == CodeModel::Small && Offset < 16*1024*1024)
2451     return true;
2452
2453   // For kernel code model we know that all object resist in the negative half
2454   // of 32bits address space. We may not accept negative offsets, since they may
2455   // be just off and we may accept pretty large positive ones.
2456   if (M == CodeModel::Kernel && Offset > 0)
2457     return true;
2458
2459   return false;
2460 }
2461
2462 /// TranslateX86CC - do a one to one translation of a ISD::CondCode to the X86
2463 /// specific condition code, returning the condition code and the LHS/RHS of the
2464 /// comparison to make.
2465 static unsigned TranslateX86CC(ISD::CondCode SetCCOpcode, bool isFP,
2466                                SDValue &LHS, SDValue &RHS, SelectionDAG &DAG) {
2467   if (!isFP) {
2468     if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) {
2469       if (SetCCOpcode == ISD::SETGT && RHSC->isAllOnesValue()) {
2470         // X > -1   -> X == 0, jump !sign.
2471         RHS = DAG.getConstant(0, RHS.getValueType());
2472         return X86::COND_NS;
2473       } else if (SetCCOpcode == ISD::SETLT && RHSC->isNullValue()) {
2474         // X < 0   -> X == 0, jump on sign.
2475         return X86::COND_S;
2476       } else if (SetCCOpcode == ISD::SETLT && RHSC->getZExtValue() == 1) {
2477         // X < 1   -> X <= 0
2478         RHS = DAG.getConstant(0, RHS.getValueType());
2479         return X86::COND_LE;
2480       }
2481     }
2482
2483     switch (SetCCOpcode) {
2484     default: llvm_unreachable("Invalid integer condition!");
2485     case ISD::SETEQ:  return X86::COND_E;
2486     case ISD::SETGT:  return X86::COND_G;
2487     case ISD::SETGE:  return X86::COND_GE;
2488     case ISD::SETLT:  return X86::COND_L;
2489     case ISD::SETLE:  return X86::COND_LE;
2490     case ISD::SETNE:  return X86::COND_NE;
2491     case ISD::SETULT: return X86::COND_B;
2492     case ISD::SETUGT: return X86::COND_A;
2493     case ISD::SETULE: return X86::COND_BE;
2494     case ISD::SETUGE: return X86::COND_AE;
2495     }
2496   }
2497
2498   // First determine if it is required or is profitable to flip the operands.
2499
2500   // If LHS is a foldable load, but RHS is not, flip the condition.
2501   if ((ISD::isNON_EXTLoad(LHS.getNode()) && LHS.hasOneUse()) &&
2502       !(ISD::isNON_EXTLoad(RHS.getNode()) && RHS.hasOneUse())) {
2503     SetCCOpcode = getSetCCSwappedOperands(SetCCOpcode);
2504     std::swap(LHS, RHS);
2505   }
2506
2507   switch (SetCCOpcode) {
2508   default: break;
2509   case ISD::SETOLT:
2510   case ISD::SETOLE:
2511   case ISD::SETUGT:
2512   case ISD::SETUGE:
2513     std::swap(LHS, RHS);
2514     break;
2515   }
2516
2517   // On a floating point condition, the flags are set as follows:
2518   // ZF  PF  CF   op
2519   //  0 | 0 | 0 | X > Y
2520   //  0 | 0 | 1 | X < Y
2521   //  1 | 0 | 0 | X == Y
2522   //  1 | 1 | 1 | unordered
2523   switch (SetCCOpcode) {
2524   default: llvm_unreachable("Condcode should be pre-legalized away");
2525   case ISD::SETUEQ:
2526   case ISD::SETEQ:   return X86::COND_E;
2527   case ISD::SETOLT:              // flipped
2528   case ISD::SETOGT:
2529   case ISD::SETGT:   return X86::COND_A;
2530   case ISD::SETOLE:              // flipped
2531   case ISD::SETOGE:
2532   case ISD::SETGE:   return X86::COND_AE;
2533   case ISD::SETUGT:              // flipped
2534   case ISD::SETULT:
2535   case ISD::SETLT:   return X86::COND_B;
2536   case ISD::SETUGE:              // flipped
2537   case ISD::SETULE:
2538   case ISD::SETLE:   return X86::COND_BE;
2539   case ISD::SETONE:
2540   case ISD::SETNE:   return X86::COND_NE;
2541   case ISD::SETUO:   return X86::COND_P;
2542   case ISD::SETO:    return X86::COND_NP;
2543   case ISD::SETOEQ:
2544   case ISD::SETUNE:  return X86::COND_INVALID;
2545   }
2546 }
2547
2548 /// hasFPCMov - is there a floating point cmov for the specific X86 condition
2549 /// code. Current x86 isa includes the following FP cmov instructions:
2550 /// fcmovb, fcomvbe, fcomve, fcmovu, fcmovae, fcmova, fcmovne, fcmovnu.
2551 static bool hasFPCMov(unsigned X86CC) {
2552   switch (X86CC) {
2553   default:
2554     return false;
2555   case X86::COND_B:
2556   case X86::COND_BE:
2557   case X86::COND_E:
2558   case X86::COND_P:
2559   case X86::COND_A:
2560   case X86::COND_AE:
2561   case X86::COND_NE:
2562   case X86::COND_NP:
2563     return true;
2564   }
2565 }
2566
2567 /// isFPImmLegal - Returns true if the target can instruction select the
2568 /// specified FP immediate natively. If false, the legalizer will
2569 /// materialize the FP immediate as a load from a constant pool.
2570 bool X86TargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
2571   for (unsigned i = 0, e = LegalFPImmediates.size(); i != e; ++i) {
2572     if (Imm.bitwiseIsEqual(LegalFPImmediates[i]))
2573       return true;
2574   }
2575   return false;
2576 }
2577
2578 /// isUndefOrInRange - Return true if Val is undef or if its value falls within
2579 /// the specified range (L, H].
2580 static bool isUndefOrInRange(int Val, int Low, int Hi) {
2581   return (Val < 0) || (Val >= Low && Val < Hi);
2582 }
2583
2584 /// isUndefOrEqual - Val is either less than zero (undef) or equal to the
2585 /// specified value.
2586 static bool isUndefOrEqual(int Val, int CmpVal) {
2587   if (Val < 0 || Val == CmpVal)
2588     return true;
2589   return false;
2590 }
2591
2592 /// isPSHUFDMask - Return true if the node specifies a shuffle of elements that
2593 /// is suitable for input to PSHUFD or PSHUFW.  That is, it doesn't reference
2594 /// the second operand.
2595 static bool isPSHUFDMask(const SmallVectorImpl<int> &Mask, EVT VT) {
2596   if (VT == MVT::v4f32 || VT == MVT::v4i32 || VT == MVT::v4i16)
2597     return (Mask[0] < 4 && Mask[1] < 4 && Mask[2] < 4 && Mask[3] < 4);
2598   if (VT == MVT::v2f64 || VT == MVT::v2i64)
2599     return (Mask[0] < 2 && Mask[1] < 2);
2600   return false;
2601 }
2602
2603 bool X86::isPSHUFDMask(ShuffleVectorSDNode *N) {
2604   SmallVector<int, 8> M;
2605   N->getMask(M);
2606   return ::isPSHUFDMask(M, N->getValueType(0));
2607 }
2608
2609 /// isPSHUFHWMask - Return true if the node specifies a shuffle of elements that
2610 /// is suitable for input to PSHUFHW.
2611 static bool isPSHUFHWMask(const SmallVectorImpl<int> &Mask, EVT VT) {
2612   if (VT != MVT::v8i16)
2613     return false;
2614
2615   // Lower quadword copied in order or undef.
2616   for (int i = 0; i != 4; ++i)
2617     if (Mask[i] >= 0 && Mask[i] != i)
2618       return false;
2619
2620   // Upper quadword shuffled.
2621   for (int i = 4; i != 8; ++i)
2622     if (Mask[i] >= 0 && (Mask[i] < 4 || Mask[i] > 7))
2623       return false;
2624
2625   return true;
2626 }
2627
2628 bool X86::isPSHUFHWMask(ShuffleVectorSDNode *N) {
2629   SmallVector<int, 8> M;
2630   N->getMask(M);
2631   return ::isPSHUFHWMask(M, N->getValueType(0));
2632 }
2633
2634 /// isPSHUFLWMask - Return true if the node specifies a shuffle of elements that
2635 /// is suitable for input to PSHUFLW.
2636 static bool isPSHUFLWMask(const SmallVectorImpl<int> &Mask, EVT VT) {
2637   if (VT != MVT::v8i16)
2638     return false;
2639
2640   // Upper quadword copied in order.
2641   for (int i = 4; i != 8; ++i)
2642     if (Mask[i] >= 0 && Mask[i] != i)
2643       return false;
2644
2645   // Lower quadword shuffled.
2646   for (int i = 0; i != 4; ++i)
2647     if (Mask[i] >= 4)
2648       return false;
2649
2650   return true;
2651 }
2652
2653 bool X86::isPSHUFLWMask(ShuffleVectorSDNode *N) {
2654   SmallVector<int, 8> M;
2655   N->getMask(M);
2656   return ::isPSHUFLWMask(M, N->getValueType(0));
2657 }
2658
2659 /// isPALIGNRMask - Return true if the node specifies a shuffle of elements that
2660 /// is suitable for input to PALIGNR.
2661 static bool isPALIGNRMask(const SmallVectorImpl<int> &Mask, EVT VT,
2662                           bool hasSSSE3) {
2663   int i, e = VT.getVectorNumElements();
2664   
2665   // Do not handle v2i64 / v2f64 shuffles with palignr.
2666   if (e < 4 || !hasSSSE3)
2667     return false;
2668   
2669   for (i = 0; i != e; ++i)
2670     if (Mask[i] >= 0)
2671       break;
2672   
2673   // All undef, not a palignr.
2674   if (i == e)
2675     return false;
2676
2677   // Determine if it's ok to perform a palignr with only the LHS, since we
2678   // don't have access to the actual shuffle elements to see if RHS is undef.
2679   bool Unary = Mask[i] < (int)e;
2680   bool NeedsUnary = false;
2681
2682   int s = Mask[i] - i;
2683   
2684   // Check the rest of the elements to see if they are consecutive.
2685   for (++i; i != e; ++i) {
2686     int m = Mask[i];
2687     if (m < 0) 
2688       continue;
2689     
2690     Unary = Unary && (m < (int)e);
2691     NeedsUnary = NeedsUnary || (m < s);
2692
2693     if (NeedsUnary && !Unary)
2694       return false;
2695     if (Unary && m != ((s+i) & (e-1)))
2696       return false;
2697     if (!Unary && m != (s+i))
2698       return false;
2699   }
2700   return true;
2701 }
2702
2703 bool X86::isPALIGNRMask(ShuffleVectorSDNode *N) {
2704   SmallVector<int, 8> M;
2705   N->getMask(M);
2706   return ::isPALIGNRMask(M, N->getValueType(0), true);
2707 }
2708
2709 /// isSHUFPMask - Return true if the specified VECTOR_SHUFFLE operand
2710 /// specifies a shuffle of elements that is suitable for input to SHUFP*.
2711 static bool isSHUFPMask(const SmallVectorImpl<int> &Mask, EVT VT) {
2712   int NumElems = VT.getVectorNumElements();
2713   if (NumElems != 2 && NumElems != 4)
2714     return false;
2715
2716   int Half = NumElems / 2;
2717   for (int i = 0; i < Half; ++i)
2718     if (!isUndefOrInRange(Mask[i], 0, NumElems))
2719       return false;
2720   for (int i = Half; i < NumElems; ++i)
2721     if (!isUndefOrInRange(Mask[i], NumElems, NumElems*2))
2722       return false;
2723
2724   return true;
2725 }
2726
2727 bool X86::isSHUFPMask(ShuffleVectorSDNode *N) {
2728   SmallVector<int, 8> M;
2729   N->getMask(M);
2730   return ::isSHUFPMask(M, N->getValueType(0));
2731 }
2732
2733 /// isCommutedSHUFP - Returns true if the shuffle mask is exactly
2734 /// the reverse of what x86 shuffles want. x86 shuffles requires the lower
2735 /// half elements to come from vector 1 (which would equal the dest.) and
2736 /// the upper half to come from vector 2.
2737 static bool isCommutedSHUFPMask(const SmallVectorImpl<int> &Mask, EVT VT) {
2738   int NumElems = VT.getVectorNumElements();
2739
2740   if (NumElems != 2 && NumElems != 4)
2741     return false;
2742
2743   int Half = NumElems / 2;
2744   for (int i = 0; i < Half; ++i)
2745     if (!isUndefOrInRange(Mask[i], NumElems, NumElems*2))
2746       return false;
2747   for (int i = Half; i < NumElems; ++i)
2748     if (!isUndefOrInRange(Mask[i], 0, NumElems))
2749       return false;
2750   return true;
2751 }
2752
2753 static bool isCommutedSHUFP(ShuffleVectorSDNode *N) {
2754   SmallVector<int, 8> M;
2755   N->getMask(M);
2756   return isCommutedSHUFPMask(M, N->getValueType(0));
2757 }
2758
2759 /// isMOVHLPSMask - Return true if the specified VECTOR_SHUFFLE operand
2760 /// specifies a shuffle of elements that is suitable for input to MOVHLPS.
2761 bool X86::isMOVHLPSMask(ShuffleVectorSDNode *N) {
2762   if (N->getValueType(0).getVectorNumElements() != 4)
2763     return false;
2764
2765   // Expect bit0 == 6, bit1 == 7, bit2 == 2, bit3 == 3
2766   return isUndefOrEqual(N->getMaskElt(0), 6) &&
2767          isUndefOrEqual(N->getMaskElt(1), 7) &&
2768          isUndefOrEqual(N->getMaskElt(2), 2) &&
2769          isUndefOrEqual(N->getMaskElt(3), 3);
2770 }
2771
2772 /// isMOVHLPS_v_undef_Mask - Special case of isMOVHLPSMask for canonical form
2773 /// of vector_shuffle v, v, <2, 3, 2, 3>, i.e. vector_shuffle v, undef,
2774 /// <2, 3, 2, 3>
2775 bool X86::isMOVHLPS_v_undef_Mask(ShuffleVectorSDNode *N) {
2776   unsigned NumElems = N->getValueType(0).getVectorNumElements();
2777   
2778   if (NumElems != 4)
2779     return false;
2780   
2781   return isUndefOrEqual(N->getMaskElt(0), 2) &&
2782   isUndefOrEqual(N->getMaskElt(1), 3) &&
2783   isUndefOrEqual(N->getMaskElt(2), 2) &&
2784   isUndefOrEqual(N->getMaskElt(3), 3);
2785 }
2786
2787 /// isMOVLPMask - Return true if the specified VECTOR_SHUFFLE operand
2788 /// specifies a shuffle of elements that is suitable for input to MOVLP{S|D}.
2789 bool X86::isMOVLPMask(ShuffleVectorSDNode *N) {
2790   unsigned NumElems = N->getValueType(0).getVectorNumElements();
2791
2792   if (NumElems != 2 && NumElems != 4)
2793     return false;
2794
2795   for (unsigned i = 0; i < NumElems/2; ++i)
2796     if (!isUndefOrEqual(N->getMaskElt(i), i + NumElems))
2797       return false;
2798
2799   for (unsigned i = NumElems/2; i < NumElems; ++i)
2800     if (!isUndefOrEqual(N->getMaskElt(i), i))
2801       return false;
2802
2803   return true;
2804 }
2805
2806 /// isMOVLHPSMask - Return true if the specified VECTOR_SHUFFLE operand
2807 /// specifies a shuffle of elements that is suitable for input to MOVLHPS.
2808 bool X86::isMOVLHPSMask(ShuffleVectorSDNode *N) {
2809   unsigned NumElems = N->getValueType(0).getVectorNumElements();
2810
2811   if (NumElems != 2 && NumElems != 4)
2812     return false;
2813
2814   for (unsigned i = 0; i < NumElems/2; ++i)
2815     if (!isUndefOrEqual(N->getMaskElt(i), i))
2816       return false;
2817
2818   for (unsigned i = 0; i < NumElems/2; ++i)
2819     if (!isUndefOrEqual(N->getMaskElt(i + NumElems/2), i + NumElems))
2820       return false;
2821
2822   return true;
2823 }
2824
2825 /// isUNPCKLMask - Return true if the specified VECTOR_SHUFFLE operand
2826 /// specifies a shuffle of elements that is suitable for input to UNPCKL.
2827 static bool isUNPCKLMask(const SmallVectorImpl<int> &Mask, EVT VT,
2828                          bool V2IsSplat = false) {
2829   int NumElts = VT.getVectorNumElements();
2830   if (NumElts != 2 && NumElts != 4 && NumElts != 8 && NumElts != 16)
2831     return false;
2832
2833   for (int i = 0, j = 0; i != NumElts; i += 2, ++j) {
2834     int BitI  = Mask[i];
2835     int BitI1 = Mask[i+1];
2836     if (!isUndefOrEqual(BitI, j))
2837       return false;
2838     if (V2IsSplat) {
2839       if (!isUndefOrEqual(BitI1, NumElts))
2840         return false;
2841     } else {
2842       if (!isUndefOrEqual(BitI1, j + NumElts))
2843         return false;
2844     }
2845   }
2846   return true;
2847 }
2848
2849 bool X86::isUNPCKLMask(ShuffleVectorSDNode *N, bool V2IsSplat) {
2850   SmallVector<int, 8> M;
2851   N->getMask(M);
2852   return ::isUNPCKLMask(M, N->getValueType(0), V2IsSplat);
2853 }
2854
2855 /// isUNPCKHMask - Return true if the specified VECTOR_SHUFFLE operand
2856 /// specifies a shuffle of elements that is suitable for input to UNPCKH.
2857 static bool isUNPCKHMask(const SmallVectorImpl<int> &Mask, EVT VT,
2858                          bool V2IsSplat = false) {
2859   int NumElts = VT.getVectorNumElements();
2860   if (NumElts != 2 && NumElts != 4 && NumElts != 8 && NumElts != 16)
2861     return false;
2862
2863   for (int i = 0, j = 0; i != NumElts; i += 2, ++j) {
2864     int BitI  = Mask[i];
2865     int BitI1 = Mask[i+1];
2866     if (!isUndefOrEqual(BitI, j + NumElts/2))
2867       return false;
2868     if (V2IsSplat) {
2869       if (isUndefOrEqual(BitI1, NumElts))
2870         return false;
2871     } else {
2872       if (!isUndefOrEqual(BitI1, j + NumElts/2 + NumElts))
2873         return false;
2874     }
2875   }
2876   return true;
2877 }
2878
2879 bool X86::isUNPCKHMask(ShuffleVectorSDNode *N, bool V2IsSplat) {
2880   SmallVector<int, 8> M;
2881   N->getMask(M);
2882   return ::isUNPCKHMask(M, N->getValueType(0), V2IsSplat);
2883 }
2884
2885 /// isUNPCKL_v_undef_Mask - Special case of isUNPCKLMask for canonical form
2886 /// of vector_shuffle v, v, <0, 4, 1, 5>, i.e. vector_shuffle v, undef,
2887 /// <0, 0, 1, 1>
2888 static bool isUNPCKL_v_undef_Mask(const SmallVectorImpl<int> &Mask, EVT VT) {
2889   int NumElems = VT.getVectorNumElements();
2890   if (NumElems != 2 && NumElems != 4 && NumElems != 8 && NumElems != 16)
2891     return false;
2892
2893   for (int i = 0, j = 0; i != NumElems; i += 2, ++j) {
2894     int BitI  = Mask[i];
2895     int BitI1 = Mask[i+1];
2896     if (!isUndefOrEqual(BitI, j))
2897       return false;
2898     if (!isUndefOrEqual(BitI1, j))
2899       return false;
2900   }
2901   return true;
2902 }
2903
2904 bool X86::isUNPCKL_v_undef_Mask(ShuffleVectorSDNode *N) {
2905   SmallVector<int, 8> M;
2906   N->getMask(M);
2907   return ::isUNPCKL_v_undef_Mask(M, N->getValueType(0));
2908 }
2909
2910 /// isUNPCKH_v_undef_Mask - Special case of isUNPCKHMask for canonical form
2911 /// of vector_shuffle v, v, <2, 6, 3, 7>, i.e. vector_shuffle v, undef,
2912 /// <2, 2, 3, 3>
2913 static bool isUNPCKH_v_undef_Mask(const SmallVectorImpl<int> &Mask, EVT VT) {
2914   int NumElems = VT.getVectorNumElements();
2915   if (NumElems != 2 && NumElems != 4 && NumElems != 8 && NumElems != 16)
2916     return false;
2917
2918   for (int i = 0, j = NumElems / 2; i != NumElems; i += 2, ++j) {
2919     int BitI  = Mask[i];
2920     int BitI1 = Mask[i+1];
2921     if (!isUndefOrEqual(BitI, j))
2922       return false;
2923     if (!isUndefOrEqual(BitI1, j))
2924       return false;
2925   }
2926   return true;
2927 }
2928
2929 bool X86::isUNPCKH_v_undef_Mask(ShuffleVectorSDNode *N) {
2930   SmallVector<int, 8> M;
2931   N->getMask(M);
2932   return ::isUNPCKH_v_undef_Mask(M, N->getValueType(0));
2933 }
2934
2935 /// isMOVLMask - Return true if the specified VECTOR_SHUFFLE operand
2936 /// specifies a shuffle of elements that is suitable for input to MOVSS,
2937 /// MOVSD, and MOVD, i.e. setting the lowest element.
2938 static bool isMOVLMask(const SmallVectorImpl<int> &Mask, EVT VT) {
2939   if (VT.getVectorElementType().getSizeInBits() < 32)
2940     return false;
2941
2942   int NumElts = VT.getVectorNumElements();
2943
2944   if (!isUndefOrEqual(Mask[0], NumElts))
2945     return false;
2946
2947   for (int i = 1; i < NumElts; ++i)
2948     if (!isUndefOrEqual(Mask[i], i))
2949       return false;
2950
2951   return true;
2952 }
2953
2954 bool X86::isMOVLMask(ShuffleVectorSDNode *N) {
2955   SmallVector<int, 8> M;
2956   N->getMask(M);
2957   return ::isMOVLMask(M, N->getValueType(0));
2958 }
2959
2960 /// isCommutedMOVL - Returns true if the shuffle mask is except the reverse
2961 /// of what x86 movss want. X86 movs requires the lowest  element to be lowest
2962 /// element of vector 2 and the other elements to come from vector 1 in order.
2963 static bool isCommutedMOVLMask(const SmallVectorImpl<int> &Mask, EVT VT,
2964                                bool V2IsSplat = false, bool V2IsUndef = false) {
2965   int NumOps = VT.getVectorNumElements();
2966   if (NumOps != 2 && NumOps != 4 && NumOps != 8 && NumOps != 16)
2967     return false;
2968
2969   if (!isUndefOrEqual(Mask[0], 0))
2970     return false;
2971
2972   for (int i = 1; i < NumOps; ++i)
2973     if (!(isUndefOrEqual(Mask[i], i+NumOps) ||
2974           (V2IsUndef && isUndefOrInRange(Mask[i], NumOps, NumOps*2)) ||
2975           (V2IsSplat && isUndefOrEqual(Mask[i], NumOps))))
2976       return false;
2977
2978   return true;
2979 }
2980
2981 static bool isCommutedMOVL(ShuffleVectorSDNode *N, bool V2IsSplat = false,
2982                            bool V2IsUndef = false) {
2983   SmallVector<int, 8> M;
2984   N->getMask(M);
2985   return isCommutedMOVLMask(M, N->getValueType(0), V2IsSplat, V2IsUndef);
2986 }
2987
2988 /// isMOVSHDUPMask - Return true if the specified VECTOR_SHUFFLE operand
2989 /// specifies a shuffle of elements that is suitable for input to MOVSHDUP.
2990 bool X86::isMOVSHDUPMask(ShuffleVectorSDNode *N) {
2991   if (N->getValueType(0).getVectorNumElements() != 4)
2992     return false;
2993
2994   // Expect 1, 1, 3, 3
2995   for (unsigned i = 0; i < 2; ++i) {
2996     int Elt = N->getMaskElt(i);
2997     if (Elt >= 0 && Elt != 1)
2998       return false;
2999   }
3000
3001   bool HasHi = false;
3002   for (unsigned i = 2; i < 4; ++i) {
3003     int Elt = N->getMaskElt(i);
3004     if (Elt >= 0 && Elt != 3)
3005       return false;
3006     if (Elt == 3)
3007       HasHi = true;
3008   }
3009   // Don't use movshdup if it can be done with a shufps.
3010   // FIXME: verify that matching u, u, 3, 3 is what we want.
3011   return HasHi;
3012 }
3013
3014 /// isMOVSLDUPMask - Return true if the specified VECTOR_SHUFFLE operand
3015 /// specifies a shuffle of elements that is suitable for input to MOVSLDUP.
3016 bool X86::isMOVSLDUPMask(ShuffleVectorSDNode *N) {
3017   if (N->getValueType(0).getVectorNumElements() != 4)
3018     return false;
3019
3020   // Expect 0, 0, 2, 2
3021   for (unsigned i = 0; i < 2; ++i)
3022     if (N->getMaskElt(i) > 0)
3023       return false;
3024
3025   bool HasHi = false;
3026   for (unsigned i = 2; i < 4; ++i) {
3027     int Elt = N->getMaskElt(i);
3028     if (Elt >= 0 && Elt != 2)
3029       return false;
3030     if (Elt == 2)
3031       HasHi = true;
3032   }
3033   // Don't use movsldup if it can be done with a shufps.
3034   return HasHi;
3035 }
3036
3037 /// isMOVDDUPMask - Return true if the specified VECTOR_SHUFFLE operand
3038 /// specifies a shuffle of elements that is suitable for input to MOVDDUP.
3039 bool X86::isMOVDDUPMask(ShuffleVectorSDNode *N) {
3040   int e = N->getValueType(0).getVectorNumElements() / 2;
3041
3042   for (int i = 0; i < e; ++i)
3043     if (!isUndefOrEqual(N->getMaskElt(i), i))
3044       return false;
3045   for (int i = 0; i < e; ++i)
3046     if (!isUndefOrEqual(N->getMaskElt(e+i), i))
3047       return false;
3048   return true;
3049 }
3050
3051 /// getShuffleSHUFImmediate - Return the appropriate immediate to shuffle
3052 /// the specified VECTOR_SHUFFLE mask with PSHUF* and SHUFP* instructions.
3053 unsigned X86::getShuffleSHUFImmediate(SDNode *N) {
3054   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
3055   int NumOperands = SVOp->getValueType(0).getVectorNumElements();
3056
3057   unsigned Shift = (NumOperands == 4) ? 2 : 1;
3058   unsigned Mask = 0;
3059   for (int i = 0; i < NumOperands; ++i) {
3060     int Val = SVOp->getMaskElt(NumOperands-i-1);
3061     if (Val < 0) Val = 0;
3062     if (Val >= NumOperands) Val -= NumOperands;
3063     Mask |= Val;
3064     if (i != NumOperands - 1)
3065       Mask <<= Shift;
3066   }
3067   return Mask;
3068 }
3069
3070 /// getShufflePSHUFHWImmediate - Return the appropriate immediate to shuffle
3071 /// the specified VECTOR_SHUFFLE mask with the PSHUFHW instruction.
3072 unsigned X86::getShufflePSHUFHWImmediate(SDNode *N) {
3073   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
3074   unsigned Mask = 0;
3075   // 8 nodes, but we only care about the last 4.
3076   for (unsigned i = 7; i >= 4; --i) {
3077     int Val = SVOp->getMaskElt(i);
3078     if (Val >= 0)
3079       Mask |= (Val - 4);
3080     if (i != 4)
3081       Mask <<= 2;
3082   }
3083   return Mask;
3084 }
3085
3086 /// getShufflePSHUFLWImmediate - Return the appropriate immediate to shuffle
3087 /// the specified VECTOR_SHUFFLE mask with the PSHUFLW instruction.
3088 unsigned X86::getShufflePSHUFLWImmediate(SDNode *N) {
3089   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
3090   unsigned Mask = 0;
3091   // 8 nodes, but we only care about the first 4.
3092   for (int i = 3; i >= 0; --i) {
3093     int Val = SVOp->getMaskElt(i);
3094     if (Val >= 0)
3095       Mask |= Val;
3096     if (i != 0)
3097       Mask <<= 2;
3098   }
3099   return Mask;
3100 }
3101
3102 /// getShufflePALIGNRImmediate - Return the appropriate immediate to shuffle
3103 /// the specified VECTOR_SHUFFLE mask with the PALIGNR instruction.
3104 unsigned X86::getShufflePALIGNRImmediate(SDNode *N) {
3105   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
3106   EVT VVT = N->getValueType(0);
3107   unsigned EltSize = VVT.getVectorElementType().getSizeInBits() >> 3;
3108   int Val = 0;
3109
3110   unsigned i, e;
3111   for (i = 0, e = VVT.getVectorNumElements(); i != e; ++i) {
3112     Val = SVOp->getMaskElt(i);
3113     if (Val >= 0)
3114       break;
3115   }
3116   return (Val - i) * EltSize;
3117 }
3118
3119 /// isZeroNode - Returns true if Elt is a constant zero or a floating point
3120 /// constant +0.0.
3121 bool X86::isZeroNode(SDValue Elt) {
3122   return ((isa<ConstantSDNode>(Elt) &&
3123            cast<ConstantSDNode>(Elt)->getZExtValue() == 0) ||
3124           (isa<ConstantFPSDNode>(Elt) &&
3125            cast<ConstantFPSDNode>(Elt)->getValueAPF().isPosZero()));
3126 }
3127
3128 /// CommuteVectorShuffle - Swap vector_shuffle operands as well as values in
3129 /// their permute mask.
3130 static SDValue CommuteVectorShuffle(ShuffleVectorSDNode *SVOp,
3131                                     SelectionDAG &DAG) {
3132   EVT VT = SVOp->getValueType(0);
3133   unsigned NumElems = VT.getVectorNumElements();
3134   SmallVector<int, 8> MaskVec;
3135
3136   for (unsigned i = 0; i != NumElems; ++i) {
3137     int idx = SVOp->getMaskElt(i);
3138     if (idx < 0)
3139       MaskVec.push_back(idx);
3140     else if (idx < (int)NumElems)
3141       MaskVec.push_back(idx + NumElems);
3142     else
3143       MaskVec.push_back(idx - NumElems);
3144   }
3145   return DAG.getVectorShuffle(VT, SVOp->getDebugLoc(), SVOp->getOperand(1),
3146                               SVOp->getOperand(0), &MaskVec[0]);
3147 }
3148
3149 /// CommuteVectorShuffleMask - Change values in a shuffle permute mask assuming
3150 /// the two vector operands have swapped position.
3151 static void CommuteVectorShuffleMask(SmallVectorImpl<int> &Mask, EVT VT) {
3152   unsigned NumElems = VT.getVectorNumElements();
3153   for (unsigned i = 0; i != NumElems; ++i) {
3154     int idx = Mask[i];
3155     if (idx < 0)
3156       continue;
3157     else if (idx < (int)NumElems)
3158       Mask[i] = idx + NumElems;
3159     else
3160       Mask[i] = idx - NumElems;
3161   }
3162 }
3163
3164 /// ShouldXformToMOVHLPS - Return true if the node should be transformed to
3165 /// match movhlps. The lower half elements should come from upper half of
3166 /// V1 (and in order), and the upper half elements should come from the upper
3167 /// half of V2 (and in order).
3168 static bool ShouldXformToMOVHLPS(ShuffleVectorSDNode *Op) {
3169   if (Op->getValueType(0).getVectorNumElements() != 4)
3170     return false;
3171   for (unsigned i = 0, e = 2; i != e; ++i)
3172     if (!isUndefOrEqual(Op->getMaskElt(i), i+2))
3173       return false;
3174   for (unsigned i = 2; i != 4; ++i)
3175     if (!isUndefOrEqual(Op->getMaskElt(i), i+4))
3176       return false;
3177   return true;
3178 }
3179
3180 /// isScalarLoadToVector - Returns true if the node is a scalar load that
3181 /// is promoted to a vector. It also returns the LoadSDNode by reference if
3182 /// required.
3183 static bool isScalarLoadToVector(SDNode *N, LoadSDNode **LD = NULL) {
3184   if (N->getOpcode() != ISD::SCALAR_TO_VECTOR)
3185     return false;
3186   N = N->getOperand(0).getNode();
3187   if (!ISD::isNON_EXTLoad(N))
3188     return false;
3189   if (LD)
3190     *LD = cast<LoadSDNode>(N);
3191   return true;
3192 }
3193
3194 /// ShouldXformToMOVLP{S|D} - Return true if the node should be transformed to
3195 /// match movlp{s|d}. The lower half elements should come from lower half of
3196 /// V1 (and in order), and the upper half elements should come from the upper
3197 /// half of V2 (and in order). And since V1 will become the source of the
3198 /// MOVLP, it must be either a vector load or a scalar load to vector.
3199 static bool ShouldXformToMOVLP(SDNode *V1, SDNode *V2,
3200                                ShuffleVectorSDNode *Op) {
3201   if (!ISD::isNON_EXTLoad(V1) && !isScalarLoadToVector(V1))
3202     return false;
3203   // Is V2 is a vector load, don't do this transformation. We will try to use
3204   // load folding shufps op.
3205   if (ISD::isNON_EXTLoad(V2))
3206     return false;
3207
3208   unsigned NumElems = Op->getValueType(0).getVectorNumElements();
3209
3210   if (NumElems != 2 && NumElems != 4)
3211     return false;
3212   for (unsigned i = 0, e = NumElems/2; i != e; ++i)
3213     if (!isUndefOrEqual(Op->getMaskElt(i), i))
3214       return false;
3215   for (unsigned i = NumElems/2; i != NumElems; ++i)
3216     if (!isUndefOrEqual(Op->getMaskElt(i), i+NumElems))
3217       return false;
3218   return true;
3219 }
3220
3221 /// isSplatVector - Returns true if N is a BUILD_VECTOR node whose elements are
3222 /// all the same.
3223 static bool isSplatVector(SDNode *N) {
3224   if (N->getOpcode() != ISD::BUILD_VECTOR)
3225     return false;
3226
3227   SDValue SplatValue = N->getOperand(0);
3228   for (unsigned i = 1, e = N->getNumOperands(); i != e; ++i)
3229     if (N->getOperand(i) != SplatValue)
3230       return false;
3231   return true;
3232 }
3233
3234 /// isZeroShuffle - Returns true if N is a VECTOR_SHUFFLE that can be resolved
3235 /// to an zero vector.
3236 /// FIXME: move to dag combiner / method on ShuffleVectorSDNode
3237 static bool isZeroShuffle(ShuffleVectorSDNode *N) {
3238   SDValue V1 = N->getOperand(0);
3239   SDValue V2 = N->getOperand(1);
3240   unsigned NumElems = N->getValueType(0).getVectorNumElements();
3241   for (unsigned i = 0; i != NumElems; ++i) {
3242     int Idx = N->getMaskElt(i);
3243     if (Idx >= (int)NumElems) {
3244       unsigned Opc = V2.getOpcode();
3245       if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V2.getNode()))
3246         continue;
3247       if (Opc != ISD::BUILD_VECTOR ||
3248           !X86::isZeroNode(V2.getOperand(Idx-NumElems)))
3249         return false;
3250     } else if (Idx >= 0) {
3251       unsigned Opc = V1.getOpcode();
3252       if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V1.getNode()))
3253         continue;
3254       if (Opc != ISD::BUILD_VECTOR ||
3255           !X86::isZeroNode(V1.getOperand(Idx)))
3256         return false;
3257     }
3258   }
3259   return true;
3260 }
3261
3262 /// getZeroVector - Returns a vector of specified type with all zero elements.
3263 ///
3264 static SDValue getZeroVector(EVT VT, bool HasSSE2, SelectionDAG &DAG,
3265                              DebugLoc dl) {
3266   assert(VT.isVector() && "Expected a vector type");
3267
3268   // Always build zero vectors as <4 x i32> or <2 x i32> bitcasted to their dest
3269   // type.  This ensures they get CSE'd.
3270   SDValue Vec;
3271   if (VT.getSizeInBits() == 64) { // MMX
3272     SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
3273     Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v2i32, Cst, Cst);
3274   } else if (HasSSE2) {  // SSE2
3275     SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
3276     Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
3277   } else { // SSE1
3278     SDValue Cst = DAG.getTargetConstantFP(+0.0, MVT::f32);
3279     Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4f32, Cst, Cst, Cst, Cst);
3280   }
3281   return DAG.getNode(ISD::BIT_CONVERT, dl, VT, Vec);
3282 }
3283
3284 /// getOnesVector - Returns a vector of specified type with all bits set.
3285 ///
3286 static SDValue getOnesVector(EVT VT, SelectionDAG &DAG, DebugLoc dl) {
3287   assert(VT.isVector() && "Expected a vector type");
3288
3289   // Always build ones vectors as <4 x i32> or <2 x i32> bitcasted to their dest
3290   // type.  This ensures they get CSE'd.
3291   SDValue Cst = DAG.getTargetConstant(~0U, MVT::i32);
3292   SDValue Vec;
3293   if (VT.getSizeInBits() == 64)  // MMX
3294     Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v2i32, Cst, Cst);
3295   else                                              // SSE
3296     Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
3297   return DAG.getNode(ISD::BIT_CONVERT, dl, VT, Vec);
3298 }
3299
3300
3301 /// NormalizeMask - V2 is a splat, modify the mask (if needed) so all elements
3302 /// that point to V2 points to its first element.
3303 static SDValue NormalizeMask(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
3304   EVT VT = SVOp->getValueType(0);
3305   unsigned NumElems = VT.getVectorNumElements();
3306
3307   bool Changed = false;
3308   SmallVector<int, 8> MaskVec;
3309   SVOp->getMask(MaskVec);
3310
3311   for (unsigned i = 0; i != NumElems; ++i) {
3312     if (MaskVec[i] > (int)NumElems) {
3313       MaskVec[i] = NumElems;
3314       Changed = true;
3315     }
3316   }
3317   if (Changed)
3318     return DAG.getVectorShuffle(VT, SVOp->getDebugLoc(), SVOp->getOperand(0),
3319                                 SVOp->getOperand(1), &MaskVec[0]);
3320   return SDValue(SVOp, 0);
3321 }
3322
3323 /// getMOVLMask - Returns a vector_shuffle mask for an movs{s|d}, movd
3324 /// operation of specified width.
3325 static SDValue getMOVL(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
3326                        SDValue V2) {
3327   unsigned NumElems = VT.getVectorNumElements();
3328   SmallVector<int, 8> Mask;
3329   Mask.push_back(NumElems);
3330   for (unsigned i = 1; i != NumElems; ++i)
3331     Mask.push_back(i);
3332   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
3333 }
3334
3335 /// getUnpackl - Returns a vector_shuffle node for an unpackl operation.
3336 static SDValue getUnpackl(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
3337                           SDValue V2) {
3338   unsigned NumElems = VT.getVectorNumElements();
3339   SmallVector<int, 8> Mask;
3340   for (unsigned i = 0, e = NumElems/2; i != e; ++i) {
3341     Mask.push_back(i);
3342     Mask.push_back(i + NumElems);
3343   }
3344   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
3345 }
3346
3347 /// getUnpackhMask - Returns a vector_shuffle node for an unpackh operation.
3348 static SDValue getUnpackh(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
3349                           SDValue V2) {
3350   unsigned NumElems = VT.getVectorNumElements();
3351   unsigned Half = NumElems/2;
3352   SmallVector<int, 8> Mask;
3353   for (unsigned i = 0; i != Half; ++i) {
3354     Mask.push_back(i + Half);
3355     Mask.push_back(i + NumElems + Half);
3356   }
3357   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
3358 }
3359
3360 /// PromoteSplat - Promote a splat of v4f32, v8i16 or v16i8 to v4i32.
3361 static SDValue PromoteSplat(ShuffleVectorSDNode *SV, SelectionDAG &DAG,
3362                             bool HasSSE2) {
3363   if (SV->getValueType(0).getVectorNumElements() <= 4)
3364     return SDValue(SV, 0);
3365
3366   EVT PVT = MVT::v4f32;
3367   EVT VT = SV->getValueType(0);
3368   DebugLoc dl = SV->getDebugLoc();
3369   SDValue V1 = SV->getOperand(0);
3370   int NumElems = VT.getVectorNumElements();
3371   int EltNo = SV->getSplatIndex();
3372
3373   // unpack elements to the correct location
3374   while (NumElems > 4) {
3375     if (EltNo < NumElems/2) {
3376       V1 = getUnpackl(DAG, dl, VT, V1, V1);
3377     } else {
3378       V1 = getUnpackh(DAG, dl, VT, V1, V1);
3379       EltNo -= NumElems/2;
3380     }
3381     NumElems >>= 1;
3382   }
3383
3384   // Perform the splat.
3385   int SplatMask[4] = { EltNo, EltNo, EltNo, EltNo };
3386   V1 = DAG.getNode(ISD::BIT_CONVERT, dl, PVT, V1);
3387   V1 = DAG.getVectorShuffle(PVT, dl, V1, DAG.getUNDEF(PVT), &SplatMask[0]);
3388   return DAG.getNode(ISD::BIT_CONVERT, dl, VT, V1);
3389 }
3390
3391 /// getShuffleVectorZeroOrUndef - Return a vector_shuffle of the specified
3392 /// vector of zero or undef vector.  This produces a shuffle where the low
3393 /// element of V2 is swizzled into the zero/undef vector, landing at element
3394 /// Idx.  This produces a shuffle mask like 4,1,2,3 (idx=0) or  0,1,2,4 (idx=3).
3395 static SDValue getShuffleVectorZeroOrUndef(SDValue V2, unsigned Idx,
3396                                              bool isZero, bool HasSSE2,
3397                                              SelectionDAG &DAG) {
3398   EVT VT = V2.getValueType();
3399   SDValue V1 = isZero
3400     ? getZeroVector(VT, HasSSE2, DAG, V2.getDebugLoc()) : DAG.getUNDEF(VT);
3401   unsigned NumElems = VT.getVectorNumElements();
3402   SmallVector<int, 16> MaskVec;
3403   for (unsigned i = 0; i != NumElems; ++i)
3404     // If this is the insertion idx, put the low elt of V2 here.
3405     MaskVec.push_back(i == Idx ? NumElems : i);
3406   return DAG.getVectorShuffle(VT, V2.getDebugLoc(), V1, V2, &MaskVec[0]);
3407 }
3408
3409 /// getNumOfConsecutiveZeros - Return the number of elements in a result of
3410 /// a shuffle that is zero.
3411 static
3412 unsigned getNumOfConsecutiveZeros(ShuffleVectorSDNode *SVOp, int NumElems,
3413                                   bool Low, SelectionDAG &DAG) {
3414   unsigned NumZeros = 0;
3415   for (int i = 0; i < NumElems; ++i) {
3416     unsigned Index = Low ? i : NumElems-i-1;
3417     int Idx = SVOp->getMaskElt(Index);
3418     if (Idx < 0) {
3419       ++NumZeros;
3420       continue;
3421     }
3422     SDValue Elt = DAG.getShuffleScalarElt(SVOp, Index);
3423     if (Elt.getNode() && X86::isZeroNode(Elt))
3424       ++NumZeros;
3425     else
3426       break;
3427   }
3428   return NumZeros;
3429 }
3430
3431 /// isVectorShift - Returns true if the shuffle can be implemented as a
3432 /// logical left or right shift of a vector.
3433 /// FIXME: split into pslldqi, psrldqi, palignr variants.
3434 static bool isVectorShift(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
3435                           bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
3436   int NumElems = SVOp->getValueType(0).getVectorNumElements();
3437
3438   isLeft = true;
3439   unsigned NumZeros = getNumOfConsecutiveZeros(SVOp, NumElems, true, DAG);
3440   if (!NumZeros) {
3441     isLeft = false;
3442     NumZeros = getNumOfConsecutiveZeros(SVOp, NumElems, false, DAG);
3443     if (!NumZeros)
3444       return false;
3445   }
3446   bool SeenV1 = false;
3447   bool SeenV2 = false;
3448   for (int i = NumZeros; i < NumElems; ++i) {
3449     int Val = isLeft ? (i - NumZeros) : i;
3450     int Idx = SVOp->getMaskElt(isLeft ? i : (i - NumZeros));
3451     if (Idx < 0)
3452       continue;
3453     if (Idx < NumElems)
3454       SeenV1 = true;
3455     else {
3456       Idx -= NumElems;
3457       SeenV2 = true;
3458     }
3459     if (Idx != Val)
3460       return false;
3461   }
3462   if (SeenV1 && SeenV2)
3463     return false;
3464
3465   ShVal = SeenV1 ? SVOp->getOperand(0) : SVOp->getOperand(1);
3466   ShAmt = NumZeros;
3467   return true;
3468 }
3469
3470
3471 /// LowerBuildVectorv16i8 - Custom lower build_vector of v16i8.
3472 ///
3473 static SDValue LowerBuildVectorv16i8(SDValue Op, unsigned NonZeros,
3474                                        unsigned NumNonZero, unsigned NumZero,
3475                                        SelectionDAG &DAG, TargetLowering &TLI) {
3476   if (NumNonZero > 8)
3477     return SDValue();
3478
3479   DebugLoc dl = Op.getDebugLoc();
3480   SDValue V(0, 0);
3481   bool First = true;
3482   for (unsigned i = 0; i < 16; ++i) {
3483     bool ThisIsNonZero = (NonZeros & (1 << i)) != 0;
3484     if (ThisIsNonZero && First) {
3485       if (NumZero)
3486         V = getZeroVector(MVT::v8i16, true, DAG, dl);
3487       else
3488         V = DAG.getUNDEF(MVT::v8i16);
3489       First = false;
3490     }
3491
3492     if ((i & 1) != 0) {
3493       SDValue ThisElt(0, 0), LastElt(0, 0);
3494       bool LastIsNonZero = (NonZeros & (1 << (i-1))) != 0;
3495       if (LastIsNonZero) {
3496         LastElt = DAG.getNode(ISD::ZERO_EXTEND, dl,
3497                               MVT::i16, Op.getOperand(i-1));
3498       }
3499       if (ThisIsNonZero) {
3500         ThisElt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i16, Op.getOperand(i));
3501         ThisElt = DAG.getNode(ISD::SHL, dl, MVT::i16,
3502                               ThisElt, DAG.getConstant(8, MVT::i8));
3503         if (LastIsNonZero)
3504           ThisElt = DAG.getNode(ISD::OR, dl, MVT::i16, ThisElt, LastElt);
3505       } else
3506         ThisElt = LastElt;
3507
3508       if (ThisElt.getNode())
3509         V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, V, ThisElt,
3510                         DAG.getIntPtrConstant(i/2));
3511     }
3512   }
3513
3514   return DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v16i8, V);
3515 }
3516
3517 /// LowerBuildVectorv8i16 - Custom lower build_vector of v8i16.
3518 ///
3519 static SDValue LowerBuildVectorv8i16(SDValue Op, unsigned NonZeros,
3520                                        unsigned NumNonZero, unsigned NumZero,
3521                                        SelectionDAG &DAG, TargetLowering &TLI) {
3522   if (NumNonZero > 4)
3523     return SDValue();
3524
3525   DebugLoc dl = Op.getDebugLoc();
3526   SDValue V(0, 0);
3527   bool First = true;
3528   for (unsigned i = 0; i < 8; ++i) {
3529     bool isNonZero = (NonZeros & (1 << i)) != 0;
3530     if (isNonZero) {
3531       if (First) {
3532         if (NumZero)
3533           V = getZeroVector(MVT::v8i16, true, DAG, dl);
3534         else
3535           V = DAG.getUNDEF(MVT::v8i16);
3536         First = false;
3537       }
3538       V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl,
3539                       MVT::v8i16, V, Op.getOperand(i),
3540                       DAG.getIntPtrConstant(i));
3541     }
3542   }
3543
3544   return V;
3545 }
3546
3547 /// getVShift - Return a vector logical shift node.
3548 ///
3549 static SDValue getVShift(bool isLeft, EVT VT, SDValue SrcOp,
3550                          unsigned NumBits, SelectionDAG &DAG,
3551                          const TargetLowering &TLI, DebugLoc dl) {
3552   bool isMMX = VT.getSizeInBits() == 64;
3553   EVT ShVT = isMMX ? MVT::v1i64 : MVT::v2i64;
3554   unsigned Opc = isLeft ? X86ISD::VSHL : X86ISD::VSRL;
3555   SrcOp = DAG.getNode(ISD::BIT_CONVERT, dl, ShVT, SrcOp);
3556   return DAG.getNode(ISD::BIT_CONVERT, dl, VT,
3557                      DAG.getNode(Opc, dl, ShVT, SrcOp,
3558                              DAG.getConstant(NumBits, TLI.getShiftAmountTy())));
3559 }
3560
3561 SDValue
3562 X86TargetLowering::LowerAsSplatVectorLoad(SDValue SrcOp, EVT VT, DebugLoc dl,
3563                                           SelectionDAG &DAG) {
3564   
3565   // Check if the scalar load can be widened into a vector load. And if
3566   // the address is "base + cst" see if the cst can be "absorbed" into
3567   // the shuffle mask.
3568   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(SrcOp)) {
3569     SDValue Ptr = LD->getBasePtr();
3570     if (!ISD::isNormalLoad(LD) || LD->isVolatile())
3571       return SDValue();
3572     EVT PVT = LD->getValueType(0);
3573     if (PVT != MVT::i32 && PVT != MVT::f32)
3574       return SDValue();
3575
3576     int FI = -1;
3577     int64_t Offset = 0;
3578     if (FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr)) {
3579       FI = FINode->getIndex();
3580       Offset = 0;
3581     } else if (Ptr.getOpcode() == ISD::ADD &&
3582                isa<ConstantSDNode>(Ptr.getOperand(1)) &&
3583                isa<FrameIndexSDNode>(Ptr.getOperand(0))) {
3584       FI = cast<FrameIndexSDNode>(Ptr.getOperand(0))->getIndex();
3585       Offset = Ptr.getConstantOperandVal(1);
3586       Ptr = Ptr.getOperand(0);
3587     } else {
3588       return SDValue();
3589     }
3590
3591     SDValue Chain = LD->getChain();
3592     // Make sure the stack object alignment is at least 16.
3593     MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
3594     if (DAG.InferPtrAlignment(Ptr) < 16) {
3595       if (MFI->isFixedObjectIndex(FI)) {
3596         // Can't change the alignment. FIXME: It's possible to compute
3597         // the exact stack offset and reference FI + adjust offset instead.
3598         // If someone *really* cares about this. That's the way to implement it.
3599         return SDValue();
3600       } else {
3601         MFI->setObjectAlignment(FI, 16);
3602       }
3603     }
3604
3605     // (Offset % 16) must be multiple of 4. Then address is then
3606     // Ptr + (Offset & ~15).
3607     if (Offset < 0)
3608       return SDValue();
3609     if ((Offset % 16) & 3)
3610       return SDValue();
3611     int64_t StartOffset = Offset & ~15;
3612     if (StartOffset)
3613       Ptr = DAG.getNode(ISD::ADD, Ptr.getDebugLoc(), Ptr.getValueType(),
3614                         Ptr,DAG.getConstant(StartOffset, Ptr.getValueType()));
3615
3616     int EltNo = (Offset - StartOffset) >> 2;
3617     int Mask[4] = { EltNo, EltNo, EltNo, EltNo };
3618     EVT VT = (PVT == MVT::i32) ? MVT::v4i32 : MVT::v4f32;
3619     SDValue V1 = DAG.getLoad(VT, dl, Chain, Ptr,LD->getSrcValue(),0,
3620                              false, false, 0);
3621     // Canonicalize it to a v4i32 shuffle.
3622     V1 = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v4i32, V1);
3623     return DAG.getNode(ISD::BIT_CONVERT, dl, VT,
3624                        DAG.getVectorShuffle(MVT::v4i32, dl, V1,
3625                                             DAG.getUNDEF(MVT::v4i32), &Mask[0]));
3626   }
3627
3628   return SDValue();
3629 }
3630
3631 SDValue
3632 X86TargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG) {
3633   DebugLoc dl = Op.getDebugLoc();
3634   // All zero's are handled with pxor, all one's are handled with pcmpeqd.
3635   if (ISD::isBuildVectorAllZeros(Op.getNode())
3636       || ISD::isBuildVectorAllOnes(Op.getNode())) {
3637     // Canonicalize this to either <4 x i32> or <2 x i32> (SSE vs MMX) to
3638     // 1) ensure the zero vectors are CSE'd, and 2) ensure that i64 scalars are
3639     // eliminated on x86-32 hosts.
3640     if (Op.getValueType() == MVT::v4i32 || Op.getValueType() == MVT::v2i32)
3641       return Op;
3642
3643     if (ISD::isBuildVectorAllOnes(Op.getNode()))
3644       return getOnesVector(Op.getValueType(), DAG, dl);
3645     return getZeroVector(Op.getValueType(), Subtarget->hasSSE2(), DAG, dl);
3646   }
3647
3648   EVT VT = Op.getValueType();
3649   EVT ExtVT = VT.getVectorElementType();
3650   unsigned EVTBits = ExtVT.getSizeInBits();
3651
3652   unsigned NumElems = Op.getNumOperands();
3653   unsigned NumZero  = 0;
3654   unsigned NumNonZero = 0;
3655   unsigned NonZeros = 0;
3656   bool IsAllConstants = true;
3657   SmallSet<SDValue, 8> Values;
3658   for (unsigned i = 0; i < NumElems; ++i) {
3659     SDValue Elt = Op.getOperand(i);
3660     if (Elt.getOpcode() == ISD::UNDEF)
3661       continue;
3662     Values.insert(Elt);
3663     if (Elt.getOpcode() != ISD::Constant &&
3664         Elt.getOpcode() != ISD::ConstantFP)
3665       IsAllConstants = false;
3666     if (X86::isZeroNode(Elt))
3667       NumZero++;
3668     else {
3669       NonZeros |= (1 << i);
3670       NumNonZero++;
3671     }
3672   }
3673
3674   if (NumNonZero == 0) {
3675     // All undef vector. Return an UNDEF.  All zero vectors were handled above.
3676     return DAG.getUNDEF(VT);
3677   }
3678
3679   // Special case for single non-zero, non-undef, element.
3680   if (NumNonZero == 1) {
3681     unsigned Idx = CountTrailingZeros_32(NonZeros);
3682     SDValue Item = Op.getOperand(Idx);
3683
3684     // If this is an insertion of an i64 value on x86-32, and if the top bits of
3685     // the value are obviously zero, truncate the value to i32 and do the
3686     // insertion that way.  Only do this if the value is non-constant or if the
3687     // value is a constant being inserted into element 0.  It is cheaper to do
3688     // a constant pool load than it is to do a movd + shuffle.
3689     if (ExtVT == MVT::i64 && !Subtarget->is64Bit() &&
3690         (!IsAllConstants || Idx == 0)) {
3691       if (DAG.MaskedValueIsZero(Item, APInt::getBitsSet(64, 32, 64))) {
3692         // Handle MMX and SSE both.
3693         EVT VecVT = VT == MVT::v2i64 ? MVT::v4i32 : MVT::v2i32;
3694         unsigned VecElts = VT == MVT::v2i64 ? 4 : 2;
3695
3696         // Truncate the value (which may itself be a constant) to i32, and
3697         // convert it to a vector with movd (S2V+shuffle to zero extend).
3698         Item = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Item);
3699         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VecVT, Item);
3700         Item = getShuffleVectorZeroOrUndef(Item, 0, true,
3701                                            Subtarget->hasSSE2(), DAG);
3702
3703         // Now we have our 32-bit value zero extended in the low element of
3704         // a vector.  If Idx != 0, swizzle it into place.
3705         if (Idx != 0) {
3706           SmallVector<int, 4> Mask;
3707           Mask.push_back(Idx);
3708           for (unsigned i = 1; i != VecElts; ++i)
3709             Mask.push_back(i);
3710           Item = DAG.getVectorShuffle(VecVT, dl, Item,
3711                                       DAG.getUNDEF(Item.getValueType()),
3712                                       &Mask[0]);
3713         }
3714         return DAG.getNode(ISD::BIT_CONVERT, dl, Op.getValueType(), Item);
3715       }
3716     }
3717
3718     // If we have a constant or non-constant insertion into the low element of
3719     // a vector, we can do this with SCALAR_TO_VECTOR + shuffle of zero into
3720     // the rest of the elements.  This will be matched as movd/movq/movss/movsd
3721     // depending on what the source datatype is.
3722     if (Idx == 0) {
3723       if (NumZero == 0) {
3724         return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
3725       } else if (ExtVT == MVT::i32 || ExtVT == MVT::f32 || ExtVT == MVT::f64 ||
3726           (ExtVT == MVT::i64 && Subtarget->is64Bit())) {
3727         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
3728         // Turn it into a MOVL (i.e. movss, movsd, or movd) to a zero vector.
3729         return getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget->hasSSE2(),
3730                                            DAG);
3731       } else if (ExtVT == MVT::i16 || ExtVT == MVT::i8) {
3732         Item = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, Item);
3733         EVT MiddleVT = VT.getSizeInBits() == 64 ? MVT::v2i32 : MVT::v4i32;
3734         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MiddleVT, Item);
3735         Item = getShuffleVectorZeroOrUndef(Item, 0, true,
3736                                            Subtarget->hasSSE2(), DAG);
3737         return DAG.getNode(ISD::BIT_CONVERT, dl, VT, Item);
3738       }
3739     }
3740
3741     // Is it a vector logical left shift?
3742     if (NumElems == 2 && Idx == 1 &&
3743         X86::isZeroNode(Op.getOperand(0)) &&
3744         !X86::isZeroNode(Op.getOperand(1))) {
3745       unsigned NumBits = VT.getSizeInBits();
3746       return getVShift(true, VT,
3747                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
3748                                    VT, Op.getOperand(1)),
3749                        NumBits/2, DAG, *this, dl);
3750     }
3751
3752     if (IsAllConstants) // Otherwise, it's better to do a constpool load.
3753       return SDValue();
3754
3755     // Otherwise, if this is a vector with i32 or f32 elements, and the element
3756     // is a non-constant being inserted into an element other than the low one,
3757     // we can't use a constant pool load.  Instead, use SCALAR_TO_VECTOR (aka
3758     // movd/movss) to move this into the low element, then shuffle it into
3759     // place.
3760     if (EVTBits == 32) {
3761       Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
3762
3763       // Turn it into a shuffle of zero and zero-extended scalar to vector.
3764       Item = getShuffleVectorZeroOrUndef(Item, 0, NumZero > 0,
3765                                          Subtarget->hasSSE2(), DAG);
3766       SmallVector<int, 8> MaskVec;
3767       for (unsigned i = 0; i < NumElems; i++)
3768         MaskVec.push_back(i == Idx ? 0 : 1);
3769       return DAG.getVectorShuffle(VT, dl, Item, DAG.getUNDEF(VT), &MaskVec[0]);
3770     }
3771   }
3772
3773   // Splat is obviously ok. Let legalizer expand it to a shuffle.
3774   if (Values.size() == 1) {
3775     if (EVTBits == 32) {
3776       // Instead of a shuffle like this:
3777       // shuffle (scalar_to_vector (load (ptr + 4))), undef, <0, 0, 0, 0>
3778       // Check if it's possible to issue this instead.
3779       // shuffle (vload ptr)), undef, <1, 1, 1, 1>
3780       unsigned Idx = CountTrailingZeros_32(NonZeros);
3781       SDValue Item = Op.getOperand(Idx);
3782       if (Op.getNode()->isOnlyUserOf(Item.getNode()))
3783         return LowerAsSplatVectorLoad(Item, VT, dl, DAG);
3784     }
3785     return SDValue();
3786   }
3787
3788   // A vector full of immediates; various special cases are already
3789   // handled, so this is best done with a single constant-pool load.
3790   if (IsAllConstants)
3791     return SDValue();
3792
3793   // Let legalizer expand 2-wide build_vectors.
3794   if (EVTBits == 64) {
3795     if (NumNonZero == 1) {
3796       // One half is zero or undef.
3797       unsigned Idx = CountTrailingZeros_32(NonZeros);
3798       SDValue V2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT,
3799                                  Op.getOperand(Idx));
3800       return getShuffleVectorZeroOrUndef(V2, Idx, true,
3801                                          Subtarget->hasSSE2(), DAG);
3802     }
3803     return SDValue();
3804   }
3805
3806   // If element VT is < 32 bits, convert it to inserts into a zero vector.
3807   if (EVTBits == 8 && NumElems == 16) {
3808     SDValue V = LowerBuildVectorv16i8(Op, NonZeros,NumNonZero,NumZero, DAG,
3809                                         *this);
3810     if (V.getNode()) return V;
3811   }
3812
3813   if (EVTBits == 16 && NumElems == 8) {
3814     SDValue V = LowerBuildVectorv8i16(Op, NonZeros,NumNonZero,NumZero, DAG,
3815                                         *this);
3816     if (V.getNode()) return V;
3817   }
3818
3819   // If element VT is == 32 bits, turn it into a number of shuffles.
3820   SmallVector<SDValue, 8> V;
3821   V.resize(NumElems);
3822   if (NumElems == 4 && NumZero > 0) {
3823     for (unsigned i = 0; i < 4; ++i) {
3824       bool isZero = !(NonZeros & (1 << i));
3825       if (isZero)
3826         V[i] = getZeroVector(VT, Subtarget->hasSSE2(), DAG, dl);
3827       else
3828         V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
3829     }
3830
3831     for (unsigned i = 0; i < 2; ++i) {
3832       switch ((NonZeros & (0x3 << i*2)) >> (i*2)) {
3833         default: break;
3834         case 0:
3835           V[i] = V[i*2];  // Must be a zero vector.
3836           break;
3837         case 1:
3838           V[i] = getMOVL(DAG, dl, VT, V[i*2+1], V[i*2]);
3839           break;
3840         case 2:
3841           V[i] = getMOVL(DAG, dl, VT, V[i*2], V[i*2+1]);
3842           break;
3843         case 3:
3844           V[i] = getUnpackl(DAG, dl, VT, V[i*2], V[i*2+1]);
3845           break;
3846       }
3847     }
3848
3849     SmallVector<int, 8> MaskVec;
3850     bool Reverse = (NonZeros & 0x3) == 2;
3851     for (unsigned i = 0; i < 2; ++i)
3852       MaskVec.push_back(Reverse ? 1-i : i);
3853     Reverse = ((NonZeros & (0x3 << 2)) >> 2) == 2;
3854     for (unsigned i = 0; i < 2; ++i)
3855       MaskVec.push_back(Reverse ? 1-i+NumElems : i+NumElems);
3856     return DAG.getVectorShuffle(VT, dl, V[0], V[1], &MaskVec[0]);
3857   }
3858
3859   if (Values.size() > 2) {
3860     // If we have SSE 4.1, Expand into a number of inserts unless the number of
3861     // values to be inserted is equal to the number of elements, in which case
3862     // use the unpack code below in the hopes of matching the consecutive elts
3863     // load merge pattern for shuffles.
3864     // FIXME: We could probably just check that here directly.
3865     if (Values.size() < NumElems && VT.getSizeInBits() == 128 &&
3866         getSubtarget()->hasSSE41()) {
3867       V[0] = DAG.getUNDEF(VT);
3868       for (unsigned i = 0; i < NumElems; ++i)
3869         if (Op.getOperand(i).getOpcode() != ISD::UNDEF)
3870           V[0] = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, V[0],
3871                              Op.getOperand(i), DAG.getIntPtrConstant(i));
3872       return V[0];
3873     }
3874     // Expand into a number of unpckl*.
3875     // e.g. for v4f32
3876     //   Step 1: unpcklps 0, 2 ==> X: <?, ?, 2, 0>
3877     //         : unpcklps 1, 3 ==> Y: <?, ?, 3, 1>
3878     //   Step 2: unpcklps X, Y ==>    <3, 2, 1, 0>
3879     for (unsigned i = 0; i < NumElems; ++i)
3880       V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
3881     NumElems >>= 1;
3882     while (NumElems != 0) {
3883       for (unsigned i = 0; i < NumElems; ++i)
3884         V[i] = getUnpackl(DAG, dl, VT, V[i], V[i + NumElems]);
3885       NumElems >>= 1;
3886     }
3887     return V[0];
3888   }
3889
3890   return SDValue();
3891 }
3892
3893 SDValue
3894 X86TargetLowering::LowerCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
3895   // We support concatenate two MMX registers and place them in a MMX
3896   // register.  This is better than doing a stack convert.
3897   DebugLoc dl = Op.getDebugLoc();
3898   EVT ResVT = Op.getValueType();
3899   assert(Op.getNumOperands() == 2);
3900   assert(ResVT == MVT::v2i64 || ResVT == MVT::v4i32 ||
3901          ResVT == MVT::v8i16 || ResVT == MVT::v16i8);
3902   int Mask[2];
3903   SDValue InVec = DAG.getNode(ISD::BIT_CONVERT,dl, MVT::v1i64, Op.getOperand(0));
3904   SDValue VecOp = DAG.getNode(X86ISD::MOVQ2DQ, dl, MVT::v2i64, InVec);
3905   InVec = Op.getOperand(1);
3906   if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR) {
3907     unsigned NumElts = ResVT.getVectorNumElements();
3908     VecOp = DAG.getNode(ISD::BIT_CONVERT, dl, ResVT, VecOp);
3909     VecOp = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, ResVT, VecOp,
3910                        InVec.getOperand(0), DAG.getIntPtrConstant(NumElts/2+1));
3911   } else {
3912     InVec = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v1i64, InVec);
3913     SDValue VecOp2 = DAG.getNode(X86ISD::MOVQ2DQ, dl, MVT::v2i64, InVec);
3914     Mask[0] = 0; Mask[1] = 2;
3915     VecOp = DAG.getVectorShuffle(MVT::v2i64, dl, VecOp, VecOp2, Mask);
3916   }
3917   return DAG.getNode(ISD::BIT_CONVERT, dl, ResVT, VecOp);
3918 }
3919
3920 // v8i16 shuffles - Prefer shuffles in the following order:
3921 // 1. [all]   pshuflw, pshufhw, optional move
3922 // 2. [ssse3] 1 x pshufb
3923 // 3. [ssse3] 2 x pshufb + 1 x por
3924 // 4. [all]   mov + pshuflw + pshufhw + N x (pextrw + pinsrw)
3925 static
3926 SDValue LowerVECTOR_SHUFFLEv8i16(ShuffleVectorSDNode *SVOp,
3927                                  SelectionDAG &DAG, X86TargetLowering &TLI) {
3928   SDValue V1 = SVOp->getOperand(0);
3929   SDValue V2 = SVOp->getOperand(1);
3930   DebugLoc dl = SVOp->getDebugLoc();
3931   SmallVector<int, 8> MaskVals;
3932
3933   // Determine if more than 1 of the words in each of the low and high quadwords
3934   // of the result come from the same quadword of one of the two inputs.  Undef
3935   // mask values count as coming from any quadword, for better codegen.
3936   SmallVector<unsigned, 4> LoQuad(4);
3937   SmallVector<unsigned, 4> HiQuad(4);
3938   BitVector InputQuads(4);
3939   for (unsigned i = 0; i < 8; ++i) {
3940     SmallVectorImpl<unsigned> &Quad = i < 4 ? LoQuad : HiQuad;
3941     int EltIdx = SVOp->getMaskElt(i);
3942     MaskVals.push_back(EltIdx);
3943     if (EltIdx < 0) {
3944       ++Quad[0];
3945       ++Quad[1];
3946       ++Quad[2];
3947       ++Quad[3];
3948       continue;
3949     }
3950     ++Quad[EltIdx / 4];
3951     InputQuads.set(EltIdx / 4);
3952   }
3953
3954   int BestLoQuad = -1;
3955   unsigned MaxQuad = 1;
3956   for (unsigned i = 0; i < 4; ++i) {
3957     if (LoQuad[i] > MaxQuad) {
3958       BestLoQuad = i;
3959       MaxQuad = LoQuad[i];
3960     }
3961   }
3962
3963   int BestHiQuad = -1;
3964   MaxQuad = 1;
3965   for (unsigned i = 0; i < 4; ++i) {
3966     if (HiQuad[i] > MaxQuad) {
3967       BestHiQuad = i;
3968       MaxQuad = HiQuad[i];
3969     }
3970   }
3971
3972   // For SSSE3, If all 8 words of the result come from only 1 quadword of each
3973   // of the two input vectors, shuffle them into one input vector so only a
3974   // single pshufb instruction is necessary. If There are more than 2 input
3975   // quads, disable the next transformation since it does not help SSSE3.
3976   bool V1Used = InputQuads[0] || InputQuads[1];
3977   bool V2Used = InputQuads[2] || InputQuads[3];
3978   if (TLI.getSubtarget()->hasSSSE3()) {
3979     if (InputQuads.count() == 2 && V1Used && V2Used) {
3980       BestLoQuad = InputQuads.find_first();
3981       BestHiQuad = InputQuads.find_next(BestLoQuad);
3982     }
3983     if (InputQuads.count() > 2) {
3984       BestLoQuad = -1;
3985       BestHiQuad = -1;
3986     }
3987   }
3988
3989   // If BestLoQuad or BestHiQuad are set, shuffle the quads together and update
3990   // the shuffle mask.  If a quad is scored as -1, that means that it contains
3991   // words from all 4 input quadwords.
3992   SDValue NewV;
3993   if (BestLoQuad >= 0 || BestHiQuad >= 0) {
3994     SmallVector<int, 8> MaskV;
3995     MaskV.push_back(BestLoQuad < 0 ? 0 : BestLoQuad);
3996     MaskV.push_back(BestHiQuad < 0 ? 1 : BestHiQuad);
3997     NewV = DAG.getVectorShuffle(MVT::v2i64, dl,
3998                   DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v2i64, V1),
3999                   DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v2i64, V2), &MaskV[0]);
4000     NewV = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v8i16, NewV);
4001
4002     // Rewrite the MaskVals and assign NewV to V1 if NewV now contains all the
4003     // source words for the shuffle, to aid later transformations.
4004     bool AllWordsInNewV = true;
4005     bool InOrder[2] = { true, true };
4006     for (unsigned i = 0; i != 8; ++i) {
4007       int idx = MaskVals[i];
4008       if (idx != (int)i)
4009         InOrder[i/4] = false;
4010       if (idx < 0 || (idx/4) == BestLoQuad || (idx/4) == BestHiQuad)
4011         continue;
4012       AllWordsInNewV = false;
4013       break;
4014     }
4015
4016     bool pshuflw = AllWordsInNewV, pshufhw = AllWordsInNewV;
4017     if (AllWordsInNewV) {
4018       for (int i = 0; i != 8; ++i) {
4019         int idx = MaskVals[i];
4020         if (idx < 0)
4021           continue;
4022         idx = MaskVals[i] = (idx / 4) == BestLoQuad ? (idx & 3) : (idx & 3) + 4;
4023         if ((idx != i) && idx < 4)
4024           pshufhw = false;
4025         if ((idx != i) && idx > 3)
4026           pshuflw = false;
4027       }
4028       V1 = NewV;
4029       V2Used = false;
4030       BestLoQuad = 0;
4031       BestHiQuad = 1;
4032     }
4033
4034     // If we've eliminated the use of V2, and the new mask is a pshuflw or
4035     // pshufhw, that's as cheap as it gets.  Return the new shuffle.
4036     if ((pshufhw && InOrder[0]) || (pshuflw && InOrder[1])) {
4037       return DAG.getVectorShuffle(MVT::v8i16, dl, NewV,
4038                                   DAG.getUNDEF(MVT::v8i16), &MaskVals[0]);
4039     }
4040   }
4041
4042   // If we have SSSE3, and all words of the result are from 1 input vector,
4043   // case 2 is generated, otherwise case 3 is generated.  If no SSSE3
4044   // is present, fall back to case 4.
4045   if (TLI.getSubtarget()->hasSSSE3()) {
4046     SmallVector<SDValue,16> pshufbMask;
4047
4048     // If we have elements from both input vectors, set the high bit of the
4049     // shuffle mask element to zero out elements that come from V2 in the V1
4050     // mask, and elements that come from V1 in the V2 mask, so that the two
4051     // results can be OR'd together.
4052     bool TwoInputs = V1Used && V2Used;
4053     for (unsigned i = 0; i != 8; ++i) {
4054       int EltIdx = MaskVals[i] * 2;
4055       if (TwoInputs && (EltIdx >= 16)) {
4056         pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
4057         pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
4058         continue;
4059       }
4060       pshufbMask.push_back(DAG.getConstant(EltIdx,   MVT::i8));
4061       pshufbMask.push_back(DAG.getConstant(EltIdx+1, MVT::i8));
4062     }
4063     V1 = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v16i8, V1);
4064     V1 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V1,
4065                      DAG.getNode(ISD::BUILD_VECTOR, dl,
4066                                  MVT::v16i8, &pshufbMask[0], 16));
4067     if (!TwoInputs)
4068       return DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v8i16, V1);
4069
4070     // Calculate the shuffle mask for the second input, shuffle it, and
4071     // OR it with the first shuffled input.
4072     pshufbMask.clear();
4073     for (unsigned i = 0; i != 8; ++i) {
4074       int EltIdx = MaskVals[i] * 2;
4075       if (EltIdx < 16) {
4076         pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
4077         pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
4078         continue;
4079       }
4080       pshufbMask.push_back(DAG.getConstant(EltIdx - 16, MVT::i8));
4081       pshufbMask.push_back(DAG.getConstant(EltIdx - 15, MVT::i8));
4082     }
4083     V2 = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v16i8, V2);
4084     V2 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V2,
4085                      DAG.getNode(ISD::BUILD_VECTOR, dl,
4086                                  MVT::v16i8, &pshufbMask[0], 16));
4087     V1 = DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2);
4088     return DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v8i16, V1);
4089   }
4090
4091   // If BestLoQuad >= 0, generate a pshuflw to put the low elements in order,
4092   // and update MaskVals with new element order.
4093   BitVector InOrder(8);
4094   if (BestLoQuad >= 0) {
4095     SmallVector<int, 8> MaskV;
4096     for (int i = 0; i != 4; ++i) {
4097       int idx = MaskVals[i];
4098       if (idx < 0) {
4099         MaskV.push_back(-1);
4100         InOrder.set(i);
4101       } else if ((idx / 4) == BestLoQuad) {
4102         MaskV.push_back(idx & 3);
4103         InOrder.set(i);
4104       } else {
4105         MaskV.push_back(-1);
4106       }
4107     }
4108     for (unsigned i = 4; i != 8; ++i)
4109       MaskV.push_back(i);
4110     NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::v8i16),
4111                                 &MaskV[0]);
4112   }
4113
4114   // If BestHi >= 0, generate a pshufhw to put the high elements in order,
4115   // and update MaskVals with the new element order.
4116   if (BestHiQuad >= 0) {
4117     SmallVector<int, 8> MaskV;
4118     for (unsigned i = 0; i != 4; ++i)
4119       MaskV.push_back(i);
4120     for (unsigned i = 4; i != 8; ++i) {
4121       int idx = MaskVals[i];
4122       if (idx < 0) {
4123         MaskV.push_back(-1);
4124         InOrder.set(i);
4125       } else if ((idx / 4) == BestHiQuad) {
4126         MaskV.push_back((idx & 3) + 4);
4127         InOrder.set(i);
4128       } else {
4129         MaskV.push_back(-1);
4130       }
4131     }
4132     NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::v8i16),
4133                                 &MaskV[0]);
4134   }
4135
4136   // In case BestHi & BestLo were both -1, which means each quadword has a word
4137   // from each of the four input quadwords, calculate the InOrder bitvector now
4138   // before falling through to the insert/extract cleanup.
4139   if (BestLoQuad == -1 && BestHiQuad == -1) {
4140     NewV = V1;
4141     for (int i = 0; i != 8; ++i)
4142       if (MaskVals[i] < 0 || MaskVals[i] == i)
4143         InOrder.set(i);
4144   }
4145
4146   // The other elements are put in the right place using pextrw and pinsrw.
4147   for (unsigned i = 0; i != 8; ++i) {
4148     if (InOrder[i])
4149       continue;
4150     int EltIdx = MaskVals[i];
4151     if (EltIdx < 0)
4152       continue;
4153     SDValue ExtOp = (EltIdx < 8)
4154     ? DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V1,
4155                   DAG.getIntPtrConstant(EltIdx))
4156     : DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V2,
4157                   DAG.getIntPtrConstant(EltIdx - 8));
4158     NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, ExtOp,
4159                        DAG.getIntPtrConstant(i));
4160   }
4161   return NewV;
4162 }
4163
4164 // v16i8 shuffles - Prefer shuffles in the following order:
4165 // 1. [ssse3] 1 x pshufb
4166 // 2. [ssse3] 2 x pshufb + 1 x por
4167 // 3. [all]   v8i16 shuffle + N x pextrw + rotate + pinsrw
4168 static
4169 SDValue LowerVECTOR_SHUFFLEv16i8(ShuffleVectorSDNode *SVOp,
4170                                  SelectionDAG &DAG, X86TargetLowering &TLI) {
4171   SDValue V1 = SVOp->getOperand(0);
4172   SDValue V2 = SVOp->getOperand(1);
4173   DebugLoc dl = SVOp->getDebugLoc();
4174   SmallVector<int, 16> MaskVals;
4175   SVOp->getMask(MaskVals);
4176
4177   // If we have SSSE3, case 1 is generated when all result bytes come from
4178   // one of  the inputs.  Otherwise, case 2 is generated.  If no SSSE3 is
4179   // present, fall back to case 3.
4180   // FIXME: kill V2Only once shuffles are canonizalized by getNode.
4181   bool V1Only = true;
4182   bool V2Only = true;
4183   for (unsigned i = 0; i < 16; ++i) {
4184     int EltIdx = MaskVals[i];
4185     if (EltIdx < 0)
4186       continue;
4187     if (EltIdx < 16)
4188       V2Only = false;
4189     else
4190       V1Only = false;
4191   }
4192
4193   // If SSSE3, use 1 pshufb instruction per vector with elements in the result.
4194   if (TLI.getSubtarget()->hasSSSE3()) {
4195     SmallVector<SDValue,16> pshufbMask;
4196
4197     // If all result elements are from one input vector, then only translate
4198     // undef mask values to 0x80 (zero out result) in the pshufb mask.
4199     //
4200     // Otherwise, we have elements from both input vectors, and must zero out
4201     // elements that come from V2 in the first mask, and V1 in the second mask
4202     // so that we can OR them together.
4203     bool TwoInputs = !(V1Only || V2Only);
4204     for (unsigned i = 0; i != 16; ++i) {
4205       int EltIdx = MaskVals[i];
4206       if (EltIdx < 0 || (TwoInputs && EltIdx >= 16)) {
4207         pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
4208         continue;
4209       }
4210       pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8));
4211     }
4212     // If all the elements are from V2, assign it to V1 and return after
4213     // building the first pshufb.
4214     if (V2Only)
4215       V1 = V2;
4216     V1 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V1,
4217                      DAG.getNode(ISD::BUILD_VECTOR, dl,
4218                                  MVT::v16i8, &pshufbMask[0], 16));
4219     if (!TwoInputs)
4220       return V1;
4221
4222     // Calculate the shuffle mask for the second input, shuffle it, and
4223     // OR it with the first shuffled input.
4224     pshufbMask.clear();
4225     for (unsigned i = 0; i != 16; ++i) {
4226       int EltIdx = MaskVals[i];
4227       if (EltIdx < 16) {
4228         pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
4229         continue;
4230       }
4231       pshufbMask.push_back(DAG.getConstant(EltIdx - 16, MVT::i8));
4232     }
4233     V2 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V2,
4234                      DAG.getNode(ISD::BUILD_VECTOR, dl,
4235                                  MVT::v16i8, &pshufbMask[0], 16));
4236     return DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2);
4237   }
4238
4239   // No SSSE3 - Calculate in place words and then fix all out of place words
4240   // With 0-16 extracts & inserts.  Worst case is 16 bytes out of order from
4241   // the 16 different words that comprise the two doublequadword input vectors.
4242   V1 = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v8i16, V1);
4243   V2 = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v8i16, V2);
4244   SDValue NewV = V2Only ? V2 : V1;
4245   for (int i = 0; i != 8; ++i) {
4246     int Elt0 = MaskVals[i*2];
4247     int Elt1 = MaskVals[i*2+1];
4248
4249     // This word of the result is all undef, skip it.
4250     if (Elt0 < 0 && Elt1 < 0)
4251       continue;
4252
4253     // This word of the result is already in the correct place, skip it.
4254     if (V1Only && (Elt0 == i*2) && (Elt1 == i*2+1))
4255       continue;
4256     if (V2Only && (Elt0 == i*2+16) && (Elt1 == i*2+17))
4257       continue;
4258
4259     SDValue Elt0Src = Elt0 < 16 ? V1 : V2;
4260     SDValue Elt1Src = Elt1 < 16 ? V1 : V2;
4261     SDValue InsElt;
4262
4263     // If Elt0 and Elt1 are defined, are consecutive, and can be load
4264     // using a single extract together, load it and store it.
4265     if ((Elt0 >= 0) && ((Elt0 + 1) == Elt1) && ((Elt0 & 1) == 0)) {
4266       InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src,
4267                            DAG.getIntPtrConstant(Elt1 / 2));
4268       NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt,
4269                         DAG.getIntPtrConstant(i));
4270       continue;
4271     }
4272
4273     // If Elt1 is defined, extract it from the appropriate source.  If the
4274     // source byte is not also odd, shift the extracted word left 8 bits
4275     // otherwise clear the bottom 8 bits if we need to do an or.
4276     if (Elt1 >= 0) {
4277       InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src,
4278                            DAG.getIntPtrConstant(Elt1 / 2));
4279       if ((Elt1 & 1) == 0)
4280         InsElt = DAG.getNode(ISD::SHL, dl, MVT::i16, InsElt,
4281                              DAG.getConstant(8, TLI.getShiftAmountTy()));
4282       else if (Elt0 >= 0)
4283         InsElt = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt,
4284                              DAG.getConstant(0xFF00, MVT::i16));
4285     }
4286     // If Elt0 is defined, extract it from the appropriate source.  If the
4287     // source byte is not also even, shift the extracted word right 8 bits. If
4288     // Elt1 was also defined, OR the extracted values together before
4289     // inserting them in the result.
4290     if (Elt0 >= 0) {
4291       SDValue InsElt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16,
4292                                     Elt0Src, DAG.getIntPtrConstant(Elt0 / 2));
4293       if ((Elt0 & 1) != 0)
4294         InsElt0 = DAG.getNode(ISD::SRL, dl, MVT::i16, InsElt0,
4295                               DAG.getConstant(8, TLI.getShiftAmountTy()));
4296       else if (Elt1 >= 0)
4297         InsElt0 = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt0,
4298                              DAG.getConstant(0x00FF, MVT::i16));
4299       InsElt = Elt1 >= 0 ? DAG.getNode(ISD::OR, dl, MVT::i16, InsElt, InsElt0)
4300                          : InsElt0;
4301     }
4302     NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt,
4303                        DAG.getIntPtrConstant(i));
4304   }
4305   return DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v16i8, NewV);
4306 }
4307
4308 /// RewriteAsNarrowerShuffle - Try rewriting v8i16 and v16i8 shuffles as 4 wide
4309 /// ones, or rewriting v4i32 / v2f32 as 2 wide ones if possible. This can be
4310 /// done when every pair / quad of shuffle mask elements point to elements in
4311 /// the right sequence. e.g.
4312 /// vector_shuffle <>, <>, < 3, 4, | 10, 11, | 0, 1, | 14, 15>
4313 static
4314 SDValue RewriteAsNarrowerShuffle(ShuffleVectorSDNode *SVOp,
4315                                  SelectionDAG &DAG,
4316                                  TargetLowering &TLI, DebugLoc dl) {
4317   EVT VT = SVOp->getValueType(0);
4318   SDValue V1 = SVOp->getOperand(0);
4319   SDValue V2 = SVOp->getOperand(1);
4320   unsigned NumElems = VT.getVectorNumElements();
4321   unsigned NewWidth = (NumElems == 4) ? 2 : 4;
4322   EVT MaskVT = MVT::getIntVectorWithNumElements(NewWidth);
4323   EVT MaskEltVT = MaskVT.getVectorElementType();
4324   EVT NewVT = MaskVT;
4325   switch (VT.getSimpleVT().SimpleTy) {
4326   default: assert(false && "Unexpected!");
4327   case MVT::v4f32: NewVT = MVT::v2f64; break;
4328   case MVT::v4i32: NewVT = MVT::v2i64; break;
4329   case MVT::v8i16: NewVT = MVT::v4i32; break;
4330   case MVT::v16i8: NewVT = MVT::v4i32; break;
4331   }
4332
4333   if (NewWidth == 2) {
4334     if (VT.isInteger())
4335       NewVT = MVT::v2i64;
4336     else
4337       NewVT = MVT::v2f64;
4338   }
4339   int Scale = NumElems / NewWidth;
4340   SmallVector<int, 8> MaskVec;
4341   for (unsigned i = 0; i < NumElems; i += Scale) {
4342     int StartIdx = -1;
4343     for (int j = 0; j < Scale; ++j) {
4344       int EltIdx = SVOp->getMaskElt(i+j);
4345       if (EltIdx < 0)
4346         continue;
4347       if (StartIdx == -1)
4348         StartIdx = EltIdx - (EltIdx % Scale);
4349       if (EltIdx != StartIdx + j)
4350         return SDValue();
4351     }
4352     if (StartIdx == -1)
4353       MaskVec.push_back(-1);
4354     else
4355       MaskVec.push_back(StartIdx / Scale);
4356   }
4357
4358   V1 = DAG.getNode(ISD::BIT_CONVERT, dl, NewVT, V1);
4359   V2 = DAG.getNode(ISD::BIT_CONVERT, dl, NewVT, V2);
4360   return DAG.getVectorShuffle(NewVT, dl, V1, V2, &MaskVec[0]);
4361 }
4362
4363 /// getVZextMovL - Return a zero-extending vector move low node.
4364 ///
4365 static SDValue getVZextMovL(EVT VT, EVT OpVT,
4366                             SDValue SrcOp, SelectionDAG &DAG,
4367                             const X86Subtarget *Subtarget, DebugLoc dl) {
4368   if (VT == MVT::v2f64 || VT == MVT::v4f32) {
4369     LoadSDNode *LD = NULL;
4370     if (!isScalarLoadToVector(SrcOp.getNode(), &LD))
4371       LD = dyn_cast<LoadSDNode>(SrcOp);
4372     if (!LD) {
4373       // movssrr and movsdrr do not clear top bits. Try to use movd, movq
4374       // instead.
4375       MVT ExtVT = (OpVT == MVT::v2f64) ? MVT::i64 : MVT::i32;
4376       if ((ExtVT.SimpleTy != MVT::i64 || Subtarget->is64Bit()) &&
4377           SrcOp.getOpcode() == ISD::SCALAR_TO_VECTOR &&
4378           SrcOp.getOperand(0).getOpcode() == ISD::BIT_CONVERT &&
4379           SrcOp.getOperand(0).getOperand(0).getValueType() == ExtVT) {
4380         // PR2108
4381         OpVT = (OpVT == MVT::v2f64) ? MVT::v2i64 : MVT::v4i32;
4382         return DAG.getNode(ISD::BIT_CONVERT, dl, VT,
4383                            DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT,
4384                                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
4385                                                    OpVT,
4386                                                    SrcOp.getOperand(0)
4387                                                           .getOperand(0))));
4388       }
4389     }
4390   }
4391
4392   return DAG.getNode(ISD::BIT_CONVERT, dl, VT,
4393                      DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT,
4394                                  DAG.getNode(ISD::BIT_CONVERT, dl,
4395                                              OpVT, SrcOp)));
4396 }
4397
4398 /// LowerVECTOR_SHUFFLE_4wide - Handle all 4 wide cases with a number of
4399 /// shuffles.
4400 static SDValue
4401 LowerVECTOR_SHUFFLE_4wide(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
4402   SDValue V1 = SVOp->getOperand(0);
4403   SDValue V2 = SVOp->getOperand(1);
4404   DebugLoc dl = SVOp->getDebugLoc();
4405   EVT VT = SVOp->getValueType(0);
4406
4407   SmallVector<std::pair<int, int>, 8> Locs;
4408   Locs.resize(4);
4409   SmallVector<int, 8> Mask1(4U, -1);
4410   SmallVector<int, 8> PermMask;
4411   SVOp->getMask(PermMask);
4412
4413   unsigned NumHi = 0;
4414   unsigned NumLo = 0;
4415   for (unsigned i = 0; i != 4; ++i) {
4416     int Idx = PermMask[i];
4417     if (Idx < 0) {
4418       Locs[i] = std::make_pair(-1, -1);
4419     } else {
4420       assert(Idx < 8 && "Invalid VECTOR_SHUFFLE index!");
4421       if (Idx < 4) {
4422         Locs[i] = std::make_pair(0, NumLo);
4423         Mask1[NumLo] = Idx;
4424         NumLo++;
4425       } else {
4426         Locs[i] = std::make_pair(1, NumHi);
4427         if (2+NumHi < 4)
4428           Mask1[2+NumHi] = Idx;
4429         NumHi++;
4430       }
4431     }
4432   }
4433
4434   if (NumLo <= 2 && NumHi <= 2) {
4435     // If no more than two elements come from either vector. This can be
4436     // implemented with two shuffles. First shuffle gather the elements.
4437     // The second shuffle, which takes the first shuffle as both of its
4438     // vector operands, put the elements into the right order.
4439     V1 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
4440
4441     SmallVector<int, 8> Mask2(4U, -1);
4442
4443     for (unsigned i = 0; i != 4; ++i) {
4444       if (Locs[i].first == -1)
4445         continue;
4446       else {
4447         unsigned Idx = (i < 2) ? 0 : 4;
4448         Idx += Locs[i].first * 2 + Locs[i].second;
4449         Mask2[i] = Idx;
4450       }
4451     }
4452
4453     return DAG.getVectorShuffle(VT, dl, V1, V1, &Mask2[0]);
4454   } else if (NumLo == 3 || NumHi == 3) {
4455     // Otherwise, we must have three elements from one vector, call it X, and
4456     // one element from the other, call it Y.  First, use a shufps to build an
4457     // intermediate vector with the one element from Y and the element from X
4458     // that will be in the same half in the final destination (the indexes don't
4459     // matter). Then, use a shufps to build the final vector, taking the half
4460     // containing the element from Y from the intermediate, and the other half
4461     // from X.
4462     if (NumHi == 3) {
4463       // Normalize it so the 3 elements come from V1.
4464       CommuteVectorShuffleMask(PermMask, VT);
4465       std::swap(V1, V2);
4466     }
4467
4468     // Find the element from V2.
4469     unsigned HiIndex;
4470     for (HiIndex = 0; HiIndex < 3; ++HiIndex) {
4471       int Val = PermMask[HiIndex];
4472       if (Val < 0)
4473         continue;
4474       if (Val >= 4)
4475         break;
4476     }
4477
4478     Mask1[0] = PermMask[HiIndex];
4479     Mask1[1] = -1;
4480     Mask1[2] = PermMask[HiIndex^1];
4481     Mask1[3] = -1;
4482     V2 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
4483
4484     if (HiIndex >= 2) {
4485       Mask1[0] = PermMask[0];
4486       Mask1[1] = PermMask[1];
4487       Mask1[2] = HiIndex & 1 ? 6 : 4;
4488       Mask1[3] = HiIndex & 1 ? 4 : 6;
4489       return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
4490     } else {
4491       Mask1[0] = HiIndex & 1 ? 2 : 0;
4492       Mask1[1] = HiIndex & 1 ? 0 : 2;
4493       Mask1[2] = PermMask[2];
4494       Mask1[3] = PermMask[3];
4495       if (Mask1[2] >= 0)
4496         Mask1[2] += 4;
4497       if (Mask1[3] >= 0)
4498         Mask1[3] += 4;
4499       return DAG.getVectorShuffle(VT, dl, V2, V1, &Mask1[0]);
4500     }
4501   }
4502
4503   // Break it into (shuffle shuffle_hi, shuffle_lo).
4504   Locs.clear();
4505   SmallVector<int,8> LoMask(4U, -1);
4506   SmallVector<int,8> HiMask(4U, -1);
4507
4508   SmallVector<int,8> *MaskPtr = &LoMask;
4509   unsigned MaskIdx = 0;
4510   unsigned LoIdx = 0;
4511   unsigned HiIdx = 2;
4512   for (unsigned i = 0; i != 4; ++i) {
4513     if (i == 2) {
4514       MaskPtr = &HiMask;
4515       MaskIdx = 1;
4516       LoIdx = 0;
4517       HiIdx = 2;
4518     }
4519     int Idx = PermMask[i];
4520     if (Idx < 0) {
4521       Locs[i] = std::make_pair(-1, -1);
4522     } else if (Idx < 4) {
4523       Locs[i] = std::make_pair(MaskIdx, LoIdx);
4524       (*MaskPtr)[LoIdx] = Idx;
4525       LoIdx++;
4526     } else {
4527       Locs[i] = std::make_pair(MaskIdx, HiIdx);
4528       (*MaskPtr)[HiIdx] = Idx;
4529       HiIdx++;
4530     }
4531   }
4532
4533   SDValue LoShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &LoMask[0]);
4534   SDValue HiShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &HiMask[0]);
4535   SmallVector<int, 8> MaskOps;
4536   for (unsigned i = 0; i != 4; ++i) {
4537     if (Locs[i].first == -1) {
4538       MaskOps.push_back(-1);
4539     } else {
4540       unsigned Idx = Locs[i].first * 4 + Locs[i].second;
4541       MaskOps.push_back(Idx);
4542     }
4543   }
4544   return DAG.getVectorShuffle(VT, dl, LoShuffle, HiShuffle, &MaskOps[0]);
4545 }
4546
4547 SDValue
4548 X86TargetLowering::LowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG) {
4549   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
4550   SDValue V1 = Op.getOperand(0);
4551   SDValue V2 = Op.getOperand(1);
4552   EVT VT = Op.getValueType();
4553   DebugLoc dl = Op.getDebugLoc();
4554   unsigned NumElems = VT.getVectorNumElements();
4555   bool isMMX = VT.getSizeInBits() == 64;
4556   bool V1IsUndef = V1.getOpcode() == ISD::UNDEF;
4557   bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
4558   bool V1IsSplat = false;
4559   bool V2IsSplat = false;
4560
4561   if (isZeroShuffle(SVOp))
4562     return getZeroVector(VT, Subtarget->hasSSE2(), DAG, dl);
4563
4564   // Promote splats to v4f32.
4565   if (SVOp->isSplat()) {
4566     if (isMMX || NumElems < 4)
4567       return Op;
4568     return PromoteSplat(SVOp, DAG, Subtarget->hasSSE2());
4569   }
4570
4571   // If the shuffle can be profitably rewritten as a narrower shuffle, then
4572   // do it!
4573   if (VT == MVT::v8i16 || VT == MVT::v16i8) {
4574     SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG, *this, dl);
4575     if (NewOp.getNode())
4576       return DAG.getNode(ISD::BIT_CONVERT, dl, VT,
4577                          LowerVECTOR_SHUFFLE(NewOp, DAG));
4578   } else if ((VT == MVT::v4i32 || (VT == MVT::v4f32 && Subtarget->hasSSE2()))) {
4579     // FIXME: Figure out a cleaner way to do this.
4580     // Try to make use of movq to zero out the top part.
4581     if (ISD::isBuildVectorAllZeros(V2.getNode())) {
4582       SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG, *this, dl);
4583       if (NewOp.getNode()) {
4584         if (isCommutedMOVL(cast<ShuffleVectorSDNode>(NewOp), true, false))
4585           return getVZextMovL(VT, NewOp.getValueType(), NewOp.getOperand(0),
4586                               DAG, Subtarget, dl);
4587       }
4588     } else if (ISD::isBuildVectorAllZeros(V1.getNode())) {
4589       SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG, *this, dl);
4590       if (NewOp.getNode() && X86::isMOVLMask(cast<ShuffleVectorSDNode>(NewOp)))
4591         return getVZextMovL(VT, NewOp.getValueType(), NewOp.getOperand(1),
4592                             DAG, Subtarget, dl);
4593     }
4594   }
4595
4596   if (X86::isPSHUFDMask(SVOp))
4597     return Op;
4598
4599   // Check if this can be converted into a logical shift.
4600   bool isLeft = false;
4601   unsigned ShAmt = 0;
4602   SDValue ShVal;
4603   bool isShift = getSubtarget()->hasSSE2() &&
4604     isVectorShift(SVOp, DAG, isLeft, ShVal, ShAmt);
4605   if (isShift && ShVal.hasOneUse()) {
4606     // If the shifted value has multiple uses, it may be cheaper to use
4607     // v_set0 + movlhps or movhlps, etc.
4608     EVT EltVT = VT.getVectorElementType();
4609     ShAmt *= EltVT.getSizeInBits();
4610     return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
4611   }
4612
4613   if (X86::isMOVLMask(SVOp)) {
4614     if (V1IsUndef)
4615       return V2;
4616     if (ISD::isBuildVectorAllZeros(V1.getNode()))
4617       return getVZextMovL(VT, VT, V2, DAG, Subtarget, dl);
4618     if (!isMMX)
4619       return Op;
4620   }
4621
4622   // FIXME: fold these into legal mask.
4623   if (!isMMX && (X86::isMOVSHDUPMask(SVOp) ||
4624                  X86::isMOVSLDUPMask(SVOp) ||
4625                  X86::isMOVHLPSMask(SVOp) ||
4626                  X86::isMOVLHPSMask(SVOp) ||
4627                  X86::isMOVLPMask(SVOp)))
4628     return Op;
4629
4630   if (ShouldXformToMOVHLPS(SVOp) ||
4631       ShouldXformToMOVLP(V1.getNode(), V2.getNode(), SVOp))
4632     return CommuteVectorShuffle(SVOp, DAG);
4633
4634   if (isShift) {
4635     // No better options. Use a vshl / vsrl.
4636     EVT EltVT = VT.getVectorElementType();
4637     ShAmt *= EltVT.getSizeInBits();
4638     return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
4639   }
4640
4641   bool Commuted = false;
4642   // FIXME: This should also accept a bitcast of a splat?  Be careful, not
4643   // 1,1,1,1 -> v8i16 though.
4644   V1IsSplat = isSplatVector(V1.getNode());
4645   V2IsSplat = isSplatVector(V2.getNode());
4646
4647   // Canonicalize the splat or undef, if present, to be on the RHS.
4648   if ((V1IsSplat || V1IsUndef) && !(V2IsSplat || V2IsUndef)) {
4649     Op = CommuteVectorShuffle(SVOp, DAG);
4650     SVOp = cast<ShuffleVectorSDNode>(Op);
4651     V1 = SVOp->getOperand(0);
4652     V2 = SVOp->getOperand(1);
4653     std::swap(V1IsSplat, V2IsSplat);
4654     std::swap(V1IsUndef, V2IsUndef);
4655     Commuted = true;
4656   }
4657
4658   if (isCommutedMOVL(SVOp, V2IsSplat, V2IsUndef)) {
4659     // Shuffling low element of v1 into undef, just return v1.
4660     if (V2IsUndef)
4661       return V1;
4662     // If V2 is a splat, the mask may be malformed such as <4,3,3,3>, which
4663     // the instruction selector will not match, so get a canonical MOVL with
4664     // swapped operands to undo the commute.
4665     return getMOVL(DAG, dl, VT, V2, V1);
4666   }
4667
4668   if (X86::isUNPCKL_v_undef_Mask(SVOp) ||
4669       X86::isUNPCKH_v_undef_Mask(SVOp) ||
4670       X86::isUNPCKLMask(SVOp) ||
4671       X86::isUNPCKHMask(SVOp))
4672     return Op;
4673
4674   if (V2IsSplat) {
4675     // Normalize mask so all entries that point to V2 points to its first
4676     // element then try to match unpck{h|l} again. If match, return a
4677     // new vector_shuffle with the corrected mask.
4678     SDValue NewMask = NormalizeMask(SVOp, DAG);
4679     ShuffleVectorSDNode *NSVOp = cast<ShuffleVectorSDNode>(NewMask);
4680     if (NSVOp != SVOp) {
4681       if (X86::isUNPCKLMask(NSVOp, true)) {
4682         return NewMask;
4683       } else if (X86::isUNPCKHMask(NSVOp, true)) {
4684         return NewMask;
4685       }
4686     }
4687   }
4688
4689   if (Commuted) {
4690     // Commute is back and try unpck* again.
4691     // FIXME: this seems wrong.
4692     SDValue NewOp = CommuteVectorShuffle(SVOp, DAG);
4693     ShuffleVectorSDNode *NewSVOp = cast<ShuffleVectorSDNode>(NewOp);
4694     if (X86::isUNPCKL_v_undef_Mask(NewSVOp) ||
4695         X86::isUNPCKH_v_undef_Mask(NewSVOp) ||
4696         X86::isUNPCKLMask(NewSVOp) ||
4697         X86::isUNPCKHMask(NewSVOp))
4698       return NewOp;
4699   }
4700
4701   // FIXME: for mmx, bitcast v2i32 to v4i16 for shuffle.
4702
4703   // Normalize the node to match x86 shuffle ops if needed
4704   if (!isMMX && V2.getOpcode() != ISD::UNDEF && isCommutedSHUFP(SVOp))
4705     return CommuteVectorShuffle(SVOp, DAG);
4706
4707   // Check for legal shuffle and return?
4708   SmallVector<int, 16> PermMask;
4709   SVOp->getMask(PermMask);
4710   if (isShuffleMaskLegal(PermMask, VT))
4711     return Op;
4712
4713   // Handle v8i16 specifically since SSE can do byte extraction and insertion.
4714   if (VT == MVT::v8i16) {
4715     SDValue NewOp = LowerVECTOR_SHUFFLEv8i16(SVOp, DAG, *this);
4716     if (NewOp.getNode())
4717       return NewOp;
4718   }
4719
4720   if (VT == MVT::v16i8) {
4721     SDValue NewOp = LowerVECTOR_SHUFFLEv16i8(SVOp, DAG, *this);
4722     if (NewOp.getNode())
4723       return NewOp;
4724   }
4725
4726   // Handle all 4 wide cases with a number of shuffles except for MMX.
4727   if (NumElems == 4 && !isMMX)
4728     return LowerVECTOR_SHUFFLE_4wide(SVOp, DAG);
4729
4730   return SDValue();
4731 }
4732
4733 SDValue
4734 X86TargetLowering::LowerEXTRACT_VECTOR_ELT_SSE4(SDValue Op,
4735                                                 SelectionDAG &DAG) {
4736   EVT VT = Op.getValueType();
4737   DebugLoc dl = Op.getDebugLoc();
4738   if (VT.getSizeInBits() == 8) {
4739     SDValue Extract = DAG.getNode(X86ISD::PEXTRB, dl, MVT::i32,
4740                                     Op.getOperand(0), Op.getOperand(1));
4741     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
4742                                     DAG.getValueType(VT));
4743     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
4744   } else if (VT.getSizeInBits() == 16) {
4745     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
4746     // If Idx is 0, it's cheaper to do a move instead of a pextrw.
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,
4752                                                  Op.getOperand(0)),
4753                                      Op.getOperand(1)));
4754     SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, MVT::i32,
4755                                     Op.getOperand(0), Op.getOperand(1));
4756     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
4757                                     DAG.getValueType(VT));
4758     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
4759   } else if (VT == MVT::f32) {
4760     // EXTRACTPS outputs to a GPR32 register which will require a movd to copy
4761     // the result back to FR32 register. It's only worth matching if the
4762     // result has a single use which is a store or a bitcast to i32.  And in
4763     // the case of a store, it's not worth it if the index is a constant 0,
4764     // because a MOVSSmr can be used instead, which is smaller and faster.
4765     if (!Op.hasOneUse())
4766       return SDValue();
4767     SDNode *User = *Op.getNode()->use_begin();
4768     if ((User->getOpcode() != ISD::STORE ||
4769          (isa<ConstantSDNode>(Op.getOperand(1)) &&
4770           cast<ConstantSDNode>(Op.getOperand(1))->isNullValue())) &&
4771         (User->getOpcode() != ISD::BIT_CONVERT ||
4772          User->getValueType(0) != MVT::i32))
4773       return SDValue();
4774     SDValue Extract = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
4775                                   DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v4i32,
4776                                               Op.getOperand(0)),
4777                                               Op.getOperand(1));
4778     return DAG.getNode(ISD::BIT_CONVERT, dl, MVT::f32, Extract);
4779   } else if (VT == MVT::i32) {
4780     // ExtractPS works with constant index.
4781     if (isa<ConstantSDNode>(Op.getOperand(1)))
4782       return Op;
4783   }
4784   return SDValue();
4785 }
4786
4787
4788 SDValue
4789 X86TargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) {
4790   if (!isa<ConstantSDNode>(Op.getOperand(1)))
4791     return SDValue();
4792
4793   if (Subtarget->hasSSE41()) {
4794     SDValue Res = LowerEXTRACT_VECTOR_ELT_SSE4(Op, DAG);
4795     if (Res.getNode())
4796       return Res;
4797   }
4798
4799   EVT VT = Op.getValueType();
4800   DebugLoc dl = Op.getDebugLoc();
4801   // TODO: handle v16i8.
4802   if (VT.getSizeInBits() == 16) {
4803     SDValue Vec = Op.getOperand(0);
4804     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
4805     if (Idx == 0)
4806       return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
4807                          DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
4808                                      DAG.getNode(ISD::BIT_CONVERT, dl,
4809                                                  MVT::v4i32, Vec),
4810                                      Op.getOperand(1)));
4811     // Transform it so it match pextrw which produces a 32-bit result.
4812     EVT EltVT = MVT::i32;
4813     SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, EltVT,
4814                                     Op.getOperand(0), Op.getOperand(1));
4815     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, EltVT, Extract,
4816                                     DAG.getValueType(VT));
4817     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
4818   } else if (VT.getSizeInBits() == 32) {
4819     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
4820     if (Idx == 0)
4821       return Op;
4822
4823     // SHUFPS the element to the lowest double word, then movss.
4824     int Mask[4] = { Idx, -1, -1, -1 };
4825     EVT VVT = Op.getOperand(0).getValueType();
4826     SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
4827                                        DAG.getUNDEF(VVT), Mask);
4828     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
4829                        DAG.getIntPtrConstant(0));
4830   } else if (VT.getSizeInBits() == 64) {
4831     // FIXME: .td only matches this for <2 x f64>, not <2 x i64> on 32b
4832     // FIXME: seems like this should be unnecessary if mov{h,l}pd were taught
4833     //        to match extract_elt for f64.
4834     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
4835     if (Idx == 0)
4836       return Op;
4837
4838     // UNPCKHPD the element to the lowest double word, then movsd.
4839     // Note if the lower 64 bits of the result of the UNPCKHPD is then stored
4840     // to a f64mem, the whole operation is folded into a single MOVHPDmr.
4841     int Mask[2] = { 1, -1 };
4842     EVT VVT = Op.getOperand(0).getValueType();
4843     SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
4844                                        DAG.getUNDEF(VVT), Mask);
4845     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
4846                        DAG.getIntPtrConstant(0));
4847   }
4848
4849   return SDValue();
4850 }
4851
4852 SDValue
4853 X86TargetLowering::LowerINSERT_VECTOR_ELT_SSE4(SDValue Op, SelectionDAG &DAG){
4854   EVT VT = Op.getValueType();
4855   EVT EltVT = VT.getVectorElementType();
4856   DebugLoc dl = Op.getDebugLoc();
4857
4858   SDValue N0 = Op.getOperand(0);
4859   SDValue N1 = Op.getOperand(1);
4860   SDValue N2 = Op.getOperand(2);
4861
4862   if ((EltVT.getSizeInBits() == 8 || EltVT.getSizeInBits() == 16) &&
4863       isa<ConstantSDNode>(N2)) {
4864     unsigned Opc;
4865     if (VT == MVT::v8i16)
4866       Opc = X86ISD::PINSRW;
4867     else if (VT == MVT::v4i16)
4868       Opc = X86ISD::MMX_PINSRW;
4869     else if (VT == MVT::v16i8)
4870       Opc = X86ISD::PINSRB;
4871     else
4872       Opc = X86ISD::PINSRB;
4873
4874     // Transform it so it match pinsr{b,w} which expects a GR32 as its second
4875     // argument.
4876     if (N1.getValueType() != MVT::i32)
4877       N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
4878     if (N2.getValueType() != MVT::i32)
4879       N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue());
4880     return DAG.getNode(Opc, dl, VT, N0, N1, N2);
4881   } else if (EltVT == MVT::f32 && isa<ConstantSDNode>(N2)) {
4882     // Bits [7:6] of the constant are the source select.  This will always be
4883     //  zero here.  The DAG Combiner may combine an extract_elt index into these
4884     //  bits.  For example (insert (extract, 3), 2) could be matched by putting
4885     //  the '3' into bits [7:6] of X86ISD::INSERTPS.
4886     // Bits [5:4] of the constant are the destination select.  This is the
4887     //  value of the incoming immediate.
4888     // Bits [3:0] of the constant are the zero mask.  The DAG Combiner may
4889     //   combine either bitwise AND or insert of float 0.0 to set these bits.
4890     N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue() << 4);
4891     // Create this as a scalar to vector..
4892     N1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4f32, N1);
4893     return DAG.getNode(X86ISD::INSERTPS, dl, VT, N0, N1, N2);
4894   } else if (EltVT == MVT::i32 && isa<ConstantSDNode>(N2)) {
4895     // PINSR* works with constant index.
4896     return Op;
4897   }
4898   return SDValue();
4899 }
4900
4901 SDValue
4902 X86TargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) {
4903   EVT VT = Op.getValueType();
4904   EVT EltVT = VT.getVectorElementType();
4905
4906   if (Subtarget->hasSSE41())
4907     return LowerINSERT_VECTOR_ELT_SSE4(Op, DAG);
4908
4909   if (EltVT == MVT::i8)
4910     return SDValue();
4911
4912   DebugLoc dl = Op.getDebugLoc();
4913   SDValue N0 = Op.getOperand(0);
4914   SDValue N1 = Op.getOperand(1);
4915   SDValue N2 = Op.getOperand(2);
4916
4917   if (EltVT.getSizeInBits() == 16 && isa<ConstantSDNode>(N2)) {
4918     // Transform it so it match pinsrw which expects a 16-bit value in a GR32
4919     // as its second argument.
4920     if (N1.getValueType() != MVT::i32)
4921       N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
4922     if (N2.getValueType() != MVT::i32)
4923       N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue());
4924     return DAG.getNode(VT == MVT::v8i16 ? X86ISD::PINSRW : X86ISD::MMX_PINSRW,
4925                        dl, VT, N0, N1, N2);
4926   }
4927   return SDValue();
4928 }
4929
4930 SDValue
4931 X86TargetLowering::LowerSCALAR_TO_VECTOR(SDValue Op, SelectionDAG &DAG) {
4932   DebugLoc dl = Op.getDebugLoc();
4933   if (Op.getValueType() == MVT::v2f32)
4934     return DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v2f32,
4935                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i32,
4936                                    DAG.getNode(ISD::BIT_CONVERT, dl, MVT::i32,
4937                                                Op.getOperand(0))));
4938
4939   if (Op.getValueType() == MVT::v1i64 && Op.getOperand(0).getValueType() == MVT::i64)
4940     return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v1i64, Op.getOperand(0));
4941
4942   SDValue AnyExt = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, Op.getOperand(0));
4943   EVT VT = MVT::v2i32;
4944   switch (Op.getValueType().getSimpleVT().SimpleTy) {
4945   default: break;
4946   case MVT::v16i8:
4947   case MVT::v8i16:
4948     VT = MVT::v4i32;
4949     break;
4950   }
4951   return DAG.getNode(ISD::BIT_CONVERT, dl, Op.getValueType(),
4952                      DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, AnyExt));
4953 }
4954
4955 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
4956 // their target countpart wrapped in the X86ISD::Wrapper node. Suppose N is
4957 // one of the above mentioned nodes. It has to be wrapped because otherwise
4958 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
4959 // be used to form addressing mode. These wrapped nodes will be selected
4960 // into MOV32ri.
4961 SDValue
4962 X86TargetLowering::LowerConstantPool(SDValue Op, SelectionDAG &DAG) {
4963   ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
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.getTargetConstantPool(CP->getConstVal(), getPointerTy(),
4980                                              CP->getAlignment(),
4981                                              CP->getOffset(), OpFlag);
4982   DebugLoc DL = CP->getDebugLoc();
4983   Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
4984   // With PIC, the address is actually $g + Offset.
4985   if (OpFlag) {
4986     Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
4987                          DAG.getNode(X86ISD::GlobalBaseReg,
4988                                      DebugLoc::getUnknownLoc(), getPointerTy()),
4989                          Result);
4990   }
4991
4992   return Result;
4993 }
4994
4995 SDValue X86TargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) {
4996   JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
4997
4998   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
4999   // global base reg.
5000   unsigned char OpFlag = 0;
5001   unsigned WrapperKind = X86ISD::Wrapper;
5002   CodeModel::Model M = getTargetMachine().getCodeModel();
5003
5004   if (Subtarget->isPICStyleRIPRel() &&
5005       (M == CodeModel::Small || M == CodeModel::Kernel))
5006     WrapperKind = X86ISD::WrapperRIP;
5007   else if (Subtarget->isPICStyleGOT())
5008     OpFlag = X86II::MO_GOTOFF;
5009   else if (Subtarget->isPICStyleStubPIC())
5010     OpFlag = X86II::MO_PIC_BASE_OFFSET;
5011
5012   SDValue Result = DAG.getTargetJumpTable(JT->getIndex(), getPointerTy(),
5013                                           OpFlag);
5014   DebugLoc DL = JT->getDebugLoc();
5015   Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
5016
5017   // With PIC, the address is actually $g + Offset.
5018   if (OpFlag) {
5019     Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
5020                          DAG.getNode(X86ISD::GlobalBaseReg,
5021                                      DebugLoc::getUnknownLoc(), getPointerTy()),
5022                          Result);
5023   }
5024
5025   return Result;
5026 }
5027
5028 SDValue
5029 X86TargetLowering::LowerExternalSymbol(SDValue Op, SelectionDAG &DAG) {
5030   const char *Sym = cast<ExternalSymbolSDNode>(Op)->getSymbol();
5031
5032   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
5033   // global base reg.
5034   unsigned char OpFlag = 0;
5035   unsigned WrapperKind = X86ISD::Wrapper;
5036   CodeModel::Model M = getTargetMachine().getCodeModel();
5037
5038   if (Subtarget->isPICStyleRIPRel() &&
5039       (M == CodeModel::Small || M == CodeModel::Kernel))
5040     WrapperKind = X86ISD::WrapperRIP;
5041   else if (Subtarget->isPICStyleGOT())
5042     OpFlag = X86II::MO_GOTOFF;
5043   else if (Subtarget->isPICStyleStubPIC())
5044     OpFlag = X86II::MO_PIC_BASE_OFFSET;
5045
5046   SDValue Result = DAG.getTargetExternalSymbol(Sym, getPointerTy(), OpFlag);
5047
5048   DebugLoc DL = Op.getDebugLoc();
5049   Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
5050
5051
5052   // With PIC, the address is actually $g + Offset.
5053   if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
5054       !Subtarget->is64Bit()) {
5055     Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
5056                          DAG.getNode(X86ISD::GlobalBaseReg,
5057                                      DebugLoc::getUnknownLoc(),
5058                                      getPointerTy()),
5059                          Result);
5060   }
5061
5062   return Result;
5063 }
5064
5065 SDValue
5066 X86TargetLowering::LowerBlockAddress(SDValue Op, SelectionDAG &DAG) {
5067   // Create the TargetBlockAddressAddress node.
5068   unsigned char OpFlags =
5069     Subtarget->ClassifyBlockAddressReference();
5070   CodeModel::Model M = getTargetMachine().getCodeModel();
5071   BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
5072   DebugLoc dl = Op.getDebugLoc();
5073   SDValue Result = DAG.getBlockAddress(BA, getPointerTy(),
5074                                        /*isTarget=*/true, OpFlags);
5075
5076   if (Subtarget->isPICStyleRIPRel() &&
5077       (M == CodeModel::Small || M == CodeModel::Kernel))
5078     Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
5079   else
5080     Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
5081
5082   // With PIC, the address is actually $g + Offset.
5083   if (isGlobalRelativeToPICBase(OpFlags)) {
5084     Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
5085                          DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
5086                          Result);
5087   }
5088
5089   return Result;
5090 }
5091
5092 SDValue
5093 X86TargetLowering::LowerGlobalAddress(const GlobalValue *GV, DebugLoc dl,
5094                                       int64_t Offset,
5095                                       SelectionDAG &DAG) const {
5096   // Create the TargetGlobalAddress node, folding in the constant
5097   // offset if it is legal.
5098   unsigned char OpFlags =
5099     Subtarget->ClassifyGlobalReference(GV, getTargetMachine());
5100   CodeModel::Model M = getTargetMachine().getCodeModel();
5101   SDValue Result;
5102   if (OpFlags == X86II::MO_NO_FLAG &&
5103       X86::isOffsetSuitableForCodeModel(Offset, M)) {
5104     // A direct static reference to a global.
5105     Result = DAG.getTargetGlobalAddress(GV, getPointerTy(), Offset);
5106     Offset = 0;
5107   } else {
5108     Result = DAG.getTargetGlobalAddress(GV, getPointerTy(), 0, OpFlags);
5109   }
5110
5111   if (Subtarget->isPICStyleRIPRel() &&
5112       (M == CodeModel::Small || M == CodeModel::Kernel))
5113     Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
5114   else
5115     Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
5116
5117   // With PIC, the address is actually $g + Offset.
5118   if (isGlobalRelativeToPICBase(OpFlags)) {
5119     Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
5120                          DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
5121                          Result);
5122   }
5123
5124   // For globals that require a load from a stub to get the address, emit the
5125   // load.
5126   if (isGlobalStubReference(OpFlags))
5127     Result = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Result,
5128                          PseudoSourceValue::getGOT(), 0, false, false, 0);
5129
5130   // If there was a non-zero offset that we didn't fold, create an explicit
5131   // addition for it.
5132   if (Offset != 0)
5133     Result = DAG.getNode(ISD::ADD, dl, getPointerTy(), Result,
5134                          DAG.getConstant(Offset, getPointerTy()));
5135
5136   return Result;
5137 }
5138
5139 SDValue
5140 X86TargetLowering::LowerGlobalAddress(SDValue Op, SelectionDAG &DAG) {
5141   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
5142   int64_t Offset = cast<GlobalAddressSDNode>(Op)->getOffset();
5143   return LowerGlobalAddress(GV, Op.getDebugLoc(), Offset, DAG);
5144 }
5145
5146 static SDValue
5147 GetTLSADDR(SelectionDAG &DAG, SDValue Chain, GlobalAddressSDNode *GA,
5148            SDValue *InFlag, const EVT PtrVT, unsigned ReturnReg,
5149            unsigned char OperandFlags) {
5150   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
5151   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Flag);
5152   DebugLoc dl = GA->getDebugLoc();
5153   SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(),
5154                                            GA->getValueType(0),
5155                                            GA->getOffset(),
5156                                            OperandFlags);
5157   if (InFlag) {
5158     SDValue Ops[] = { Chain,  TGA, *InFlag };
5159     Chain = DAG.getNode(X86ISD::TLSADDR, dl, NodeTys, Ops, 3);
5160   } else {
5161     SDValue Ops[]  = { Chain, TGA };
5162     Chain = DAG.getNode(X86ISD::TLSADDR, dl, NodeTys, Ops, 2);
5163   }
5164
5165   // TLSADDR will be codegen'ed as call. Inform MFI that function has calls.
5166   MFI->setHasCalls(true);
5167
5168   SDValue Flag = Chain.getValue(1);
5169   return DAG.getCopyFromReg(Chain, dl, ReturnReg, PtrVT, Flag);
5170 }
5171
5172 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 32 bit
5173 static SDValue
5174 LowerToTLSGeneralDynamicModel32(GlobalAddressSDNode *GA, SelectionDAG &DAG,
5175                                 const EVT PtrVT) {
5176   SDValue InFlag;
5177   DebugLoc dl = GA->getDebugLoc();  // ? function entry point might be better
5178   SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
5179                                      DAG.getNode(X86ISD::GlobalBaseReg,
5180                                                  DebugLoc::getUnknownLoc(),
5181                                                  PtrVT), InFlag);
5182   InFlag = Chain.getValue(1);
5183
5184   return GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX, X86II::MO_TLSGD);
5185 }
5186
5187 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 64 bit
5188 static SDValue
5189 LowerToTLSGeneralDynamicModel64(GlobalAddressSDNode *GA, SelectionDAG &DAG,
5190                                 const EVT PtrVT) {
5191   return GetTLSADDR(DAG, DAG.getEntryNode(), GA, NULL, PtrVT,
5192                     X86::RAX, X86II::MO_TLSGD);
5193 }
5194
5195 // Lower ISD::GlobalTLSAddress using the "initial exec" (for no-pic) or
5196 // "local exec" model.
5197 static SDValue LowerToTLSExecModel(GlobalAddressSDNode *GA, SelectionDAG &DAG,
5198                                    const EVT PtrVT, TLSModel::Model model,
5199                                    bool is64Bit) {
5200   DebugLoc dl = GA->getDebugLoc();
5201   // Get the Thread Pointer
5202   SDValue Base = DAG.getNode(X86ISD::SegmentBaseAddress,
5203                              DebugLoc::getUnknownLoc(), PtrVT,
5204                              DAG.getRegister(is64Bit? X86::FS : X86::GS,
5205                                              MVT::i32));
5206
5207   SDValue ThreadPointer = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Base,
5208                                       NULL, 0, false, false, 0);
5209
5210   unsigned char OperandFlags = 0;
5211   // Most TLS accesses are not RIP relative, even on x86-64.  One exception is
5212   // initialexec.
5213   unsigned WrapperKind = X86ISD::Wrapper;
5214   if (model == TLSModel::LocalExec) {
5215     OperandFlags = is64Bit ? X86II::MO_TPOFF : X86II::MO_NTPOFF;
5216   } else if (is64Bit) {
5217     assert(model == TLSModel::InitialExec);
5218     OperandFlags = X86II::MO_GOTTPOFF;
5219     WrapperKind = X86ISD::WrapperRIP;
5220   } else {
5221     assert(model == TLSModel::InitialExec);
5222     OperandFlags = X86II::MO_INDNTPOFF;
5223   }
5224
5225   // emit "addl x@ntpoff,%eax" (local exec) or "addl x@indntpoff,%eax" (initial
5226   // exec)
5227   SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), GA->getValueType(0),
5228                                            GA->getOffset(), OperandFlags);
5229   SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
5230
5231   if (model == TLSModel::InitialExec)
5232     Offset = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Offset,
5233                          PseudoSourceValue::getGOT(), 0, false, false, 0);
5234
5235   // The address of the thread local variable is the add of the thread
5236   // pointer with the offset of the variable.
5237   return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
5238 }
5239
5240 SDValue
5241 X86TargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) {
5242   // TODO: implement the "local dynamic" model
5243   // TODO: implement the "initial exec"model for pic executables
5244   assert(Subtarget->isTargetELF() &&
5245          "TLS not implemented for non-ELF targets");
5246   GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
5247   const GlobalValue *GV = GA->getGlobal();
5248
5249   // If GV is an alias then use the aliasee for determining
5250   // thread-localness.
5251   if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(GV))
5252     GV = GA->resolveAliasedGlobal(false);
5253
5254   TLSModel::Model model = getTLSModel(GV,
5255                                       getTargetMachine().getRelocationModel());
5256
5257   switch (model) {
5258   case TLSModel::GeneralDynamic:
5259   case TLSModel::LocalDynamic: // not implemented
5260     if (Subtarget->is64Bit())
5261       return LowerToTLSGeneralDynamicModel64(GA, DAG, getPointerTy());
5262     return LowerToTLSGeneralDynamicModel32(GA, DAG, getPointerTy());
5263
5264   case TLSModel::InitialExec:
5265   case TLSModel::LocalExec:
5266     return LowerToTLSExecModel(GA, DAG, getPointerTy(), model,
5267                                Subtarget->is64Bit());
5268   }
5269
5270   llvm_unreachable("Unreachable");
5271   return SDValue();
5272 }
5273
5274
5275 /// LowerShift - Lower SRA_PARTS and friends, which return two i32 values and
5276 /// take a 2 x i32 value to shift plus a shift amount.
5277 SDValue X86TargetLowering::LowerShift(SDValue Op, SelectionDAG &DAG) {
5278   assert(Op.getNumOperands() == 3 && "Not a double-shift!");
5279   EVT VT = Op.getValueType();
5280   unsigned VTBits = VT.getSizeInBits();
5281   DebugLoc dl = Op.getDebugLoc();
5282   bool isSRA = Op.getOpcode() == ISD::SRA_PARTS;
5283   SDValue ShOpLo = Op.getOperand(0);
5284   SDValue ShOpHi = Op.getOperand(1);
5285   SDValue ShAmt  = Op.getOperand(2);
5286   SDValue Tmp1 = isSRA ? DAG.getNode(ISD::SRA, dl, VT, ShOpHi,
5287                                      DAG.getConstant(VTBits - 1, MVT::i8))
5288                        : DAG.getConstant(0, VT);
5289
5290   SDValue Tmp2, Tmp3;
5291   if (Op.getOpcode() == ISD::SHL_PARTS) {
5292     Tmp2 = DAG.getNode(X86ISD::SHLD, dl, VT, ShOpHi, ShOpLo, ShAmt);
5293     Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ShAmt);
5294   } else {
5295     Tmp2 = DAG.getNode(X86ISD::SHRD, dl, VT, ShOpLo, ShOpHi, ShAmt);
5296     Tmp3 = DAG.getNode(isSRA ? ISD::SRA : ISD::SRL, dl, VT, ShOpHi, ShAmt);
5297   }
5298
5299   SDValue AndNode = DAG.getNode(ISD::AND, dl, MVT::i8, ShAmt,
5300                                 DAG.getConstant(VTBits, MVT::i8));
5301   SDValue Cond = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
5302                              AndNode, DAG.getConstant(0, MVT::i8));
5303
5304   SDValue Hi, Lo;
5305   SDValue CC = DAG.getConstant(X86::COND_NE, MVT::i8);
5306   SDValue Ops0[4] = { Tmp2, Tmp3, CC, Cond };
5307   SDValue Ops1[4] = { Tmp3, Tmp1, CC, Cond };
5308
5309   if (Op.getOpcode() == ISD::SHL_PARTS) {
5310     Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0, 4);
5311     Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1, 4);
5312   } else {
5313     Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0, 4);
5314     Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1, 4);
5315   }
5316
5317   SDValue Ops[2] = { Lo, Hi };
5318   return DAG.getMergeValues(Ops, 2, dl);
5319 }
5320
5321 SDValue X86TargetLowering::LowerSINT_TO_FP(SDValue Op, SelectionDAG &DAG) {
5322   EVT SrcVT = Op.getOperand(0).getValueType();
5323
5324   if (SrcVT.isVector()) {
5325     if (SrcVT == MVT::v2i32 && Op.getValueType() == MVT::v2f64) {
5326       return Op;
5327     }
5328     return SDValue();
5329   }
5330
5331   assert(SrcVT.getSimpleVT() <= MVT::i64 && SrcVT.getSimpleVT() >= MVT::i16 &&
5332          "Unknown SINT_TO_FP to lower!");
5333
5334   // These are really Legal; return the operand so the caller accepts it as
5335   // Legal.
5336   if (SrcVT == MVT::i32 && isScalarFPTypeInSSEReg(Op.getValueType()))
5337     return Op;
5338   if (SrcVT == MVT::i64 && isScalarFPTypeInSSEReg(Op.getValueType()) &&
5339       Subtarget->is64Bit()) {
5340     return Op;
5341   }
5342
5343   DebugLoc dl = Op.getDebugLoc();
5344   unsigned Size = SrcVT.getSizeInBits()/8;
5345   MachineFunction &MF = DAG.getMachineFunction();
5346   int SSFI = MF.getFrameInfo()->CreateStackObject(Size, Size, false);
5347   SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
5348   SDValue Chain = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
5349                                StackSlot,
5350                                PseudoSourceValue::getFixedStack(SSFI), 0,
5351                                false, false, 0);
5352   return BuildFILD(Op, SrcVT, Chain, StackSlot, DAG);
5353 }
5354
5355 SDValue X86TargetLowering::BuildFILD(SDValue Op, EVT SrcVT, SDValue Chain,
5356                                      SDValue StackSlot,
5357                                      SelectionDAG &DAG) {
5358   // Build the FILD
5359   DebugLoc dl = Op.getDebugLoc();
5360   SDVTList Tys;
5361   bool useSSE = isScalarFPTypeInSSEReg(Op.getValueType());
5362   if (useSSE)
5363     Tys = DAG.getVTList(MVT::f64, MVT::Other, MVT::Flag);
5364   else
5365     Tys = DAG.getVTList(Op.getValueType(), MVT::Other);
5366   SDValue Ops[] = { Chain, StackSlot, DAG.getValueType(SrcVT) };
5367   SDValue Result = DAG.getNode(useSSE ? X86ISD::FILD_FLAG : X86ISD::FILD, dl,
5368                                Tys, Ops, array_lengthof(Ops));
5369
5370   if (useSSE) {
5371     Chain = Result.getValue(1);
5372     SDValue InFlag = Result.getValue(2);
5373
5374     // FIXME: Currently the FST is flagged to the FILD_FLAG. This
5375     // shouldn't be necessary except that RFP cannot be live across
5376     // multiple blocks. When stackifier is fixed, they can be uncoupled.
5377     MachineFunction &MF = DAG.getMachineFunction();
5378     int SSFI = MF.getFrameInfo()->CreateStackObject(8, 8, false);
5379     SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
5380     Tys = DAG.getVTList(MVT::Other);
5381     SDValue Ops[] = {
5382       Chain, Result, StackSlot, DAG.getValueType(Op.getValueType()), InFlag
5383     };
5384     Chain = DAG.getNode(X86ISD::FST, dl, Tys, Ops, array_lengthof(Ops));
5385     Result = DAG.getLoad(Op.getValueType(), dl, Chain, StackSlot,
5386                          PseudoSourceValue::getFixedStack(SSFI), 0,
5387                          false, false, 0);
5388   }
5389
5390   return Result;
5391 }
5392
5393 // LowerUINT_TO_FP_i64 - 64-bit unsigned integer to double expansion.
5394 SDValue X86TargetLowering::LowerUINT_TO_FP_i64(SDValue Op, SelectionDAG &DAG) {
5395   // This algorithm is not obvious. Here it is in C code, more or less:
5396   /*
5397     double uint64_to_double( uint32_t hi, uint32_t lo ) {
5398       static const __m128i exp = { 0x4330000045300000ULL, 0 };
5399       static const __m128d bias = { 0x1.0p84, 0x1.0p52 };
5400
5401       // Copy ints to xmm registers.
5402       __m128i xh = _mm_cvtsi32_si128( hi );
5403       __m128i xl = _mm_cvtsi32_si128( lo );
5404
5405       // Combine into low half of a single xmm register.
5406       __m128i x = _mm_unpacklo_epi32( xh, xl );
5407       __m128d d;
5408       double sd;
5409
5410       // Merge in appropriate exponents to give the integer bits the right
5411       // magnitude.
5412       x = _mm_unpacklo_epi32( x, exp );
5413
5414       // Subtract away the biases to deal with the IEEE-754 double precision
5415       // implicit 1.
5416       d = _mm_sub_pd( (__m128d) x, bias );
5417
5418       // All conversions up to here are exact. The correctly rounded result is
5419       // calculated using the current rounding mode using the following
5420       // horizontal add.
5421       d = _mm_add_sd( d, _mm_unpackhi_pd( d, d ) );
5422       _mm_store_sd( &sd, d );   // Because we are returning doubles in XMM, this
5423                                 // store doesn't really need to be here (except
5424                                 // maybe to zero the other double)
5425       return sd;
5426     }
5427   */
5428
5429   DebugLoc dl = Op.getDebugLoc();
5430   LLVMContext *Context = DAG.getContext();
5431
5432   // Build some magic constants.
5433   std::vector<Constant*> CV0;
5434   CV0.push_back(ConstantInt::get(*Context, APInt(32, 0x45300000)));
5435   CV0.push_back(ConstantInt::get(*Context, APInt(32, 0x43300000)));
5436   CV0.push_back(ConstantInt::get(*Context, APInt(32, 0)));
5437   CV0.push_back(ConstantInt::get(*Context, APInt(32, 0)));
5438   Constant *C0 = ConstantVector::get(CV0);
5439   SDValue CPIdx0 = DAG.getConstantPool(C0, getPointerTy(), 16);
5440
5441   std::vector<Constant*> CV1;
5442   CV1.push_back(
5443     ConstantFP::get(*Context, APFloat(APInt(64, 0x4530000000000000ULL))));
5444   CV1.push_back(
5445     ConstantFP::get(*Context, APFloat(APInt(64, 0x4330000000000000ULL))));
5446   Constant *C1 = ConstantVector::get(CV1);
5447   SDValue CPIdx1 = DAG.getConstantPool(C1, getPointerTy(), 16);
5448
5449   SDValue XR1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
5450                             DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
5451                                         Op.getOperand(0),
5452                                         DAG.getIntPtrConstant(1)));
5453   SDValue XR2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
5454                             DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
5455                                         Op.getOperand(0),
5456                                         DAG.getIntPtrConstant(0)));
5457   SDValue Unpck1 = getUnpackl(DAG, dl, MVT::v4i32, XR1, XR2);
5458   SDValue CLod0 = DAG.getLoad(MVT::v4i32, dl, DAG.getEntryNode(), CPIdx0,
5459                               PseudoSourceValue::getConstantPool(), 0,
5460                               false, false, 16);
5461   SDValue Unpck2 = getUnpackl(DAG, dl, MVT::v4i32, Unpck1, CLod0);
5462   SDValue XR2F = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v2f64, Unpck2);
5463   SDValue CLod1 = DAG.getLoad(MVT::v2f64, dl, CLod0.getValue(1), CPIdx1,
5464                               PseudoSourceValue::getConstantPool(), 0,
5465                               false, false, 16);
5466   SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, XR2F, CLod1);
5467
5468   // Add the halves; easiest way is to swap them into another reg first.
5469   int ShufMask[2] = { 1, -1 };
5470   SDValue Shuf = DAG.getVectorShuffle(MVT::v2f64, dl, Sub,
5471                                       DAG.getUNDEF(MVT::v2f64), ShufMask);
5472   SDValue Add = DAG.getNode(ISD::FADD, dl, MVT::v2f64, Shuf, Sub);
5473   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Add,
5474                      DAG.getIntPtrConstant(0));
5475 }
5476
5477 // LowerUINT_TO_FP_i32 - 32-bit unsigned integer to float expansion.
5478 SDValue X86TargetLowering::LowerUINT_TO_FP_i32(SDValue Op, SelectionDAG &DAG) {
5479   DebugLoc dl = Op.getDebugLoc();
5480   // FP constant to bias correct the final result.
5481   SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL),
5482                                    MVT::f64);
5483
5484   // Load the 32-bit value into an XMM register.
5485   SDValue Load = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
5486                              DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
5487                                          Op.getOperand(0),
5488                                          DAG.getIntPtrConstant(0)));
5489
5490   Load = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
5491                      DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v2f64, Load),
5492                      DAG.getIntPtrConstant(0));
5493
5494   // Or the load with the bias.
5495   SDValue Or = DAG.getNode(ISD::OR, dl, MVT::v2i64,
5496                            DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v2i64,
5497                                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
5498                                                    MVT::v2f64, Load)),
5499                            DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v2i64,
5500                                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
5501                                                    MVT::v2f64, Bias)));
5502   Or = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
5503                    DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v2f64, Or),
5504                    DAG.getIntPtrConstant(0));
5505
5506   // Subtract the bias.
5507   SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::f64, Or, Bias);
5508
5509   // Handle final rounding.
5510   EVT DestVT = Op.getValueType();
5511
5512   if (DestVT.bitsLT(MVT::f64)) {
5513     return DAG.getNode(ISD::FP_ROUND, dl, DestVT, Sub,
5514                        DAG.getIntPtrConstant(0));
5515   } else if (DestVT.bitsGT(MVT::f64)) {
5516     return DAG.getNode(ISD::FP_EXTEND, dl, DestVT, Sub);
5517   }
5518
5519   // Handle final rounding.
5520   return Sub;
5521 }
5522
5523 SDValue X86TargetLowering::LowerUINT_TO_FP(SDValue Op, SelectionDAG &DAG) {
5524   SDValue N0 = Op.getOperand(0);
5525   DebugLoc dl = Op.getDebugLoc();
5526
5527   // Now not UINT_TO_FP is legal (it's marked custom), dag combiner won't
5528   // optimize it to a SINT_TO_FP when the sign bit is known zero. Perform
5529   // the optimization here.
5530   if (DAG.SignBitIsZero(N0))
5531     return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(), N0);
5532
5533   EVT SrcVT = N0.getValueType();
5534   if (SrcVT == MVT::i64) {
5535     // We only handle SSE2 f64 target here; caller can expand the rest.
5536     if (Op.getValueType() != MVT::f64 || !X86ScalarSSEf64)
5537       return SDValue();
5538
5539     return LowerUINT_TO_FP_i64(Op, DAG);
5540   } else if (SrcVT == MVT::i32 && X86ScalarSSEf64) {
5541     return LowerUINT_TO_FP_i32(Op, DAG);
5542   }
5543
5544   assert(SrcVT == MVT::i32 && "Unknown UINT_TO_FP to lower!");
5545
5546   // Make a 64-bit buffer, and use it to build an FILD.
5547   SDValue StackSlot = DAG.CreateStackTemporary(MVT::i64);
5548   SDValue WordOff = DAG.getConstant(4, getPointerTy());
5549   SDValue OffsetSlot = DAG.getNode(ISD::ADD, dl,
5550                                    getPointerTy(), StackSlot, WordOff);
5551   SDValue Store1 = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
5552                                 StackSlot, NULL, 0, false, false, 0);
5553   SDValue Store2 = DAG.getStore(Store1, dl, DAG.getConstant(0, MVT::i32),
5554                                 OffsetSlot, NULL, 0, false, false, 0);
5555   return BuildFILD(Op, MVT::i64, Store2, StackSlot, DAG);
5556 }
5557
5558 std::pair<SDValue,SDValue> X86TargetLowering::
5559 FP_TO_INTHelper(SDValue Op, SelectionDAG &DAG, bool IsSigned) {
5560   DebugLoc dl = Op.getDebugLoc();
5561
5562   EVT DstTy = Op.getValueType();
5563
5564   if (!IsSigned) {
5565     assert(DstTy == MVT::i32 && "Unexpected FP_TO_UINT");
5566     DstTy = MVT::i64;
5567   }
5568
5569   assert(DstTy.getSimpleVT() <= MVT::i64 &&
5570          DstTy.getSimpleVT() >= MVT::i16 &&
5571          "Unknown FP_TO_SINT to lower!");
5572
5573   // These are really Legal.
5574   if (DstTy == MVT::i32 &&
5575       isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
5576     return std::make_pair(SDValue(), SDValue());
5577   if (Subtarget->is64Bit() &&
5578       DstTy == MVT::i64 &&
5579       isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
5580     return std::make_pair(SDValue(), SDValue());
5581
5582   // We lower FP->sint64 into FISTP64, followed by a load, all to a temporary
5583   // stack slot.
5584   MachineFunction &MF = DAG.getMachineFunction();
5585   unsigned MemSize = DstTy.getSizeInBits()/8;
5586   int SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
5587   SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
5588
5589   unsigned Opc;
5590   switch (DstTy.getSimpleVT().SimpleTy) {
5591   default: llvm_unreachable("Invalid FP_TO_SINT to lower!");
5592   case MVT::i16: Opc = X86ISD::FP_TO_INT16_IN_MEM; break;
5593   case MVT::i32: Opc = X86ISD::FP_TO_INT32_IN_MEM; break;
5594   case MVT::i64: Opc = X86ISD::FP_TO_INT64_IN_MEM; break;
5595   }
5596
5597   SDValue Chain = DAG.getEntryNode();
5598   SDValue Value = Op.getOperand(0);
5599   if (isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType())) {
5600     assert(DstTy == MVT::i64 && "Invalid FP_TO_SINT to lower!");
5601     Chain = DAG.getStore(Chain, dl, Value, StackSlot,
5602                          PseudoSourceValue::getFixedStack(SSFI), 0,
5603                          false, false, 0);
5604     SDVTList Tys = DAG.getVTList(Op.getOperand(0).getValueType(), MVT::Other);
5605     SDValue Ops[] = {
5606       Chain, StackSlot, DAG.getValueType(Op.getOperand(0).getValueType())
5607     };
5608     Value = DAG.getNode(X86ISD::FLD, dl, Tys, Ops, 3);
5609     Chain = Value.getValue(1);
5610     SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
5611     StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
5612   }
5613
5614   // Build the FP_TO_INT*_IN_MEM
5615   SDValue Ops[] = { Chain, Value, StackSlot };
5616   SDValue FIST = DAG.getNode(Opc, dl, MVT::Other, Ops, 3);
5617
5618   return std::make_pair(FIST, StackSlot);
5619 }
5620
5621 SDValue X86TargetLowering::LowerFP_TO_SINT(SDValue Op, SelectionDAG &DAG) {
5622   if (Op.getValueType().isVector()) {
5623     if (Op.getValueType() == MVT::v2i32 &&
5624         Op.getOperand(0).getValueType() == MVT::v2f64) {
5625       return Op;
5626     }
5627     return SDValue();
5628   }
5629
5630   std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG, true);
5631   SDValue FIST = Vals.first, StackSlot = Vals.second;
5632   // If FP_TO_INTHelper failed, the node is actually supposed to be Legal.
5633   if (FIST.getNode() == 0) return Op;
5634
5635   // Load the result.
5636   return DAG.getLoad(Op.getValueType(), Op.getDebugLoc(),
5637                      FIST, StackSlot, NULL, 0, false, false, 0);
5638 }
5639
5640 SDValue X86TargetLowering::LowerFP_TO_UINT(SDValue Op, SelectionDAG &DAG) {
5641   std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG, false);
5642   SDValue FIST = Vals.first, StackSlot = Vals.second;
5643   assert(FIST.getNode() && "Unexpected failure");
5644
5645   // Load the result.
5646   return DAG.getLoad(Op.getValueType(), Op.getDebugLoc(),
5647                      FIST, StackSlot, NULL, 0, false, false, 0);
5648 }
5649
5650 SDValue X86TargetLowering::LowerFABS(SDValue Op, SelectionDAG &DAG) {
5651   LLVMContext *Context = DAG.getContext();
5652   DebugLoc dl = Op.getDebugLoc();
5653   EVT VT = Op.getValueType();
5654   EVT EltVT = VT;
5655   if (VT.isVector())
5656     EltVT = VT.getVectorElementType();
5657   std::vector<Constant*> CV;
5658   if (EltVT == MVT::f64) {
5659     Constant *C = ConstantFP::get(*Context, APFloat(APInt(64, ~(1ULL << 63))));
5660     CV.push_back(C);
5661     CV.push_back(C);
5662   } else {
5663     Constant *C = ConstantFP::get(*Context, APFloat(APInt(32, ~(1U << 31))));
5664     CV.push_back(C);
5665     CV.push_back(C);
5666     CV.push_back(C);
5667     CV.push_back(C);
5668   }
5669   Constant *C = ConstantVector::get(CV);
5670   SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
5671   SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
5672                              PseudoSourceValue::getConstantPool(), 0,
5673                              false, false, 16);
5674   return DAG.getNode(X86ISD::FAND, dl, VT, Op.getOperand(0), Mask);
5675 }
5676
5677 SDValue X86TargetLowering::LowerFNEG(SDValue Op, SelectionDAG &DAG) {
5678   LLVMContext *Context = DAG.getContext();
5679   DebugLoc dl = Op.getDebugLoc();
5680   EVT VT = Op.getValueType();
5681   EVT EltVT = VT;
5682   if (VT.isVector())
5683     EltVT = VT.getVectorElementType();
5684   std::vector<Constant*> CV;
5685   if (EltVT == MVT::f64) {
5686     Constant *C = ConstantFP::get(*Context, APFloat(APInt(64, 1ULL << 63)));
5687     CV.push_back(C);
5688     CV.push_back(C);
5689   } else {
5690     Constant *C = ConstantFP::get(*Context, APFloat(APInt(32, 1U << 31)));
5691     CV.push_back(C);
5692     CV.push_back(C);
5693     CV.push_back(C);
5694     CV.push_back(C);
5695   }
5696   Constant *C = ConstantVector::get(CV);
5697   SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
5698   SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
5699                              PseudoSourceValue::getConstantPool(), 0,
5700                              false, false, 16);
5701   if (VT.isVector()) {
5702     return DAG.getNode(ISD::BIT_CONVERT, dl, VT,
5703                        DAG.getNode(ISD::XOR, dl, MVT::v2i64,
5704                     DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v2i64,
5705                                 Op.getOperand(0)),
5706                     DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v2i64, Mask)));
5707   } else {
5708     return DAG.getNode(X86ISD::FXOR, dl, VT, Op.getOperand(0), Mask);
5709   }
5710 }
5711
5712 SDValue X86TargetLowering::LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) {
5713   LLVMContext *Context = DAG.getContext();
5714   SDValue Op0 = Op.getOperand(0);
5715   SDValue Op1 = Op.getOperand(1);
5716   DebugLoc dl = Op.getDebugLoc();
5717   EVT VT = Op.getValueType();
5718   EVT SrcVT = Op1.getValueType();
5719
5720   // If second operand is smaller, extend it first.
5721   if (SrcVT.bitsLT(VT)) {
5722     Op1 = DAG.getNode(ISD::FP_EXTEND, dl, VT, Op1);
5723     SrcVT = VT;
5724   }
5725   // And if it is bigger, shrink it first.
5726   if (SrcVT.bitsGT(VT)) {
5727     Op1 = DAG.getNode(ISD::FP_ROUND, dl, VT, Op1, DAG.getIntPtrConstant(1));
5728     SrcVT = VT;
5729   }
5730
5731   // At this point the operands and the result should have the same
5732   // type, and that won't be f80 since that is not custom lowered.
5733
5734   // First get the sign bit of second operand.
5735   std::vector<Constant*> CV;
5736   if (SrcVT == MVT::f64) {
5737     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, 1ULL << 63))));
5738     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, 0))));
5739   } else {
5740     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 1U << 31))));
5741     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
5742     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
5743     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
5744   }
5745   Constant *C = ConstantVector::get(CV);
5746   SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
5747   SDValue Mask1 = DAG.getLoad(SrcVT, dl, DAG.getEntryNode(), CPIdx,
5748                               PseudoSourceValue::getConstantPool(), 0,
5749                               false, false, 16);
5750   SDValue SignBit = DAG.getNode(X86ISD::FAND, dl, SrcVT, Op1, Mask1);
5751
5752   // Shift sign bit right or left if the two operands have different types.
5753   if (SrcVT.bitsGT(VT)) {
5754     // Op0 is MVT::f32, Op1 is MVT::f64.
5755     SignBit = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f64, SignBit);
5756     SignBit = DAG.getNode(X86ISD::FSRL, dl, MVT::v2f64, SignBit,
5757                           DAG.getConstant(32, MVT::i32));
5758     SignBit = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v4f32, SignBit);
5759     SignBit = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f32, SignBit,
5760                           DAG.getIntPtrConstant(0));
5761   }
5762
5763   // Clear first operand sign bit.
5764   CV.clear();
5765   if (VT == MVT::f64) {
5766     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, ~(1ULL << 63)))));
5767     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, 0))));
5768   } else {
5769     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, ~(1U << 31)))));
5770     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
5771     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
5772     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
5773   }
5774   C = ConstantVector::get(CV);
5775   CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
5776   SDValue Mask2 = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
5777                               PseudoSourceValue::getConstantPool(), 0,
5778                               false, false, 16);
5779   SDValue Val = DAG.getNode(X86ISD::FAND, dl, VT, Op0, Mask2);
5780
5781   // Or the value with the sign bit.
5782   return DAG.getNode(X86ISD::FOR, dl, VT, Val, SignBit);
5783 }
5784
5785 /// Emit nodes that will be selected as "test Op0,Op0", or something
5786 /// equivalent.
5787 SDValue X86TargetLowering::EmitTest(SDValue Op, unsigned X86CC,
5788                                     SelectionDAG &DAG) {
5789   DebugLoc dl = Op.getDebugLoc();
5790
5791   // CF and OF aren't always set the way we want. Determine which
5792   // of these we need.
5793   bool NeedCF = false;
5794   bool NeedOF = false;
5795   switch (X86CC) {
5796   case X86::COND_A: case X86::COND_AE:
5797   case X86::COND_B: case X86::COND_BE:
5798     NeedCF = true;
5799     break;
5800   case X86::COND_G: case X86::COND_GE:
5801   case X86::COND_L: case X86::COND_LE:
5802   case X86::COND_O: case X86::COND_NO:
5803     NeedOF = true;
5804     break;
5805   default: break;
5806   }
5807
5808   // See if we can use the EFLAGS value from the operand instead of
5809   // doing a separate TEST. TEST always sets OF and CF to 0, so unless
5810   // we prove that the arithmetic won't overflow, we can't use OF or CF.
5811   if (Op.getResNo() == 0 && !NeedOF && !NeedCF) {
5812     unsigned Opcode = 0;
5813     unsigned NumOperands = 0;
5814     switch (Op.getNode()->getOpcode()) {
5815     case ISD::ADD:
5816       // Due to an isel shortcoming, be conservative if this add is likely to
5817       // be selected as part of a load-modify-store instruction. When the root
5818       // node in a match is a store, isel doesn't know how to remap non-chain
5819       // non-flag uses of other nodes in the match, such as the ADD in this
5820       // case. This leads to the ADD being left around and reselected, with
5821       // the result being two adds in the output.
5822       for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
5823            UE = Op.getNode()->use_end(); UI != UE; ++UI)
5824         if (UI->getOpcode() == ISD::STORE)
5825           goto default_case;
5826       if (ConstantSDNode *C =
5827             dyn_cast<ConstantSDNode>(Op.getNode()->getOperand(1))) {
5828         // An add of one will be selected as an INC.
5829         if (C->getAPIntValue() == 1) {
5830           Opcode = X86ISD::INC;
5831           NumOperands = 1;
5832           break;
5833         }
5834         // An add of negative one (subtract of one) will be selected as a DEC.
5835         if (C->getAPIntValue().isAllOnesValue()) {
5836           Opcode = X86ISD::DEC;
5837           NumOperands = 1;
5838           break;
5839         }
5840       }
5841       // Otherwise use a regular EFLAGS-setting add.
5842       Opcode = X86ISD::ADD;
5843       NumOperands = 2;
5844       break;
5845     case ISD::AND: {
5846       // If the primary and result isn't used, don't bother using X86ISD::AND,
5847       // because a TEST instruction will be better.
5848       bool NonFlagUse = false;
5849       for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
5850              UE = Op.getNode()->use_end(); UI != UE; ++UI) {
5851         SDNode *User = *UI;
5852         unsigned UOpNo = UI.getOperandNo();
5853         if (User->getOpcode() == ISD::TRUNCATE && User->hasOneUse()) {
5854           // Look pass truncate.
5855           UOpNo = User->use_begin().getOperandNo();
5856           User = *User->use_begin();
5857         }
5858         if (User->getOpcode() != ISD::BRCOND &&
5859             User->getOpcode() != ISD::SETCC &&
5860             (User->getOpcode() != ISD::SELECT || UOpNo != 0)) {
5861           NonFlagUse = true;
5862           break;
5863         }
5864       }
5865       if (!NonFlagUse)
5866         break;
5867     }
5868     // FALL THROUGH
5869     case ISD::SUB:
5870     case ISD::OR:
5871     case ISD::XOR:
5872       // Due to the ISEL shortcoming noted above, be conservative if this op is
5873       // likely to be selected as part of a load-modify-store instruction.
5874       for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
5875            UE = Op.getNode()->use_end(); UI != UE; ++UI)
5876         if (UI->getOpcode() == ISD::STORE)
5877           goto default_case;
5878       // Otherwise use a regular EFLAGS-setting instruction.
5879       switch (Op.getNode()->getOpcode()) {
5880       case ISD::SUB: Opcode = X86ISD::SUB; break;
5881       case ISD::OR:  Opcode = X86ISD::OR;  break;
5882       case ISD::XOR: Opcode = X86ISD::XOR; break;
5883       case ISD::AND: Opcode = X86ISD::AND; break;
5884       default: llvm_unreachable("unexpected operator!");
5885       }
5886       NumOperands = 2;
5887       break;
5888     case X86ISD::ADD:
5889     case X86ISD::SUB:
5890     case X86ISD::INC:
5891     case X86ISD::DEC:
5892     case X86ISD::OR:
5893     case X86ISD::XOR:
5894     case X86ISD::AND:
5895       return SDValue(Op.getNode(), 1);
5896     default:
5897     default_case:
5898       break;
5899     }
5900     if (Opcode != 0) {
5901       SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
5902       SmallVector<SDValue, 4> Ops;
5903       for (unsigned i = 0; i != NumOperands; ++i)
5904         Ops.push_back(Op.getOperand(i));
5905       SDValue New = DAG.getNode(Opcode, dl, VTs, &Ops[0], NumOperands);
5906       DAG.ReplaceAllUsesWith(Op, New);
5907       return SDValue(New.getNode(), 1);
5908     }
5909   }
5910
5911   // Otherwise just emit a CMP with 0, which is the TEST pattern.
5912   return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
5913                      DAG.getConstant(0, Op.getValueType()));
5914 }
5915
5916 /// Emit nodes that will be selected as "cmp Op0,Op1", or something
5917 /// equivalent.
5918 SDValue X86TargetLowering::EmitCmp(SDValue Op0, SDValue Op1, unsigned X86CC,
5919                                    SelectionDAG &DAG) {
5920   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op1))
5921     if (C->getAPIntValue() == 0)
5922       return EmitTest(Op0, X86CC, DAG);
5923
5924   DebugLoc dl = Op0.getDebugLoc();
5925   return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op0, Op1);
5926 }
5927
5928 /// LowerToBT - Result of 'and' is compared against zero. Turn it into a BT node
5929 /// if it's possible.
5930 static SDValue LowerToBT(SDValue And, ISD::CondCode CC,
5931                          DebugLoc dl, SelectionDAG &DAG) {
5932   SDValue Op0 = And.getOperand(0);
5933   SDValue Op1 = And.getOperand(1);
5934   if (Op0.getOpcode() == ISD::TRUNCATE)
5935     Op0 = Op0.getOperand(0);
5936   if (Op1.getOpcode() == ISD::TRUNCATE)
5937     Op1 = Op1.getOperand(0);
5938
5939   SDValue LHS, RHS;
5940   if (Op1.getOpcode() == ISD::SHL) {
5941     if (ConstantSDNode *And10C = dyn_cast<ConstantSDNode>(Op1.getOperand(0)))
5942       if (And10C->getZExtValue() == 1) {
5943         LHS = Op0;
5944         RHS = Op1.getOperand(1);
5945       }
5946   } else if (Op0.getOpcode() == ISD::SHL) {
5947     if (ConstantSDNode *And00C = dyn_cast<ConstantSDNode>(Op0.getOperand(0)))
5948       if (And00C->getZExtValue() == 1) {
5949         LHS = Op1;
5950         RHS = Op0.getOperand(1);
5951       }
5952   } else if (Op1.getOpcode() == ISD::Constant) {
5953     ConstantSDNode *AndRHS = cast<ConstantSDNode>(Op1);
5954     SDValue AndLHS = Op0;
5955     if (AndRHS->getZExtValue() == 1 && AndLHS.getOpcode() == ISD::SRL) {
5956       LHS = AndLHS.getOperand(0);
5957       RHS = AndLHS.getOperand(1);
5958     }
5959   }
5960
5961   if (LHS.getNode()) {
5962     // If LHS is i8, promote it to i16 with any_extend.  There is no i8 BT
5963     // instruction.  Since the shift amount is in-range-or-undefined, we know
5964     // that doing a bittest on the i16 value is ok.  We extend to i32 because
5965     // the encoding for the i16 version is larger than the i32 version.
5966     if (LHS.getValueType() == MVT::i8)
5967       LHS = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, LHS);
5968
5969     // If the operand types disagree, extend the shift amount to match.  Since
5970     // BT ignores high bits (like shifts) we can use anyextend.
5971     if (LHS.getValueType() != RHS.getValueType())
5972       RHS = DAG.getNode(ISD::ANY_EXTEND, dl, LHS.getValueType(), RHS);
5973
5974     SDValue BT = DAG.getNode(X86ISD::BT, dl, MVT::i32, LHS, RHS);
5975     unsigned Cond = CC == ISD::SETEQ ? X86::COND_AE : X86::COND_B;
5976     return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
5977                        DAG.getConstant(Cond, MVT::i8), BT);
5978   }
5979
5980   return SDValue();
5981 }
5982
5983 SDValue X86TargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) {
5984   assert(Op.getValueType() == MVT::i8 && "SetCC type must be 8-bit integer");
5985   SDValue Op0 = Op.getOperand(0);
5986   SDValue Op1 = Op.getOperand(1);
5987   DebugLoc dl = Op.getDebugLoc();
5988   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
5989
5990   // Optimize to BT if possible.
5991   // Lower (X & (1 << N)) == 0 to BT(X, N).
5992   // Lower ((X >>u N) & 1) != 0 to BT(X, N).
5993   // Lower ((X >>s N) & 1) != 0 to BT(X, N).
5994   if (Op0.getOpcode() == ISD::AND &&
5995       Op0.hasOneUse() &&
5996       Op1.getOpcode() == ISD::Constant &&
5997       cast<ConstantSDNode>(Op1)->getZExtValue() == 0 &&
5998       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
5999     SDValue NewSetCC = LowerToBT(Op0, CC, dl, DAG);
6000     if (NewSetCC.getNode())
6001       return NewSetCC;
6002   }
6003
6004   // Look for "(setcc) == / != 1" to avoid unncessary setcc.
6005   if (Op0.getOpcode() == X86ISD::SETCC &&
6006       Op1.getOpcode() == ISD::Constant &&
6007       (cast<ConstantSDNode>(Op1)->getZExtValue() == 1 ||
6008        cast<ConstantSDNode>(Op1)->isNullValue()) &&
6009       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
6010     X86::CondCode CCode = (X86::CondCode)Op0.getConstantOperandVal(0);
6011     bool Invert = (CC == ISD::SETNE) ^
6012       cast<ConstantSDNode>(Op1)->isNullValue();
6013     if (Invert)
6014       CCode = X86::GetOppositeBranchCondition(CCode);
6015     return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
6016                        DAG.getConstant(CCode, MVT::i8), Op0.getOperand(1));
6017   }
6018
6019   bool isFP = Op.getOperand(1).getValueType().isFloatingPoint();
6020   unsigned X86CC = TranslateX86CC(CC, isFP, Op0, Op1, DAG);
6021   if (X86CC == X86::COND_INVALID)
6022     return SDValue();
6023
6024   SDValue Cond = EmitCmp(Op0, Op1, X86CC, DAG);
6025
6026   // Use sbb x, x to materialize carry bit into a GPR.
6027   if (X86CC == X86::COND_B)
6028     return DAG.getNode(ISD::AND, dl, MVT::i8,
6029                        DAG.getNode(X86ISD::SETCC_CARRY, dl, MVT::i8,
6030                                    DAG.getConstant(X86CC, MVT::i8), Cond),
6031                        DAG.getConstant(1, MVT::i8));
6032
6033   return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
6034                      DAG.getConstant(X86CC, MVT::i8), Cond);
6035 }
6036
6037 SDValue X86TargetLowering::LowerVSETCC(SDValue Op, SelectionDAG &DAG) {
6038   SDValue Cond;
6039   SDValue Op0 = Op.getOperand(0);
6040   SDValue Op1 = Op.getOperand(1);
6041   SDValue CC = Op.getOperand(2);
6042   EVT VT = Op.getValueType();
6043   ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
6044   bool isFP = Op.getOperand(1).getValueType().isFloatingPoint();
6045   DebugLoc dl = Op.getDebugLoc();
6046
6047   if (isFP) {
6048     unsigned SSECC = 8;
6049     EVT VT0 = Op0.getValueType();
6050     assert(VT0 == MVT::v4f32 || VT0 == MVT::v2f64);
6051     unsigned Opc = VT0 == MVT::v4f32 ? X86ISD::CMPPS : X86ISD::CMPPD;
6052     bool Swap = false;
6053
6054     switch (SetCCOpcode) {
6055     default: break;
6056     case ISD::SETOEQ:
6057     case ISD::SETEQ:  SSECC = 0; break;
6058     case ISD::SETOGT:
6059     case ISD::SETGT: Swap = true; // Fallthrough
6060     case ISD::SETLT:
6061     case ISD::SETOLT: SSECC = 1; break;
6062     case ISD::SETOGE:
6063     case ISD::SETGE: Swap = true; // Fallthrough
6064     case ISD::SETLE:
6065     case ISD::SETOLE: SSECC = 2; break;
6066     case ISD::SETUO:  SSECC = 3; break;
6067     case ISD::SETUNE:
6068     case ISD::SETNE:  SSECC = 4; break;
6069     case ISD::SETULE: Swap = true;
6070     case ISD::SETUGE: SSECC = 5; break;
6071     case ISD::SETULT: Swap = true;
6072     case ISD::SETUGT: SSECC = 6; break;
6073     case ISD::SETO:   SSECC = 7; break;
6074     }
6075     if (Swap)
6076       std::swap(Op0, Op1);
6077
6078     // In the two special cases we can't handle, emit two comparisons.
6079     if (SSECC == 8) {
6080       if (SetCCOpcode == ISD::SETUEQ) {
6081         SDValue UNORD, EQ;
6082         UNORD = DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(3, MVT::i8));
6083         EQ = DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(0, MVT::i8));
6084         return DAG.getNode(ISD::OR, dl, VT, UNORD, EQ);
6085       }
6086       else if (SetCCOpcode == ISD::SETONE) {
6087         SDValue ORD, NEQ;
6088         ORD = DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(7, MVT::i8));
6089         NEQ = DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(4, MVT::i8));
6090         return DAG.getNode(ISD::AND, dl, VT, ORD, NEQ);
6091       }
6092       llvm_unreachable("Illegal FP comparison");
6093     }
6094     // Handle all other FP comparisons here.
6095     return DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(SSECC, MVT::i8));
6096   }
6097
6098   // We are handling one of the integer comparisons here.  Since SSE only has
6099   // GT and EQ comparisons for integer, swapping operands and multiple
6100   // operations may be required for some comparisons.
6101   unsigned Opc = 0, EQOpc = 0, GTOpc = 0;
6102   bool Swap = false, Invert = false, FlipSigns = false;
6103
6104   switch (VT.getSimpleVT().SimpleTy) {
6105   default: break;
6106   case MVT::v8i8:
6107   case MVT::v16i8: EQOpc = X86ISD::PCMPEQB; GTOpc = X86ISD::PCMPGTB; break;
6108   case MVT::v4i16:
6109   case MVT::v8i16: EQOpc = X86ISD::PCMPEQW; GTOpc = X86ISD::PCMPGTW; break;
6110   case MVT::v2i32:
6111   case MVT::v4i32: EQOpc = X86ISD::PCMPEQD; GTOpc = X86ISD::PCMPGTD; break;
6112   case MVT::v2i64: EQOpc = X86ISD::PCMPEQQ; GTOpc = X86ISD::PCMPGTQ; break;
6113   }
6114
6115   switch (SetCCOpcode) {
6116   default: break;
6117   case ISD::SETNE:  Invert = true;
6118   case ISD::SETEQ:  Opc = EQOpc; break;
6119   case ISD::SETLT:  Swap = true;
6120   case ISD::SETGT:  Opc = GTOpc; break;
6121   case ISD::SETGE:  Swap = true;
6122   case ISD::SETLE:  Opc = GTOpc; Invert = true; break;
6123   case ISD::SETULT: Swap = true;
6124   case ISD::SETUGT: Opc = GTOpc; FlipSigns = true; break;
6125   case ISD::SETUGE: Swap = true;
6126   case ISD::SETULE: Opc = GTOpc; FlipSigns = true; Invert = true; break;
6127   }
6128   if (Swap)
6129     std::swap(Op0, Op1);
6130
6131   // Since SSE has no unsigned integer comparisons, we need to flip  the sign
6132   // bits of the inputs before performing those operations.
6133   if (FlipSigns) {
6134     EVT EltVT = VT.getVectorElementType();
6135     SDValue SignBit = DAG.getConstant(APInt::getSignBit(EltVT.getSizeInBits()),
6136                                       EltVT);
6137     std::vector<SDValue> SignBits(VT.getVectorNumElements(), SignBit);
6138     SDValue SignVec = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &SignBits[0],
6139                                     SignBits.size());
6140     Op0 = DAG.getNode(ISD::XOR, dl, VT, Op0, SignVec);
6141     Op1 = DAG.getNode(ISD::XOR, dl, VT, Op1, SignVec);
6142   }
6143
6144   SDValue Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
6145
6146   // If the logical-not of the result is required, perform that now.
6147   if (Invert)
6148     Result = DAG.getNOT(dl, Result, VT);
6149
6150   return Result;
6151 }
6152
6153 // isX86LogicalCmp - Return true if opcode is a X86 logical comparison.
6154 static bool isX86LogicalCmp(SDValue Op) {
6155   unsigned Opc = Op.getNode()->getOpcode();
6156   if (Opc == X86ISD::CMP || Opc == X86ISD::COMI || Opc == X86ISD::UCOMI)
6157     return true;
6158   if (Op.getResNo() == 1 &&
6159       (Opc == X86ISD::ADD ||
6160        Opc == X86ISD::SUB ||
6161        Opc == X86ISD::SMUL ||
6162        Opc == X86ISD::UMUL ||
6163        Opc == X86ISD::INC ||
6164        Opc == X86ISD::DEC ||
6165        Opc == X86ISD::OR ||
6166        Opc == X86ISD::XOR ||
6167        Opc == X86ISD::AND))
6168     return true;
6169
6170   return false;
6171 }
6172
6173 SDValue X86TargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) {
6174   bool addTest = true;
6175   SDValue Cond  = Op.getOperand(0);
6176   DebugLoc dl = Op.getDebugLoc();
6177   SDValue CC;
6178
6179   if (Cond.getOpcode() == ISD::SETCC) {
6180     SDValue NewCond = LowerSETCC(Cond, DAG);
6181     if (NewCond.getNode())
6182       Cond = NewCond;
6183   }
6184
6185   // (select (x == 0), -1, 0) -> (sign_bit (x - 1))
6186   SDValue Op1 = Op.getOperand(1);
6187   SDValue Op2 = Op.getOperand(2);
6188   if (Cond.getOpcode() == X86ISD::SETCC &&
6189       cast<ConstantSDNode>(Cond.getOperand(0))->getZExtValue() == X86::COND_E) {
6190     SDValue Cmp = Cond.getOperand(1);
6191     if (Cmp.getOpcode() == X86ISD::CMP) {
6192       ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(Op1);
6193       ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(Op2);
6194       ConstantSDNode *RHSC =
6195         dyn_cast<ConstantSDNode>(Cmp.getOperand(1).getNode());
6196       if (N1C && N1C->isAllOnesValue() &&
6197           N2C && N2C->isNullValue() &&
6198           RHSC && RHSC->isNullValue()) {
6199         SDValue CmpOp0 = Cmp.getOperand(0);
6200         Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
6201                           CmpOp0, DAG.getConstant(1, CmpOp0.getValueType()));
6202         return DAG.getNode(X86ISD::SETCC_CARRY, dl, Op.getValueType(),
6203                            DAG.getConstant(X86::COND_B, MVT::i8), Cmp);
6204       }
6205     }
6206   }
6207
6208   // Look pass (and (setcc_carry (cmp ...)), 1).
6209   if (Cond.getOpcode() == ISD::AND &&
6210       Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
6211     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
6212     if (C && C->getAPIntValue() == 1) 
6213       Cond = Cond.getOperand(0);
6214   }
6215
6216   // If condition flag is set by a X86ISD::CMP, then use it as the condition
6217   // setting operand in place of the X86ISD::SETCC.
6218   if (Cond.getOpcode() == X86ISD::SETCC ||
6219       Cond.getOpcode() == X86ISD::SETCC_CARRY) {
6220     CC = Cond.getOperand(0);
6221
6222     SDValue Cmp = Cond.getOperand(1);
6223     unsigned Opc = Cmp.getOpcode();
6224     EVT VT = Op.getValueType();
6225
6226     bool IllegalFPCMov = false;
6227     if (VT.isFloatingPoint() && !VT.isVector() &&
6228         !isScalarFPTypeInSSEReg(VT))  // FPStack?
6229       IllegalFPCMov = !hasFPCMov(cast<ConstantSDNode>(CC)->getSExtValue());
6230
6231     if ((isX86LogicalCmp(Cmp) && !IllegalFPCMov) ||
6232         Opc == X86ISD::BT) { // FIXME
6233       Cond = Cmp;
6234       addTest = false;
6235     }
6236   }
6237
6238   if (addTest) {
6239     // Look pass the truncate.
6240     if (Cond.getOpcode() == ISD::TRUNCATE)
6241       Cond = Cond.getOperand(0);
6242
6243     // We know the result of AND is compared against zero. Try to match
6244     // it to BT.
6245     if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) { 
6246       SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, dl, DAG);
6247       if (NewSetCC.getNode()) {
6248         CC = NewSetCC.getOperand(0);
6249         Cond = NewSetCC.getOperand(1);
6250         addTest = false;
6251       }
6252     }
6253   }
6254
6255   if (addTest) {
6256     CC = DAG.getConstant(X86::COND_NE, MVT::i8);
6257     Cond = EmitTest(Cond, X86::COND_NE, DAG);
6258   }
6259
6260   // X86ISD::CMOV means set the result (which is operand 1) to the RHS if
6261   // condition is true.
6262   SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::Flag);
6263   SDValue Ops[] = { Op2, Op1, CC, Cond };
6264   return DAG.getNode(X86ISD::CMOV, dl, VTs, Ops, array_lengthof(Ops));
6265 }
6266
6267 // isAndOrOfSingleUseSetCCs - Return true if node is an ISD::AND or
6268 // ISD::OR of two X86ISD::SETCC nodes each of which has no other use apart
6269 // from the AND / OR.
6270 static bool isAndOrOfSetCCs(SDValue Op, unsigned &Opc) {
6271   Opc = Op.getOpcode();
6272   if (Opc != ISD::OR && Opc != ISD::AND)
6273     return false;
6274   return (Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
6275           Op.getOperand(0).hasOneUse() &&
6276           Op.getOperand(1).getOpcode() == X86ISD::SETCC &&
6277           Op.getOperand(1).hasOneUse());
6278 }
6279
6280 // isXor1OfSetCC - Return true if node is an ISD::XOR of a X86ISD::SETCC and
6281 // 1 and that the SETCC node has a single use.
6282 static bool isXor1OfSetCC(SDValue Op) {
6283   if (Op.getOpcode() != ISD::XOR)
6284     return false;
6285   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
6286   if (N1C && N1C->getAPIntValue() == 1) {
6287     return Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
6288       Op.getOperand(0).hasOneUse();
6289   }
6290   return false;
6291 }
6292
6293 SDValue X86TargetLowering::LowerBRCOND(SDValue Op, SelectionDAG &DAG) {
6294   bool addTest = true;
6295   SDValue Chain = Op.getOperand(0);
6296   SDValue Cond  = Op.getOperand(1);
6297   SDValue Dest  = Op.getOperand(2);
6298   DebugLoc dl = Op.getDebugLoc();
6299   SDValue CC;
6300
6301   if (Cond.getOpcode() == ISD::SETCC) {
6302     SDValue NewCond = LowerSETCC(Cond, DAG);
6303     if (NewCond.getNode())
6304       Cond = NewCond;
6305   }
6306 #if 0
6307   // FIXME: LowerXALUO doesn't handle these!!
6308   else if (Cond.getOpcode() == X86ISD::ADD  ||
6309            Cond.getOpcode() == X86ISD::SUB  ||
6310            Cond.getOpcode() == X86ISD::SMUL ||
6311            Cond.getOpcode() == X86ISD::UMUL)
6312     Cond = LowerXALUO(Cond, DAG);
6313 #endif
6314
6315   // Look pass (and (setcc_carry (cmp ...)), 1).
6316   if (Cond.getOpcode() == ISD::AND &&
6317       Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
6318     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
6319     if (C && C->getAPIntValue() == 1) 
6320       Cond = Cond.getOperand(0);
6321   }
6322
6323   // If condition flag is set by a X86ISD::CMP, then use it as the condition
6324   // setting operand in place of the X86ISD::SETCC.
6325   if (Cond.getOpcode() == X86ISD::SETCC ||
6326       Cond.getOpcode() == X86ISD::SETCC_CARRY) {
6327     CC = Cond.getOperand(0);
6328
6329     SDValue Cmp = Cond.getOperand(1);
6330     unsigned Opc = Cmp.getOpcode();
6331     // FIXME: WHY THE SPECIAL CASING OF LogicalCmp??
6332     if (isX86LogicalCmp(Cmp) || Opc == X86ISD::BT) {
6333       Cond = Cmp;
6334       addTest = false;
6335     } else {
6336       switch (cast<ConstantSDNode>(CC)->getZExtValue()) {
6337       default: break;
6338       case X86::COND_O:
6339       case X86::COND_B:
6340         // These can only come from an arithmetic instruction with overflow,
6341         // e.g. SADDO, UADDO.
6342         Cond = Cond.getNode()->getOperand(1);
6343         addTest = false;
6344         break;
6345       }
6346     }
6347   } else {
6348     unsigned CondOpc;
6349     if (Cond.hasOneUse() && isAndOrOfSetCCs(Cond, CondOpc)) {
6350       SDValue Cmp = Cond.getOperand(0).getOperand(1);
6351       if (CondOpc == ISD::OR) {
6352         // Also, recognize the pattern generated by an FCMP_UNE. We can emit
6353         // two branches instead of an explicit OR instruction with a
6354         // separate test.
6355         if (Cmp == Cond.getOperand(1).getOperand(1) &&
6356             isX86LogicalCmp(Cmp)) {
6357           CC = Cond.getOperand(0).getOperand(0);
6358           Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
6359                               Chain, Dest, CC, Cmp);
6360           CC = Cond.getOperand(1).getOperand(0);
6361           Cond = Cmp;
6362           addTest = false;
6363         }
6364       } else { // ISD::AND
6365         // Also, recognize the pattern generated by an FCMP_OEQ. We can emit
6366         // two branches instead of an explicit AND instruction with a
6367         // separate test. However, we only do this if this block doesn't
6368         // have a fall-through edge, because this requires an explicit
6369         // jmp when the condition is false.
6370         if (Cmp == Cond.getOperand(1).getOperand(1) &&
6371             isX86LogicalCmp(Cmp) &&
6372             Op.getNode()->hasOneUse()) {
6373           X86::CondCode CCode =
6374             (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
6375           CCode = X86::GetOppositeBranchCondition(CCode);
6376           CC = DAG.getConstant(CCode, MVT::i8);
6377           SDValue User = SDValue(*Op.getNode()->use_begin(), 0);
6378           // Look for an unconditional branch following this conditional branch.
6379           // We need this because we need to reverse the successors in order
6380           // to implement FCMP_OEQ.
6381           if (User.getOpcode() == ISD::BR) {
6382             SDValue FalseBB = User.getOperand(1);
6383             SDValue NewBR =
6384               DAG.UpdateNodeOperands(User, User.getOperand(0), Dest);
6385             assert(NewBR == User);
6386             Dest = FalseBB;
6387
6388             Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
6389                                 Chain, Dest, CC, Cmp);
6390             X86::CondCode CCode =
6391               (X86::CondCode)Cond.getOperand(1).getConstantOperandVal(0);
6392             CCode = X86::GetOppositeBranchCondition(CCode);
6393             CC = DAG.getConstant(CCode, MVT::i8);
6394             Cond = Cmp;
6395             addTest = false;
6396           }
6397         }
6398       }
6399     } else if (Cond.hasOneUse() && isXor1OfSetCC(Cond)) {
6400       // Recognize for xorb (setcc), 1 patterns. The xor inverts the condition.
6401       // It should be transformed during dag combiner except when the condition
6402       // is set by a arithmetics with overflow node.
6403       X86::CondCode CCode =
6404         (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
6405       CCode = X86::GetOppositeBranchCondition(CCode);
6406       CC = DAG.getConstant(CCode, MVT::i8);
6407       Cond = Cond.getOperand(0).getOperand(1);
6408       addTest = false;
6409     }
6410   }
6411
6412   if (addTest) {
6413     // Look pass the truncate.
6414     if (Cond.getOpcode() == ISD::TRUNCATE)
6415       Cond = Cond.getOperand(0);
6416
6417     // We know the result of AND is compared against zero. Try to match
6418     // it to BT.
6419     if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) { 
6420       SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, dl, DAG);
6421       if (NewSetCC.getNode()) {
6422         CC = NewSetCC.getOperand(0);
6423         Cond = NewSetCC.getOperand(1);
6424         addTest = false;
6425       }
6426     }
6427   }
6428
6429   if (addTest) {
6430     CC = DAG.getConstant(X86::COND_NE, MVT::i8);
6431     Cond = EmitTest(Cond, X86::COND_NE, DAG);
6432   }
6433   return DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
6434                      Chain, Dest, CC, Cond);
6435 }
6436
6437
6438 // Lower dynamic stack allocation to _alloca call for Cygwin/Mingw targets.
6439 // Calls to _alloca is needed to probe the stack when allocating more than 4k
6440 // bytes in one go. Touching the stack at 4K increments is necessary to ensure
6441 // that the guard pages used by the OS virtual memory manager are allocated in
6442 // correct sequence.
6443 SDValue
6444 X86TargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
6445                                            SelectionDAG &DAG) {
6446   assert(Subtarget->isTargetCygMing() &&
6447          "This should be used only on Cygwin/Mingw targets");
6448   DebugLoc dl = Op.getDebugLoc();
6449
6450   // Get the inputs.
6451   SDValue Chain = Op.getOperand(0);
6452   SDValue Size  = Op.getOperand(1);
6453   // FIXME: Ensure alignment here
6454
6455   SDValue Flag;
6456
6457   EVT IntPtr = getPointerTy();
6458   EVT SPTy = Subtarget->is64Bit() ? MVT::i64 : MVT::i32;
6459
6460   Chain = DAG.getCopyToReg(Chain, dl, X86::EAX, Size, Flag);
6461   Flag = Chain.getValue(1);
6462
6463   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Flag);
6464
6465   Chain = DAG.getNode(X86ISD::MINGW_ALLOCA, dl, NodeTys, Chain, Flag);
6466   Flag = Chain.getValue(1);
6467
6468   Chain = DAG.getCopyFromReg(Chain, dl, X86StackPtr, SPTy).getValue(1);
6469
6470   SDValue Ops1[2] = { Chain.getValue(0), Chain };
6471   return DAG.getMergeValues(Ops1, 2, dl);
6472 }
6473
6474 SDValue
6475 X86TargetLowering::EmitTargetCodeForMemset(SelectionDAG &DAG, DebugLoc dl,
6476                                            SDValue Chain,
6477                                            SDValue Dst, SDValue Src,
6478                                            SDValue Size, unsigned Align,
6479                                            const Value *DstSV,
6480                                            uint64_t DstSVOff) {
6481   ConstantSDNode *ConstantSize = dyn_cast<ConstantSDNode>(Size);
6482
6483   // If not DWORD aligned or size is more than the threshold, call the library.
6484   // The libc version is likely to be faster for these cases. It can use the
6485   // address value and run time information about the CPU.
6486   if ((Align & 3) != 0 ||
6487       !ConstantSize ||
6488       ConstantSize->getZExtValue() >
6489         getSubtarget()->getMaxInlineSizeThreshold()) {
6490     SDValue InFlag(0, 0);
6491
6492     // Check to see if there is a specialized entry-point for memory zeroing.
6493     ConstantSDNode *V = dyn_cast<ConstantSDNode>(Src);
6494
6495     if (const char *bzeroEntry =  V &&
6496         V->isNullValue() ? Subtarget->getBZeroEntry() : 0) {
6497       EVT IntPtr = getPointerTy();
6498       const Type *IntPtrTy = TD->getIntPtrType(*DAG.getContext());
6499       TargetLowering::ArgListTy Args;
6500       TargetLowering::ArgListEntry Entry;
6501       Entry.Node = Dst;
6502       Entry.Ty = IntPtrTy;
6503       Args.push_back(Entry);
6504       Entry.Node = Size;
6505       Args.push_back(Entry);
6506       std::pair<SDValue,SDValue> CallResult =
6507         LowerCallTo(Chain, Type::getVoidTy(*DAG.getContext()),
6508                     false, false, false, false,
6509                     0, CallingConv::C, false, /*isReturnValueUsed=*/false,
6510                     DAG.getExternalSymbol(bzeroEntry, IntPtr), Args, DAG, dl);
6511       return CallResult.second;
6512     }
6513
6514     // Otherwise have the target-independent code call memset.
6515     return SDValue();
6516   }
6517
6518   uint64_t SizeVal = ConstantSize->getZExtValue();
6519   SDValue InFlag(0, 0);
6520   EVT AVT;
6521   SDValue Count;
6522   ConstantSDNode *ValC = dyn_cast<ConstantSDNode>(Src);
6523   unsigned BytesLeft = 0;
6524   bool TwoRepStos = false;
6525   if (ValC) {
6526     unsigned ValReg;
6527     uint64_t Val = ValC->getZExtValue() & 255;
6528
6529     // If the value is a constant, then we can potentially use larger sets.
6530     switch (Align & 3) {
6531     case 2:   // WORD aligned
6532       AVT = MVT::i16;
6533       ValReg = X86::AX;
6534       Val = (Val << 8) | Val;
6535       break;
6536     case 0:  // DWORD aligned
6537       AVT = MVT::i32;
6538       ValReg = X86::EAX;
6539       Val = (Val << 8)  | Val;
6540       Val = (Val << 16) | Val;
6541       if (Subtarget->is64Bit() && ((Align & 0x7) == 0)) {  // QWORD aligned
6542         AVT = MVT::i64;
6543         ValReg = X86::RAX;
6544         Val = (Val << 32) | Val;
6545       }
6546       break;
6547     default:  // Byte aligned
6548       AVT = MVT::i8;
6549       ValReg = X86::AL;
6550       Count = DAG.getIntPtrConstant(SizeVal);
6551       break;
6552     }
6553
6554     if (AVT.bitsGT(MVT::i8)) {
6555       unsigned UBytes = AVT.getSizeInBits() / 8;
6556       Count = DAG.getIntPtrConstant(SizeVal / UBytes);
6557       BytesLeft = SizeVal % UBytes;
6558     }
6559
6560     Chain  = DAG.getCopyToReg(Chain, dl, ValReg, DAG.getConstant(Val, AVT),
6561                               InFlag);
6562     InFlag = Chain.getValue(1);
6563   } else {
6564     AVT = MVT::i8;
6565     Count  = DAG.getIntPtrConstant(SizeVal);
6566     Chain  = DAG.getCopyToReg(Chain, dl, X86::AL, Src, InFlag);
6567     InFlag = Chain.getValue(1);
6568   }
6569
6570   Chain  = DAG.getCopyToReg(Chain, dl, Subtarget->is64Bit() ? X86::RCX :
6571                                                               X86::ECX,
6572                             Count, InFlag);
6573   InFlag = Chain.getValue(1);
6574   Chain  = DAG.getCopyToReg(Chain, dl, Subtarget->is64Bit() ? X86::RDI :
6575                                                               X86::EDI,
6576                             Dst, InFlag);
6577   InFlag = Chain.getValue(1);
6578
6579   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Flag);
6580   SDValue Ops[] = { Chain, DAG.getValueType(AVT), InFlag };
6581   Chain = DAG.getNode(X86ISD::REP_STOS, dl, Tys, Ops, array_lengthof(Ops));
6582
6583   if (TwoRepStos) {
6584     InFlag = Chain.getValue(1);
6585     Count  = Size;
6586     EVT CVT = Count.getValueType();
6587     SDValue Left = DAG.getNode(ISD::AND, dl, CVT, Count,
6588                                DAG.getConstant((AVT == MVT::i64) ? 7 : 3, CVT));
6589     Chain  = DAG.getCopyToReg(Chain, dl, (CVT == MVT::i64) ? X86::RCX :
6590                                                              X86::ECX,
6591                               Left, InFlag);
6592     InFlag = Chain.getValue(1);
6593     Tys = DAG.getVTList(MVT::Other, MVT::Flag);
6594     SDValue Ops[] = { Chain, DAG.getValueType(MVT::i8), InFlag };
6595     Chain = DAG.getNode(X86ISD::REP_STOS, dl, Tys, Ops, array_lengthof(Ops));
6596   } else if (BytesLeft) {
6597     // Handle the last 1 - 7 bytes.
6598     unsigned Offset = SizeVal - BytesLeft;
6599     EVT AddrVT = Dst.getValueType();
6600     EVT SizeVT = Size.getValueType();
6601
6602     Chain = DAG.getMemset(Chain, dl,
6603                           DAG.getNode(ISD::ADD, dl, AddrVT, Dst,
6604                                       DAG.getConstant(Offset, AddrVT)),
6605                           Src,
6606                           DAG.getConstant(BytesLeft, SizeVT),
6607                           Align, DstSV, DstSVOff + Offset);
6608   }
6609
6610   // TODO: Use a Tokenfactor, as in memcpy, instead of a single chain.
6611   return Chain;
6612 }
6613
6614 SDValue
6615 X86TargetLowering::EmitTargetCodeForMemcpy(SelectionDAG &DAG, DebugLoc dl,
6616                                       SDValue Chain, SDValue Dst, SDValue Src,
6617                                       SDValue Size, unsigned Align,
6618                                       bool AlwaysInline,
6619                                       const Value *DstSV, uint64_t DstSVOff,
6620                                       const Value *SrcSV, uint64_t SrcSVOff) {
6621   // This requires the copy size to be a constant, preferrably
6622   // within a subtarget-specific limit.
6623   ConstantSDNode *ConstantSize = dyn_cast<ConstantSDNode>(Size);
6624   if (!ConstantSize)
6625     return SDValue();
6626   uint64_t SizeVal = ConstantSize->getZExtValue();
6627   if (!AlwaysInline && SizeVal > getSubtarget()->getMaxInlineSizeThreshold())
6628     return SDValue();
6629
6630   /// If not DWORD aligned, call the library.
6631   if ((Align & 3) != 0)
6632     return SDValue();
6633
6634   // DWORD aligned
6635   EVT AVT = MVT::i32;
6636   if (Subtarget->is64Bit() && ((Align & 0x7) == 0))  // QWORD aligned
6637     AVT = MVT::i64;
6638
6639   unsigned UBytes = AVT.getSizeInBits() / 8;
6640   unsigned CountVal = SizeVal / UBytes;
6641   SDValue Count = DAG.getIntPtrConstant(CountVal);
6642   unsigned BytesLeft = SizeVal % UBytes;
6643
6644   SDValue InFlag(0, 0);
6645   Chain  = DAG.getCopyToReg(Chain, dl, Subtarget->is64Bit() ? X86::RCX :
6646                                                               X86::ECX,
6647                             Count, InFlag);
6648   InFlag = Chain.getValue(1);
6649   Chain  = DAG.getCopyToReg(Chain, dl, Subtarget->is64Bit() ? X86::RDI :
6650                                                              X86::EDI,
6651                             Dst, InFlag);
6652   InFlag = Chain.getValue(1);
6653   Chain  = DAG.getCopyToReg(Chain, dl, Subtarget->is64Bit() ? X86::RSI :
6654                                                               X86::ESI,
6655                             Src, InFlag);
6656   InFlag = Chain.getValue(1);
6657
6658   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Flag);
6659   SDValue Ops[] = { Chain, DAG.getValueType(AVT), InFlag };
6660   SDValue RepMovs = DAG.getNode(X86ISD::REP_MOVS, dl, Tys, Ops,
6661                                 array_lengthof(Ops));
6662
6663   SmallVector<SDValue, 4> Results;
6664   Results.push_back(RepMovs);
6665   if (BytesLeft) {
6666     // Handle the last 1 - 7 bytes.
6667     unsigned Offset = SizeVal - BytesLeft;
6668     EVT DstVT = Dst.getValueType();
6669     EVT SrcVT = Src.getValueType();
6670     EVT SizeVT = Size.getValueType();
6671     Results.push_back(DAG.getMemcpy(Chain, dl,
6672                                     DAG.getNode(ISD::ADD, dl, DstVT, Dst,
6673                                                 DAG.getConstant(Offset, DstVT)),
6674                                     DAG.getNode(ISD::ADD, dl, SrcVT, Src,
6675                                                 DAG.getConstant(Offset, SrcVT)),
6676                                     DAG.getConstant(BytesLeft, SizeVT),
6677                                     Align, AlwaysInline,
6678                                     DstSV, DstSVOff + Offset,
6679                                     SrcSV, SrcSVOff + Offset));
6680   }
6681
6682   return DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
6683                      &Results[0], Results.size());
6684 }
6685
6686 SDValue X86TargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) {
6687   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
6688   DebugLoc dl = Op.getDebugLoc();
6689
6690   if (!Subtarget->is64Bit()) {
6691     // vastart just stores the address of the VarArgsFrameIndex slot into the
6692     // memory location argument.
6693     SDValue FR = DAG.getFrameIndex(VarArgsFrameIndex, getPointerTy());
6694     return DAG.getStore(Op.getOperand(0), dl, FR, Op.getOperand(1), SV, 0,
6695                         false, false, 0);
6696   }
6697
6698   // __va_list_tag:
6699   //   gp_offset         (0 - 6 * 8)
6700   //   fp_offset         (48 - 48 + 8 * 16)
6701   //   overflow_arg_area (point to parameters coming in memory).
6702   //   reg_save_area
6703   SmallVector<SDValue, 8> MemOps;
6704   SDValue FIN = Op.getOperand(1);
6705   // Store gp_offset
6706   SDValue Store = DAG.getStore(Op.getOperand(0), dl,
6707                                DAG.getConstant(VarArgsGPOffset, MVT::i32),
6708                                FIN, SV, 0, false, false, 0);
6709   MemOps.push_back(Store);
6710
6711   // Store fp_offset
6712   FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(),
6713                     FIN, DAG.getIntPtrConstant(4));
6714   Store = DAG.getStore(Op.getOperand(0), dl,
6715                        DAG.getConstant(VarArgsFPOffset, MVT::i32),
6716                        FIN, SV, 0, false, false, 0);
6717   MemOps.push_back(Store);
6718
6719   // Store ptr to overflow_arg_area
6720   FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(),
6721                     FIN, DAG.getIntPtrConstant(4));
6722   SDValue OVFIN = DAG.getFrameIndex(VarArgsFrameIndex, getPointerTy());
6723   Store = DAG.getStore(Op.getOperand(0), dl, OVFIN, FIN, SV, 0,
6724                        false, false, 0);
6725   MemOps.push_back(Store);
6726
6727   // Store ptr to reg_save_area.
6728   FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(),
6729                     FIN, DAG.getIntPtrConstant(8));
6730   SDValue RSFIN = DAG.getFrameIndex(RegSaveFrameIndex, getPointerTy());
6731   Store = DAG.getStore(Op.getOperand(0), dl, RSFIN, FIN, SV, 0,
6732                        false, false, 0);
6733   MemOps.push_back(Store);
6734   return DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
6735                      &MemOps[0], MemOps.size());
6736 }
6737
6738 SDValue X86TargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) {
6739   // X86-64 va_list is a struct { i32, i32, i8*, i8* }.
6740   assert(Subtarget->is64Bit() && "This code only handles 64-bit va_arg!");
6741   SDValue Chain = Op.getOperand(0);
6742   SDValue SrcPtr = Op.getOperand(1);
6743   SDValue SrcSV = Op.getOperand(2);
6744
6745   llvm_report_error("VAArgInst is not yet implemented for x86-64!");
6746   return SDValue();
6747 }
6748
6749 SDValue X86TargetLowering::LowerVACOPY(SDValue Op, SelectionDAG &DAG) {
6750   // X86-64 va_list is a struct { i32, i32, i8*, i8* }.
6751   assert(Subtarget->is64Bit() && "This code only handles 64-bit va_copy!");
6752   SDValue Chain = Op.getOperand(0);
6753   SDValue DstPtr = Op.getOperand(1);
6754   SDValue SrcPtr = Op.getOperand(2);
6755   const Value *DstSV = cast<SrcValueSDNode>(Op.getOperand(3))->getValue();
6756   const Value *SrcSV = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
6757   DebugLoc dl = Op.getDebugLoc();
6758
6759   return DAG.getMemcpy(Chain, dl, DstPtr, SrcPtr,
6760                        DAG.getIntPtrConstant(24), 8, false,
6761                        DstSV, 0, SrcSV, 0);
6762 }
6763
6764 SDValue
6765 X86TargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op, SelectionDAG &DAG) {
6766   DebugLoc dl = Op.getDebugLoc();
6767   unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
6768   switch (IntNo) {
6769   default: return SDValue();    // Don't custom lower most intrinsics.
6770   // Comparison intrinsics.
6771   case Intrinsic::x86_sse_comieq_ss:
6772   case Intrinsic::x86_sse_comilt_ss:
6773   case Intrinsic::x86_sse_comile_ss:
6774   case Intrinsic::x86_sse_comigt_ss:
6775   case Intrinsic::x86_sse_comige_ss:
6776   case Intrinsic::x86_sse_comineq_ss:
6777   case Intrinsic::x86_sse_ucomieq_ss:
6778   case Intrinsic::x86_sse_ucomilt_ss:
6779   case Intrinsic::x86_sse_ucomile_ss:
6780   case Intrinsic::x86_sse_ucomigt_ss:
6781   case Intrinsic::x86_sse_ucomige_ss:
6782   case Intrinsic::x86_sse_ucomineq_ss:
6783   case Intrinsic::x86_sse2_comieq_sd:
6784   case Intrinsic::x86_sse2_comilt_sd:
6785   case Intrinsic::x86_sse2_comile_sd:
6786   case Intrinsic::x86_sse2_comigt_sd:
6787   case Intrinsic::x86_sse2_comige_sd:
6788   case Intrinsic::x86_sse2_comineq_sd:
6789   case Intrinsic::x86_sse2_ucomieq_sd:
6790   case Intrinsic::x86_sse2_ucomilt_sd:
6791   case Intrinsic::x86_sse2_ucomile_sd:
6792   case Intrinsic::x86_sse2_ucomigt_sd:
6793   case Intrinsic::x86_sse2_ucomige_sd:
6794   case Intrinsic::x86_sse2_ucomineq_sd: {
6795     unsigned Opc = 0;
6796     ISD::CondCode CC = ISD::SETCC_INVALID;
6797     switch (IntNo) {
6798     default: break;
6799     case Intrinsic::x86_sse_comieq_ss:
6800     case Intrinsic::x86_sse2_comieq_sd:
6801       Opc = X86ISD::COMI;
6802       CC = ISD::SETEQ;
6803       break;
6804     case Intrinsic::x86_sse_comilt_ss:
6805     case Intrinsic::x86_sse2_comilt_sd:
6806       Opc = X86ISD::COMI;
6807       CC = ISD::SETLT;
6808       break;
6809     case Intrinsic::x86_sse_comile_ss:
6810     case Intrinsic::x86_sse2_comile_sd:
6811       Opc = X86ISD::COMI;
6812       CC = ISD::SETLE;
6813       break;
6814     case Intrinsic::x86_sse_comigt_ss:
6815     case Intrinsic::x86_sse2_comigt_sd:
6816       Opc = X86ISD::COMI;
6817       CC = ISD::SETGT;
6818       break;
6819     case Intrinsic::x86_sse_comige_ss:
6820     case Intrinsic::x86_sse2_comige_sd:
6821       Opc = X86ISD::COMI;
6822       CC = ISD::SETGE;
6823       break;
6824     case Intrinsic::x86_sse_comineq_ss:
6825     case Intrinsic::x86_sse2_comineq_sd:
6826       Opc = X86ISD::COMI;
6827       CC = ISD::SETNE;
6828       break;
6829     case Intrinsic::x86_sse_ucomieq_ss:
6830     case Intrinsic::x86_sse2_ucomieq_sd:
6831       Opc = X86ISD::UCOMI;
6832       CC = ISD::SETEQ;
6833       break;
6834     case Intrinsic::x86_sse_ucomilt_ss:
6835     case Intrinsic::x86_sse2_ucomilt_sd:
6836       Opc = X86ISD::UCOMI;
6837       CC = ISD::SETLT;
6838       break;
6839     case Intrinsic::x86_sse_ucomile_ss:
6840     case Intrinsic::x86_sse2_ucomile_sd:
6841       Opc = X86ISD::UCOMI;
6842       CC = ISD::SETLE;
6843       break;
6844     case Intrinsic::x86_sse_ucomigt_ss:
6845     case Intrinsic::x86_sse2_ucomigt_sd:
6846       Opc = X86ISD::UCOMI;
6847       CC = ISD::SETGT;
6848       break;
6849     case Intrinsic::x86_sse_ucomige_ss:
6850     case Intrinsic::x86_sse2_ucomige_sd:
6851       Opc = X86ISD::UCOMI;
6852       CC = ISD::SETGE;
6853       break;
6854     case Intrinsic::x86_sse_ucomineq_ss:
6855     case Intrinsic::x86_sse2_ucomineq_sd:
6856       Opc = X86ISD::UCOMI;
6857       CC = ISD::SETNE;
6858       break;
6859     }
6860
6861     SDValue LHS = Op.getOperand(1);
6862     SDValue RHS = Op.getOperand(2);
6863     unsigned X86CC = TranslateX86CC(CC, true, LHS, RHS, DAG);
6864     assert(X86CC != X86::COND_INVALID && "Unexpected illegal condition!");
6865     SDValue Cond = DAG.getNode(Opc, dl, MVT::i32, LHS, RHS);
6866     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
6867                                 DAG.getConstant(X86CC, MVT::i8), Cond);
6868     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
6869   }
6870   // ptest intrinsics. The intrinsic these come from are designed to return
6871   // an integer value, not just an instruction so lower it to the ptest
6872   // pattern and a setcc for the result.
6873   case Intrinsic::x86_sse41_ptestz:
6874   case Intrinsic::x86_sse41_ptestc:
6875   case Intrinsic::x86_sse41_ptestnzc:{
6876     unsigned X86CC = 0;
6877     switch (IntNo) {
6878     default: llvm_unreachable("Bad fallthrough in Intrinsic lowering.");
6879     case Intrinsic::x86_sse41_ptestz:
6880       // ZF = 1
6881       X86CC = X86::COND_E;
6882       break;
6883     case Intrinsic::x86_sse41_ptestc:
6884       // CF = 1
6885       X86CC = X86::COND_B;
6886       break;
6887     case Intrinsic::x86_sse41_ptestnzc:
6888       // ZF and CF = 0
6889       X86CC = X86::COND_A;
6890       break;
6891     }
6892
6893     SDValue LHS = Op.getOperand(1);
6894     SDValue RHS = Op.getOperand(2);
6895     SDValue Test = DAG.getNode(X86ISD::PTEST, dl, MVT::i32, LHS, RHS);
6896     SDValue CC = DAG.getConstant(X86CC, MVT::i8);
6897     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8, CC, Test);
6898     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
6899   }
6900
6901   // Fix vector shift instructions where the last operand is a non-immediate
6902   // i32 value.
6903   case Intrinsic::x86_sse2_pslli_w:
6904   case Intrinsic::x86_sse2_pslli_d:
6905   case Intrinsic::x86_sse2_pslli_q:
6906   case Intrinsic::x86_sse2_psrli_w:
6907   case Intrinsic::x86_sse2_psrli_d:
6908   case Intrinsic::x86_sse2_psrli_q:
6909   case Intrinsic::x86_sse2_psrai_w:
6910   case Intrinsic::x86_sse2_psrai_d:
6911   case Intrinsic::x86_mmx_pslli_w:
6912   case Intrinsic::x86_mmx_pslli_d:
6913   case Intrinsic::x86_mmx_pslli_q:
6914   case Intrinsic::x86_mmx_psrli_w:
6915   case Intrinsic::x86_mmx_psrli_d:
6916   case Intrinsic::x86_mmx_psrli_q:
6917   case Intrinsic::x86_mmx_psrai_w:
6918   case Intrinsic::x86_mmx_psrai_d: {
6919     SDValue ShAmt = Op.getOperand(2);
6920     if (isa<ConstantSDNode>(ShAmt))
6921       return SDValue();
6922
6923     unsigned NewIntNo = 0;
6924     EVT ShAmtVT = MVT::v4i32;
6925     switch (IntNo) {
6926     case Intrinsic::x86_sse2_pslli_w:
6927       NewIntNo = Intrinsic::x86_sse2_psll_w;
6928       break;
6929     case Intrinsic::x86_sse2_pslli_d:
6930       NewIntNo = Intrinsic::x86_sse2_psll_d;
6931       break;
6932     case Intrinsic::x86_sse2_pslli_q:
6933       NewIntNo = Intrinsic::x86_sse2_psll_q;
6934       break;
6935     case Intrinsic::x86_sse2_psrli_w:
6936       NewIntNo = Intrinsic::x86_sse2_psrl_w;
6937       break;
6938     case Intrinsic::x86_sse2_psrli_d:
6939       NewIntNo = Intrinsic::x86_sse2_psrl_d;
6940       break;
6941     case Intrinsic::x86_sse2_psrli_q:
6942       NewIntNo = Intrinsic::x86_sse2_psrl_q;
6943       break;
6944     case Intrinsic::x86_sse2_psrai_w:
6945       NewIntNo = Intrinsic::x86_sse2_psra_w;
6946       break;
6947     case Intrinsic::x86_sse2_psrai_d:
6948       NewIntNo = Intrinsic::x86_sse2_psra_d;
6949       break;
6950     default: {
6951       ShAmtVT = MVT::v2i32;
6952       switch (IntNo) {
6953       case Intrinsic::x86_mmx_pslli_w:
6954         NewIntNo = Intrinsic::x86_mmx_psll_w;
6955         break;
6956       case Intrinsic::x86_mmx_pslli_d:
6957         NewIntNo = Intrinsic::x86_mmx_psll_d;
6958         break;
6959       case Intrinsic::x86_mmx_pslli_q:
6960         NewIntNo = Intrinsic::x86_mmx_psll_q;
6961         break;
6962       case Intrinsic::x86_mmx_psrli_w:
6963         NewIntNo = Intrinsic::x86_mmx_psrl_w;
6964         break;
6965       case Intrinsic::x86_mmx_psrli_d:
6966         NewIntNo = Intrinsic::x86_mmx_psrl_d;
6967         break;
6968       case Intrinsic::x86_mmx_psrli_q:
6969         NewIntNo = Intrinsic::x86_mmx_psrl_q;
6970         break;
6971       case Intrinsic::x86_mmx_psrai_w:
6972         NewIntNo = Intrinsic::x86_mmx_psra_w;
6973         break;
6974       case Intrinsic::x86_mmx_psrai_d:
6975         NewIntNo = Intrinsic::x86_mmx_psra_d;
6976         break;
6977       default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
6978       }
6979       break;
6980     }
6981     }
6982
6983     // The vector shift intrinsics with scalars uses 32b shift amounts but
6984     // the sse2/mmx shift instructions reads 64 bits. Set the upper 32 bits
6985     // to be zero.
6986     SDValue ShOps[4];
6987     ShOps[0] = ShAmt;
6988     ShOps[1] = DAG.getConstant(0, MVT::i32);
6989     if (ShAmtVT == MVT::v4i32) {
6990       ShOps[2] = DAG.getUNDEF(MVT::i32);
6991       ShOps[3] = DAG.getUNDEF(MVT::i32);
6992       ShAmt =  DAG.getNode(ISD::BUILD_VECTOR, dl, ShAmtVT, &ShOps[0], 4);
6993     } else {
6994       ShAmt =  DAG.getNode(ISD::BUILD_VECTOR, dl, ShAmtVT, &ShOps[0], 2);
6995     }
6996
6997     EVT VT = Op.getValueType();
6998     ShAmt = DAG.getNode(ISD::BIT_CONVERT, dl, VT, ShAmt);
6999     return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
7000                        DAG.getConstant(NewIntNo, MVT::i32),
7001                        Op.getOperand(1), ShAmt);
7002   }
7003   }
7004 }
7005
7006 SDValue X86TargetLowering::LowerRETURNADDR(SDValue Op, SelectionDAG &DAG) {
7007   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
7008   DebugLoc dl = Op.getDebugLoc();
7009
7010   if (Depth > 0) {
7011     SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
7012     SDValue Offset =
7013       DAG.getConstant(TD->getPointerSize(),
7014                       Subtarget->is64Bit() ? MVT::i64 : MVT::i32);
7015     return DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(),
7016                        DAG.getNode(ISD::ADD, dl, getPointerTy(),
7017                                    FrameAddr, Offset),
7018                        NULL, 0, false, false, 0);
7019   }
7020
7021   // Just load the return address.
7022   SDValue RetAddrFI = getReturnAddressFrameIndex(DAG);
7023   return DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(),
7024                      RetAddrFI, NULL, 0, false, false, 0);
7025 }
7026
7027 SDValue X86TargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) {
7028   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
7029   MFI->setFrameAddressIsTaken(true);
7030   EVT VT = Op.getValueType();
7031   DebugLoc dl = Op.getDebugLoc();  // FIXME probably not meaningful
7032   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
7033   unsigned FrameReg = Subtarget->is64Bit() ? X86::RBP : X86::EBP;
7034   SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
7035   while (Depth--)
7036     FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr, NULL, 0,
7037                             false, false, 0);
7038   return FrameAddr;
7039 }
7040
7041 SDValue X86TargetLowering::LowerFRAME_TO_ARGS_OFFSET(SDValue Op,
7042                                                      SelectionDAG &DAG) {
7043   return DAG.getIntPtrConstant(2*TD->getPointerSize());
7044 }
7045
7046 SDValue X86TargetLowering::LowerEH_RETURN(SDValue Op, SelectionDAG &DAG)
7047 {
7048   MachineFunction &MF = DAG.getMachineFunction();
7049   SDValue Chain     = Op.getOperand(0);
7050   SDValue Offset    = Op.getOperand(1);
7051   SDValue Handler   = Op.getOperand(2);
7052   DebugLoc dl       = Op.getDebugLoc();
7053
7054   SDValue Frame = DAG.getRegister(Subtarget->is64Bit() ? X86::RBP : X86::EBP,
7055                                   getPointerTy());
7056   unsigned StoreAddrReg = (Subtarget->is64Bit() ? X86::RCX : X86::ECX);
7057
7058   SDValue StoreAddr = DAG.getNode(ISD::SUB, dl, getPointerTy(), Frame,
7059                                   DAG.getIntPtrConstant(-TD->getPointerSize()));
7060   StoreAddr = DAG.getNode(ISD::ADD, dl, getPointerTy(), StoreAddr, Offset);
7061   Chain = DAG.getStore(Chain, dl, Handler, StoreAddr, NULL, 0, false, false, 0);
7062   Chain = DAG.getCopyToReg(Chain, dl, StoreAddrReg, StoreAddr);
7063   MF.getRegInfo().addLiveOut(StoreAddrReg);
7064
7065   return DAG.getNode(X86ISD::EH_RETURN, dl,
7066                      MVT::Other,
7067                      Chain, DAG.getRegister(StoreAddrReg, getPointerTy()));
7068 }
7069
7070 SDValue X86TargetLowering::LowerTRAMPOLINE(SDValue Op,
7071                                              SelectionDAG &DAG) {
7072   SDValue Root = Op.getOperand(0);
7073   SDValue Trmp = Op.getOperand(1); // trampoline
7074   SDValue FPtr = Op.getOperand(2); // nested function
7075   SDValue Nest = Op.getOperand(3); // 'nest' parameter value
7076   DebugLoc dl  = Op.getDebugLoc();
7077
7078   const Value *TrmpAddr = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
7079
7080   if (Subtarget->is64Bit()) {
7081     SDValue OutChains[6];
7082
7083     // Large code-model.
7084     const unsigned char JMP64r  = 0xFF; // 64-bit jmp through register opcode.
7085     const unsigned char MOV64ri = 0xB8; // X86::MOV64ri opcode.
7086
7087     const unsigned char N86R10 = RegInfo->getX86RegNum(X86::R10);
7088     const unsigned char N86R11 = RegInfo->getX86RegNum(X86::R11);
7089
7090     const unsigned char REX_WB = 0x40 | 0x08 | 0x01; // REX prefix
7091
7092     // Load the pointer to the nested function into R11.
7093     unsigned OpCode = ((MOV64ri | N86R11) << 8) | REX_WB; // movabsq r11
7094     SDValue Addr = Trmp;
7095     OutChains[0] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
7096                                 Addr, TrmpAddr, 0, false, false, 0);
7097
7098     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
7099                        DAG.getConstant(2, MVT::i64));
7100     OutChains[1] = DAG.getStore(Root, dl, FPtr, Addr, TrmpAddr, 2,
7101                                 false, false, 2);
7102
7103     // Load the 'nest' parameter value into R10.
7104     // R10 is specified in X86CallingConv.td
7105     OpCode = ((MOV64ri | N86R10) << 8) | REX_WB; // movabsq r10
7106     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
7107                        DAG.getConstant(10, MVT::i64));
7108     OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
7109                                 Addr, TrmpAddr, 10, false, false, 0);
7110
7111     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
7112                        DAG.getConstant(12, MVT::i64));
7113     OutChains[3] = DAG.getStore(Root, dl, Nest, Addr, TrmpAddr, 12,
7114                                 false, false, 2);
7115
7116     // Jump to the nested function.
7117     OpCode = (JMP64r << 8) | REX_WB; // jmpq *...
7118     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
7119                        DAG.getConstant(20, MVT::i64));
7120     OutChains[4] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
7121                                 Addr, TrmpAddr, 20, false, false, 0);
7122
7123     unsigned char ModRM = N86R11 | (4 << 3) | (3 << 6); // ...r11
7124     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
7125                        DAG.getConstant(22, MVT::i64));
7126     OutChains[5] = DAG.getStore(Root, dl, DAG.getConstant(ModRM, MVT::i8), Addr,
7127                                 TrmpAddr, 22, false, false, 0);
7128
7129     SDValue Ops[] =
7130       { Trmp, DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains, 6) };
7131     return DAG.getMergeValues(Ops, 2, dl);
7132   } else {
7133     const Function *Func =
7134       cast<Function>(cast<SrcValueSDNode>(Op.getOperand(5))->getValue());
7135     CallingConv::ID CC = Func->getCallingConv();
7136     unsigned NestReg;
7137
7138     switch (CC) {
7139     default:
7140       llvm_unreachable("Unsupported calling convention");
7141     case CallingConv::C:
7142     case CallingConv::X86_StdCall: {
7143       // Pass 'nest' parameter in ECX.
7144       // Must be kept in sync with X86CallingConv.td
7145       NestReg = X86::ECX;
7146
7147       // Check that ECX wasn't needed by an 'inreg' parameter.
7148       const FunctionType *FTy = Func->getFunctionType();
7149       const AttrListPtr &Attrs = Func->getAttributes();
7150
7151       if (!Attrs.isEmpty() && !Func->isVarArg()) {
7152         unsigned InRegCount = 0;
7153         unsigned Idx = 1;
7154
7155         for (FunctionType::param_iterator I = FTy->param_begin(),
7156              E = FTy->param_end(); I != E; ++I, ++Idx)
7157           if (Attrs.paramHasAttr(Idx, Attribute::InReg))
7158             // FIXME: should only count parameters that are lowered to integers.
7159             InRegCount += (TD->getTypeSizeInBits(*I) + 31) / 32;
7160
7161         if (InRegCount > 2) {
7162           llvm_report_error("Nest register in use - reduce number of inreg parameters!");
7163         }
7164       }
7165       break;
7166     }
7167     case CallingConv::X86_FastCall:
7168     case CallingConv::Fast:
7169       // Pass 'nest' parameter in EAX.
7170       // Must be kept in sync with X86CallingConv.td
7171       NestReg = X86::EAX;
7172       break;
7173     }
7174
7175     SDValue OutChains[4];
7176     SDValue Addr, Disp;
7177
7178     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
7179                        DAG.getConstant(10, MVT::i32));
7180     Disp = DAG.getNode(ISD::SUB, dl, MVT::i32, FPtr, Addr);
7181
7182     // This is storing the opcode for MOV32ri.
7183     const unsigned char MOV32ri = 0xB8; // X86::MOV32ri's opcode byte.
7184     const unsigned char N86Reg = RegInfo->getX86RegNum(NestReg);
7185     OutChains[0] = DAG.getStore(Root, dl,
7186                                 DAG.getConstant(MOV32ri|N86Reg, MVT::i8),
7187                                 Trmp, TrmpAddr, 0, false, false, 0);
7188
7189     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
7190                        DAG.getConstant(1, MVT::i32));
7191     OutChains[1] = DAG.getStore(Root, dl, Nest, Addr, TrmpAddr, 1,
7192                                 false, false, 1);
7193
7194     const unsigned char JMP = 0xE9; // jmp <32bit dst> opcode.
7195     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
7196                        DAG.getConstant(5, MVT::i32));
7197     OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(JMP, MVT::i8), Addr,
7198                                 TrmpAddr, 5, false, false, 1);
7199
7200     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
7201                        DAG.getConstant(6, MVT::i32));
7202     OutChains[3] = DAG.getStore(Root, dl, Disp, Addr, TrmpAddr, 6,
7203                                 false, false, 1);
7204
7205     SDValue Ops[] =
7206       { Trmp, DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains, 4) };
7207     return DAG.getMergeValues(Ops, 2, dl);
7208   }
7209 }
7210
7211 SDValue X86TargetLowering::LowerFLT_ROUNDS_(SDValue Op, SelectionDAG &DAG) {
7212   /*
7213    The rounding mode is in bits 11:10 of FPSR, and has the following
7214    settings:
7215      00 Round to nearest
7216      01 Round to -inf
7217      10 Round to +inf
7218      11 Round to 0
7219
7220   FLT_ROUNDS, on the other hand, expects the following:
7221     -1 Undefined
7222      0 Round to 0
7223      1 Round to nearest
7224      2 Round to +inf
7225      3 Round to -inf
7226
7227   To perform the conversion, we do:
7228     (((((FPSR & 0x800) >> 11) | ((FPSR & 0x400) >> 9)) + 1) & 3)
7229   */
7230
7231   MachineFunction &MF = DAG.getMachineFunction();
7232   const TargetMachine &TM = MF.getTarget();
7233   const TargetFrameInfo &TFI = *TM.getFrameInfo();
7234   unsigned StackAlignment = TFI.getStackAlignment();
7235   EVT VT = Op.getValueType();
7236   DebugLoc dl = Op.getDebugLoc();
7237
7238   // Save FP Control Word to stack slot
7239   int SSFI = MF.getFrameInfo()->CreateStackObject(2, StackAlignment, false);
7240   SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
7241
7242   SDValue Chain = DAG.getNode(X86ISD::FNSTCW16m, dl, MVT::Other,
7243                               DAG.getEntryNode(), StackSlot);
7244
7245   // Load FP Control Word from stack slot
7246   SDValue CWD = DAG.getLoad(MVT::i16, dl, Chain, StackSlot, NULL, 0,
7247                             false, false, 0);
7248
7249   // Transform as necessary
7250   SDValue CWD1 =
7251     DAG.getNode(ISD::SRL, dl, MVT::i16,
7252                 DAG.getNode(ISD::AND, dl, MVT::i16,
7253                             CWD, DAG.getConstant(0x800, MVT::i16)),
7254                 DAG.getConstant(11, MVT::i8));
7255   SDValue CWD2 =
7256     DAG.getNode(ISD::SRL, dl, MVT::i16,
7257                 DAG.getNode(ISD::AND, dl, MVT::i16,
7258                             CWD, DAG.getConstant(0x400, MVT::i16)),
7259                 DAG.getConstant(9, MVT::i8));
7260
7261   SDValue RetVal =
7262     DAG.getNode(ISD::AND, dl, MVT::i16,
7263                 DAG.getNode(ISD::ADD, dl, MVT::i16,
7264                             DAG.getNode(ISD::OR, dl, MVT::i16, CWD1, CWD2),
7265                             DAG.getConstant(1, MVT::i16)),
7266                 DAG.getConstant(3, MVT::i16));
7267
7268
7269   return DAG.getNode((VT.getSizeInBits() < 16 ?
7270                       ISD::TRUNCATE : ISD::ZERO_EXTEND), dl, VT, RetVal);
7271 }
7272
7273 SDValue X86TargetLowering::LowerCTLZ(SDValue Op, SelectionDAG &DAG) {
7274   EVT VT = Op.getValueType();
7275   EVT OpVT = VT;
7276   unsigned NumBits = VT.getSizeInBits();
7277   DebugLoc dl = Op.getDebugLoc();
7278
7279   Op = Op.getOperand(0);
7280   if (VT == MVT::i8) {
7281     // Zero extend to i32 since there is not an i8 bsr.
7282     OpVT = MVT::i32;
7283     Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
7284   }
7285
7286   // Issue a bsr (scan bits in reverse) which also sets EFLAGS.
7287   SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
7288   Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
7289
7290   // If src is zero (i.e. bsr sets ZF), returns NumBits.
7291   SDValue Ops[] = {
7292     Op,
7293     DAG.getConstant(NumBits+NumBits-1, OpVT),
7294     DAG.getConstant(X86::COND_E, MVT::i8),
7295     Op.getValue(1)
7296   };
7297   Op = DAG.getNode(X86ISD::CMOV, dl, OpVT, Ops, array_lengthof(Ops));
7298
7299   // Finally xor with NumBits-1.
7300   Op = DAG.getNode(ISD::XOR, dl, OpVT, Op, DAG.getConstant(NumBits-1, OpVT));
7301
7302   if (VT == MVT::i8)
7303     Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
7304   return Op;
7305 }
7306
7307 SDValue X86TargetLowering::LowerCTTZ(SDValue Op, SelectionDAG &DAG) {
7308   EVT VT = Op.getValueType();
7309   EVT OpVT = VT;
7310   unsigned NumBits = VT.getSizeInBits();
7311   DebugLoc dl = Op.getDebugLoc();
7312
7313   Op = Op.getOperand(0);
7314   if (VT == MVT::i8) {
7315     OpVT = MVT::i32;
7316     Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
7317   }
7318
7319   // Issue a bsf (scan bits forward) which also sets EFLAGS.
7320   SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
7321   Op = DAG.getNode(X86ISD::BSF, dl, VTs, Op);
7322
7323   // If src is zero (i.e. bsf sets ZF), returns NumBits.
7324   SDValue Ops[] = {
7325     Op,
7326     DAG.getConstant(NumBits, OpVT),
7327     DAG.getConstant(X86::COND_E, MVT::i8),
7328     Op.getValue(1)
7329   };
7330   Op = DAG.getNode(X86ISD::CMOV, dl, OpVT, Ops, array_lengthof(Ops));
7331
7332   if (VT == MVT::i8)
7333     Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
7334   return Op;
7335 }
7336
7337 SDValue X86TargetLowering::LowerMUL_V2I64(SDValue Op, SelectionDAG &DAG) {
7338   EVT VT = Op.getValueType();
7339   assert(VT == MVT::v2i64 && "Only know how to lower V2I64 multiply");
7340   DebugLoc dl = Op.getDebugLoc();
7341
7342   //  ulong2 Ahi = __builtin_ia32_psrlqi128( a, 32);
7343   //  ulong2 Bhi = __builtin_ia32_psrlqi128( b, 32);
7344   //  ulong2 AloBlo = __builtin_ia32_pmuludq128( a, b );
7345   //  ulong2 AloBhi = __builtin_ia32_pmuludq128( a, Bhi );
7346   //  ulong2 AhiBlo = __builtin_ia32_pmuludq128( Ahi, b );
7347   //
7348   //  AloBhi = __builtin_ia32_psllqi128( AloBhi, 32 );
7349   //  AhiBlo = __builtin_ia32_psllqi128( AhiBlo, 32 );
7350   //  return AloBlo + AloBhi + AhiBlo;
7351
7352   SDValue A = Op.getOperand(0);
7353   SDValue B = Op.getOperand(1);
7354
7355   SDValue Ahi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
7356                        DAG.getConstant(Intrinsic::x86_sse2_psrli_q, MVT::i32),
7357                        A, DAG.getConstant(32, MVT::i32));
7358   SDValue Bhi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
7359                        DAG.getConstant(Intrinsic::x86_sse2_psrli_q, MVT::i32),
7360                        B, DAG.getConstant(32, MVT::i32));
7361   SDValue AloBlo = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
7362                        DAG.getConstant(Intrinsic::x86_sse2_pmulu_dq, MVT::i32),
7363                        A, B);
7364   SDValue AloBhi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
7365                        DAG.getConstant(Intrinsic::x86_sse2_pmulu_dq, MVT::i32),
7366                        A, Bhi);
7367   SDValue AhiBlo = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
7368                        DAG.getConstant(Intrinsic::x86_sse2_pmulu_dq, MVT::i32),
7369                        Ahi, B);
7370   AloBhi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
7371                        DAG.getConstant(Intrinsic::x86_sse2_pslli_q, MVT::i32),
7372                        AloBhi, DAG.getConstant(32, MVT::i32));
7373   AhiBlo = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
7374                        DAG.getConstant(Intrinsic::x86_sse2_pslli_q, MVT::i32),
7375                        AhiBlo, DAG.getConstant(32, MVT::i32));
7376   SDValue Res = DAG.getNode(ISD::ADD, dl, VT, AloBlo, AloBhi);
7377   Res = DAG.getNode(ISD::ADD, dl, VT, Res, AhiBlo);
7378   return Res;
7379 }
7380
7381
7382 SDValue X86TargetLowering::LowerXALUO(SDValue Op, SelectionDAG &DAG) {
7383   // Lower the "add/sub/mul with overflow" instruction into a regular ins plus
7384   // a "setcc" instruction that checks the overflow flag. The "brcond" lowering
7385   // looks for this combo and may remove the "setcc" instruction if the "setcc"
7386   // has only one use.
7387   SDNode *N = Op.getNode();
7388   SDValue LHS = N->getOperand(0);
7389   SDValue RHS = N->getOperand(1);
7390   unsigned BaseOp = 0;
7391   unsigned Cond = 0;
7392   DebugLoc dl = Op.getDebugLoc();
7393
7394   switch (Op.getOpcode()) {
7395   default: llvm_unreachable("Unknown ovf instruction!");
7396   case ISD::SADDO:
7397     // A subtract of one will be selected as a INC. Note that INC doesn't
7398     // set CF, so we can't do this for UADDO.
7399     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op))
7400       if (C->getAPIntValue() == 1) {
7401         BaseOp = X86ISD::INC;
7402         Cond = X86::COND_O;
7403         break;
7404       }
7405     BaseOp = X86ISD::ADD;
7406     Cond = X86::COND_O;
7407     break;
7408   case ISD::UADDO:
7409     BaseOp = X86ISD::ADD;
7410     Cond = X86::COND_B;
7411     break;
7412   case ISD::SSUBO:
7413     // A subtract of one will be selected as a DEC. Note that DEC doesn't
7414     // set CF, so we can't do this for USUBO.
7415     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op))
7416       if (C->getAPIntValue() == 1) {
7417         BaseOp = X86ISD::DEC;
7418         Cond = X86::COND_O;
7419         break;
7420       }
7421     BaseOp = X86ISD::SUB;
7422     Cond = X86::COND_O;
7423     break;
7424   case ISD::USUBO:
7425     BaseOp = X86ISD::SUB;
7426     Cond = X86::COND_B;
7427     break;
7428   case ISD::SMULO:
7429     BaseOp = X86ISD::SMUL;
7430     Cond = X86::COND_O;
7431     break;
7432   case ISD::UMULO:
7433     BaseOp = X86ISD::UMUL;
7434     Cond = X86::COND_B;
7435     break;
7436   }
7437
7438   // Also sets EFLAGS.
7439   SDVTList VTs = DAG.getVTList(N->getValueType(0), MVT::i32);
7440   SDValue Sum = DAG.getNode(BaseOp, dl, VTs, LHS, RHS);
7441
7442   SDValue SetCC =
7443     DAG.getNode(X86ISD::SETCC, dl, N->getValueType(1),
7444                 DAG.getConstant(Cond, MVT::i32), SDValue(Sum.getNode(), 1));
7445
7446   DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), SetCC);
7447   return Sum;
7448 }
7449
7450 SDValue X86TargetLowering::LowerCMP_SWAP(SDValue Op, SelectionDAG &DAG) {
7451   EVT T = Op.getValueType();
7452   DebugLoc dl = Op.getDebugLoc();
7453   unsigned Reg = 0;
7454   unsigned size = 0;
7455   switch(T.getSimpleVT().SimpleTy) {
7456   default:
7457     assert(false && "Invalid value type!");
7458   case MVT::i8:  Reg = X86::AL;  size = 1; break;
7459   case MVT::i16: Reg = X86::AX;  size = 2; break;
7460   case MVT::i32: Reg = X86::EAX; size = 4; break;
7461   case MVT::i64:
7462     assert(Subtarget->is64Bit() && "Node not type legal!");
7463     Reg = X86::RAX; size = 8;
7464     break;
7465   }
7466   SDValue cpIn = DAG.getCopyToReg(Op.getOperand(0), dl, Reg,
7467                                     Op.getOperand(2), SDValue());
7468   SDValue Ops[] = { cpIn.getValue(0),
7469                     Op.getOperand(1),
7470                     Op.getOperand(3),
7471                     DAG.getTargetConstant(size, MVT::i8),
7472                     cpIn.getValue(1) };
7473   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Flag);
7474   SDValue Result = DAG.getNode(X86ISD::LCMPXCHG_DAG, dl, Tys, Ops, 5);
7475   SDValue cpOut =
7476     DAG.getCopyFromReg(Result.getValue(0), dl, Reg, T, Result.getValue(1));
7477   return cpOut;
7478 }
7479
7480 SDValue X86TargetLowering::LowerREADCYCLECOUNTER(SDValue Op,
7481                                                  SelectionDAG &DAG) {
7482   assert(Subtarget->is64Bit() && "Result not type legalized?");
7483   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Flag);
7484   SDValue TheChain = Op.getOperand(0);
7485   DebugLoc dl = Op.getDebugLoc();
7486   SDValue rd = DAG.getNode(X86ISD::RDTSC_DAG, dl, Tys, &TheChain, 1);
7487   SDValue rax = DAG.getCopyFromReg(rd, dl, X86::RAX, MVT::i64, rd.getValue(1));
7488   SDValue rdx = DAG.getCopyFromReg(rax.getValue(1), dl, X86::RDX, MVT::i64,
7489                                    rax.getValue(2));
7490   SDValue Tmp = DAG.getNode(ISD::SHL, dl, MVT::i64, rdx,
7491                             DAG.getConstant(32, MVT::i8));
7492   SDValue Ops[] = {
7493     DAG.getNode(ISD::OR, dl, MVT::i64, rax, Tmp),
7494     rdx.getValue(1)
7495   };
7496   return DAG.getMergeValues(Ops, 2, dl);
7497 }
7498
7499 SDValue X86TargetLowering::LowerLOAD_SUB(SDValue Op, SelectionDAG &DAG) {
7500   SDNode *Node = Op.getNode();
7501   DebugLoc dl = Node->getDebugLoc();
7502   EVT T = Node->getValueType(0);
7503   SDValue negOp = DAG.getNode(ISD::SUB, dl, T,
7504                               DAG.getConstant(0, T), Node->getOperand(2));
7505   return DAG.getAtomic(ISD::ATOMIC_LOAD_ADD, dl,
7506                        cast<AtomicSDNode>(Node)->getMemoryVT(),
7507                        Node->getOperand(0),
7508                        Node->getOperand(1), negOp,
7509                        cast<AtomicSDNode>(Node)->getSrcValue(),
7510                        cast<AtomicSDNode>(Node)->getAlignment());
7511 }
7512
7513 /// LowerOperation - Provide custom lowering hooks for some operations.
7514 ///
7515 SDValue X86TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) {
7516   switch (Op.getOpcode()) {
7517   default: llvm_unreachable("Should not custom lower this!");
7518   case ISD::ATOMIC_CMP_SWAP:    return LowerCMP_SWAP(Op,DAG);
7519   case ISD::ATOMIC_LOAD_SUB:    return LowerLOAD_SUB(Op,DAG);
7520   case ISD::BUILD_VECTOR:       return LowerBUILD_VECTOR(Op, DAG);
7521   case ISD::CONCAT_VECTORS:     return LowerCONCAT_VECTORS(Op, DAG);
7522   case ISD::VECTOR_SHUFFLE:     return LowerVECTOR_SHUFFLE(Op, DAG);
7523   case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
7524   case ISD::INSERT_VECTOR_ELT:  return LowerINSERT_VECTOR_ELT(Op, DAG);
7525   case ISD::SCALAR_TO_VECTOR:   return LowerSCALAR_TO_VECTOR(Op, DAG);
7526   case ISD::ConstantPool:       return LowerConstantPool(Op, DAG);
7527   case ISD::GlobalAddress:      return LowerGlobalAddress(Op, DAG);
7528   case ISD::GlobalTLSAddress:   return LowerGlobalTLSAddress(Op, DAG);
7529   case ISD::ExternalSymbol:     return LowerExternalSymbol(Op, DAG);
7530   case ISD::BlockAddress:       return LowerBlockAddress(Op, DAG);
7531   case ISD::SHL_PARTS:
7532   case ISD::SRA_PARTS:
7533   case ISD::SRL_PARTS:          return LowerShift(Op, DAG);
7534   case ISD::SINT_TO_FP:         return LowerSINT_TO_FP(Op, DAG);
7535   case ISD::UINT_TO_FP:         return LowerUINT_TO_FP(Op, DAG);
7536   case ISD::FP_TO_SINT:         return LowerFP_TO_SINT(Op, DAG);
7537   case ISD::FP_TO_UINT:         return LowerFP_TO_UINT(Op, DAG);
7538   case ISD::FABS:               return LowerFABS(Op, DAG);
7539   case ISD::FNEG:               return LowerFNEG(Op, DAG);
7540   case ISD::FCOPYSIGN:          return LowerFCOPYSIGN(Op, DAG);
7541   case ISD::SETCC:              return LowerSETCC(Op, DAG);
7542   case ISD::VSETCC:             return LowerVSETCC(Op, DAG);
7543   case ISD::SELECT:             return LowerSELECT(Op, DAG);
7544   case ISD::BRCOND:             return LowerBRCOND(Op, DAG);
7545   case ISD::JumpTable:          return LowerJumpTable(Op, DAG);
7546   case ISD::VASTART:            return LowerVASTART(Op, DAG);
7547   case ISD::VAARG:              return LowerVAARG(Op, DAG);
7548   case ISD::VACOPY:             return LowerVACOPY(Op, DAG);
7549   case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
7550   case ISD::RETURNADDR:         return LowerRETURNADDR(Op, DAG);
7551   case ISD::FRAMEADDR:          return LowerFRAMEADDR(Op, DAG);
7552   case ISD::FRAME_TO_ARGS_OFFSET:
7553                                 return LowerFRAME_TO_ARGS_OFFSET(Op, DAG);
7554   case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG);
7555   case ISD::EH_RETURN:          return LowerEH_RETURN(Op, DAG);
7556   case ISD::TRAMPOLINE:         return LowerTRAMPOLINE(Op, DAG);
7557   case ISD::FLT_ROUNDS_:        return LowerFLT_ROUNDS_(Op, DAG);
7558   case ISD::CTLZ:               return LowerCTLZ(Op, DAG);
7559   case ISD::CTTZ:               return LowerCTTZ(Op, DAG);
7560   case ISD::MUL:                return LowerMUL_V2I64(Op, DAG);
7561   case ISD::SADDO:
7562   case ISD::UADDO:
7563   case ISD::SSUBO:
7564   case ISD::USUBO:
7565   case ISD::SMULO:
7566   case ISD::UMULO:              return LowerXALUO(Op, DAG);
7567   case ISD::READCYCLECOUNTER:   return LowerREADCYCLECOUNTER(Op, DAG);
7568   }
7569 }
7570
7571 void X86TargetLowering::
7572 ReplaceATOMIC_BINARY_64(SDNode *Node, SmallVectorImpl<SDValue>&Results,
7573                         SelectionDAG &DAG, unsigned NewOp) {
7574   EVT T = Node->getValueType(0);
7575   DebugLoc dl = Node->getDebugLoc();
7576   assert (T == MVT::i64 && "Only know how to expand i64 atomics");
7577
7578   SDValue Chain = Node->getOperand(0);
7579   SDValue In1 = Node->getOperand(1);
7580   SDValue In2L = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
7581                              Node->getOperand(2), DAG.getIntPtrConstant(0));
7582   SDValue In2H = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
7583                              Node->getOperand(2), DAG.getIntPtrConstant(1));
7584   SDValue Ops[] = { Chain, In1, In2L, In2H };
7585   SDVTList Tys = DAG.getVTList(MVT::i32, MVT::i32, MVT::Other);
7586   SDValue Result =
7587     DAG.getMemIntrinsicNode(NewOp, dl, Tys, Ops, 4, MVT::i64,
7588                             cast<MemSDNode>(Node)->getMemOperand());
7589   SDValue OpsF[] = { Result.getValue(0), Result.getValue(1)};
7590   Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, OpsF, 2));
7591   Results.push_back(Result.getValue(2));
7592 }
7593
7594 /// ReplaceNodeResults - Replace a node with an illegal result type
7595 /// with a new node built out of custom code.
7596 void X86TargetLowering::ReplaceNodeResults(SDNode *N,
7597                                            SmallVectorImpl<SDValue>&Results,
7598                                            SelectionDAG &DAG) {
7599   DebugLoc dl = N->getDebugLoc();
7600   switch (N->getOpcode()) {
7601   default:
7602     assert(false && "Do not know how to custom type legalize this operation!");
7603     return;
7604   case ISD::FP_TO_SINT: {
7605     std::pair<SDValue,SDValue> Vals =
7606         FP_TO_INTHelper(SDValue(N, 0), DAG, true);
7607     SDValue FIST = Vals.first, StackSlot = Vals.second;
7608     if (FIST.getNode() != 0) {
7609       EVT VT = N->getValueType(0);
7610       // Return a load from the stack slot.
7611       Results.push_back(DAG.getLoad(VT, dl, FIST, StackSlot, NULL, 0,
7612                                     false, false, 0));
7613     }
7614     return;
7615   }
7616   case ISD::READCYCLECOUNTER: {
7617     SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Flag);
7618     SDValue TheChain = N->getOperand(0);
7619     SDValue rd = DAG.getNode(X86ISD::RDTSC_DAG, dl, Tys, &TheChain, 1);
7620     SDValue eax = DAG.getCopyFromReg(rd, dl, X86::EAX, MVT::i32,
7621                                      rd.getValue(1));
7622     SDValue edx = DAG.getCopyFromReg(eax.getValue(1), dl, X86::EDX, MVT::i32,
7623                                      eax.getValue(2));
7624     // Use a buildpair to merge the two 32-bit values into a 64-bit one.
7625     SDValue Ops[] = { eax, edx };
7626     Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Ops, 2));
7627     Results.push_back(edx.getValue(1));
7628     return;
7629   }
7630   case ISD::ATOMIC_CMP_SWAP: {
7631     EVT T = N->getValueType(0);
7632     assert (T == MVT::i64 && "Only know how to expand i64 Cmp and Swap");
7633     SDValue cpInL, cpInH;
7634     cpInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(2),
7635                         DAG.getConstant(0, MVT::i32));
7636     cpInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(2),
7637                         DAG.getConstant(1, MVT::i32));
7638     cpInL = DAG.getCopyToReg(N->getOperand(0), dl, X86::EAX, cpInL, SDValue());
7639     cpInH = DAG.getCopyToReg(cpInL.getValue(0), dl, X86::EDX, cpInH,
7640                              cpInL.getValue(1));
7641     SDValue swapInL, swapInH;
7642     swapInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(3),
7643                           DAG.getConstant(0, MVT::i32));
7644     swapInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(3),
7645                           DAG.getConstant(1, MVT::i32));
7646     swapInL = DAG.getCopyToReg(cpInH.getValue(0), dl, X86::EBX, swapInL,
7647                                cpInH.getValue(1));
7648     swapInH = DAG.getCopyToReg(swapInL.getValue(0), dl, X86::ECX, swapInH,
7649                                swapInL.getValue(1));
7650     SDValue Ops[] = { swapInH.getValue(0),
7651                       N->getOperand(1),
7652                       swapInH.getValue(1) };
7653     SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Flag);
7654     SDValue Result = DAG.getNode(X86ISD::LCMPXCHG8_DAG, dl, Tys, Ops, 3);
7655     SDValue cpOutL = DAG.getCopyFromReg(Result.getValue(0), dl, X86::EAX,
7656                                         MVT::i32, Result.getValue(1));
7657     SDValue cpOutH = DAG.getCopyFromReg(cpOutL.getValue(1), dl, X86::EDX,
7658                                         MVT::i32, cpOutL.getValue(2));
7659     SDValue OpsF[] = { cpOutL.getValue(0), cpOutH.getValue(0)};
7660     Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, OpsF, 2));
7661     Results.push_back(cpOutH.getValue(1));
7662     return;
7663   }
7664   case ISD::ATOMIC_LOAD_ADD:
7665     ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMADD64_DAG);
7666     return;
7667   case ISD::ATOMIC_LOAD_AND:
7668     ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMAND64_DAG);
7669     return;
7670   case ISD::ATOMIC_LOAD_NAND:
7671     ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMNAND64_DAG);
7672     return;
7673   case ISD::ATOMIC_LOAD_OR:
7674     ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMOR64_DAG);
7675     return;
7676   case ISD::ATOMIC_LOAD_SUB:
7677     ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMSUB64_DAG);
7678     return;
7679   case ISD::ATOMIC_LOAD_XOR:
7680     ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMXOR64_DAG);
7681     return;
7682   case ISD::ATOMIC_SWAP:
7683     ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMSWAP64_DAG);
7684     return;
7685   }
7686 }
7687
7688 const char *X86TargetLowering::getTargetNodeName(unsigned Opcode) const {
7689   switch (Opcode) {
7690   default: return NULL;
7691   case X86ISD::BSF:                return "X86ISD::BSF";
7692   case X86ISD::BSR:                return "X86ISD::BSR";
7693   case X86ISD::SHLD:               return "X86ISD::SHLD";
7694   case X86ISD::SHRD:               return "X86ISD::SHRD";
7695   case X86ISD::FAND:               return "X86ISD::FAND";
7696   case X86ISD::FOR:                return "X86ISD::FOR";
7697   case X86ISD::FXOR:               return "X86ISD::FXOR";
7698   case X86ISD::FSRL:               return "X86ISD::FSRL";
7699   case X86ISD::FILD:               return "X86ISD::FILD";
7700   case X86ISD::FILD_FLAG:          return "X86ISD::FILD_FLAG";
7701   case X86ISD::FP_TO_INT16_IN_MEM: return "X86ISD::FP_TO_INT16_IN_MEM";
7702   case X86ISD::FP_TO_INT32_IN_MEM: return "X86ISD::FP_TO_INT32_IN_MEM";
7703   case X86ISD::FP_TO_INT64_IN_MEM: return "X86ISD::FP_TO_INT64_IN_MEM";
7704   case X86ISD::FLD:                return "X86ISD::FLD";
7705   case X86ISD::FST:                return "X86ISD::FST";
7706   case X86ISD::CALL:               return "X86ISD::CALL";
7707   case X86ISD::RDTSC_DAG:          return "X86ISD::RDTSC_DAG";
7708   case X86ISD::BT:                 return "X86ISD::BT";
7709   case X86ISD::CMP:                return "X86ISD::CMP";
7710   case X86ISD::COMI:               return "X86ISD::COMI";
7711   case X86ISD::UCOMI:              return "X86ISD::UCOMI";
7712   case X86ISD::SETCC:              return "X86ISD::SETCC";
7713   case X86ISD::SETCC_CARRY:        return "X86ISD::SETCC_CARRY";
7714   case X86ISD::CMOV:               return "X86ISD::CMOV";
7715   case X86ISD::BRCOND:             return "X86ISD::BRCOND";
7716   case X86ISD::RET_FLAG:           return "X86ISD::RET_FLAG";
7717   case X86ISD::REP_STOS:           return "X86ISD::REP_STOS";
7718   case X86ISD::REP_MOVS:           return "X86ISD::REP_MOVS";
7719   case X86ISD::GlobalBaseReg:      return "X86ISD::GlobalBaseReg";
7720   case X86ISD::Wrapper:            return "X86ISD::Wrapper";
7721   case X86ISD::WrapperRIP:         return "X86ISD::WrapperRIP";
7722   case X86ISD::PEXTRB:             return "X86ISD::PEXTRB";
7723   case X86ISD::PEXTRW:             return "X86ISD::PEXTRW";
7724   case X86ISD::INSERTPS:           return "X86ISD::INSERTPS";
7725   case X86ISD::PINSRB:             return "X86ISD::PINSRB";
7726   case X86ISD::PINSRW:             return "X86ISD::PINSRW";
7727   case X86ISD::MMX_PINSRW:         return "X86ISD::MMX_PINSRW";
7728   case X86ISD::PSHUFB:             return "X86ISD::PSHUFB";
7729   case X86ISD::FMAX:               return "X86ISD::FMAX";
7730   case X86ISD::FMIN:               return "X86ISD::FMIN";
7731   case X86ISD::FRSQRT:             return "X86ISD::FRSQRT";
7732   case X86ISD::FRCP:               return "X86ISD::FRCP";
7733   case X86ISD::TLSADDR:            return "X86ISD::TLSADDR";
7734   case X86ISD::SegmentBaseAddress: return "X86ISD::SegmentBaseAddress";
7735   case X86ISD::EH_RETURN:          return "X86ISD::EH_RETURN";
7736   case X86ISD::TC_RETURN:          return "X86ISD::TC_RETURN";
7737   case X86ISD::FNSTCW16m:          return "X86ISD::FNSTCW16m";
7738   case X86ISD::LCMPXCHG_DAG:       return "X86ISD::LCMPXCHG_DAG";
7739   case X86ISD::LCMPXCHG8_DAG:      return "X86ISD::LCMPXCHG8_DAG";
7740   case X86ISD::ATOMADD64_DAG:      return "X86ISD::ATOMADD64_DAG";
7741   case X86ISD::ATOMSUB64_DAG:      return "X86ISD::ATOMSUB64_DAG";
7742   case X86ISD::ATOMOR64_DAG:       return "X86ISD::ATOMOR64_DAG";
7743   case X86ISD::ATOMXOR64_DAG:      return "X86ISD::ATOMXOR64_DAG";
7744   case X86ISD::ATOMAND64_DAG:      return "X86ISD::ATOMAND64_DAG";
7745   case X86ISD::ATOMNAND64_DAG:     return "X86ISD::ATOMNAND64_DAG";
7746   case X86ISD::VZEXT_MOVL:         return "X86ISD::VZEXT_MOVL";
7747   case X86ISD::VZEXT_LOAD:         return "X86ISD::VZEXT_LOAD";
7748   case X86ISD::VSHL:               return "X86ISD::VSHL";
7749   case X86ISD::VSRL:               return "X86ISD::VSRL";
7750   case X86ISD::CMPPD:              return "X86ISD::CMPPD";
7751   case X86ISD::CMPPS:              return "X86ISD::CMPPS";
7752   case X86ISD::PCMPEQB:            return "X86ISD::PCMPEQB";
7753   case X86ISD::PCMPEQW:            return "X86ISD::PCMPEQW";
7754   case X86ISD::PCMPEQD:            return "X86ISD::PCMPEQD";
7755   case X86ISD::PCMPEQQ:            return "X86ISD::PCMPEQQ";
7756   case X86ISD::PCMPGTB:            return "X86ISD::PCMPGTB";
7757   case X86ISD::PCMPGTW:            return "X86ISD::PCMPGTW";
7758   case X86ISD::PCMPGTD:            return "X86ISD::PCMPGTD";
7759   case X86ISD::PCMPGTQ:            return "X86ISD::PCMPGTQ";
7760   case X86ISD::ADD:                return "X86ISD::ADD";
7761   case X86ISD::SUB:                return "X86ISD::SUB";
7762   case X86ISD::SMUL:               return "X86ISD::SMUL";
7763   case X86ISD::UMUL:               return "X86ISD::UMUL";
7764   case X86ISD::INC:                return "X86ISD::INC";
7765   case X86ISD::DEC:                return "X86ISD::DEC";
7766   case X86ISD::OR:                 return "X86ISD::OR";
7767   case X86ISD::XOR:                return "X86ISD::XOR";
7768   case X86ISD::AND:                return "X86ISD::AND";
7769   case X86ISD::MUL_IMM:            return "X86ISD::MUL_IMM";
7770   case X86ISD::PTEST:              return "X86ISD::PTEST";
7771   case X86ISD::VASTART_SAVE_XMM_REGS: return "X86ISD::VASTART_SAVE_XMM_REGS";
7772   case X86ISD::MINGW_ALLOCA:       return "X86ISD::MINGW_ALLOCA";
7773   }
7774 }
7775
7776 // isLegalAddressingMode - Return true if the addressing mode represented
7777 // by AM is legal for this target, for a load/store of the specified type.
7778 bool X86TargetLowering::isLegalAddressingMode(const AddrMode &AM,
7779                                               const Type *Ty) const {
7780   // X86 supports extremely general addressing modes.
7781   CodeModel::Model M = getTargetMachine().getCodeModel();
7782
7783   // X86 allows a sign-extended 32-bit immediate field as a displacement.
7784   if (!X86::isOffsetSuitableForCodeModel(AM.BaseOffs, M, AM.BaseGV != NULL))
7785     return false;
7786
7787   if (AM.BaseGV) {
7788     unsigned GVFlags =
7789       Subtarget->ClassifyGlobalReference(AM.BaseGV, getTargetMachine());
7790
7791     // If a reference to this global requires an extra load, we can't fold it.
7792     if (isGlobalStubReference(GVFlags))
7793       return false;
7794
7795     // If BaseGV requires a register for the PIC base, we cannot also have a
7796     // BaseReg specified.
7797     if (AM.HasBaseReg && isGlobalRelativeToPICBase(GVFlags))
7798       return false;
7799
7800     // If lower 4G is not available, then we must use rip-relative addressing.
7801     if (Subtarget->is64Bit() && (AM.BaseOffs || AM.Scale > 1))
7802       return false;
7803   }
7804
7805   switch (AM.Scale) {
7806   case 0:
7807   case 1:
7808   case 2:
7809   case 4:
7810   case 8:
7811     // These scales always work.
7812     break;
7813   case 3:
7814   case 5:
7815   case 9:
7816     // These scales are formed with basereg+scalereg.  Only accept if there is
7817     // no basereg yet.
7818     if (AM.HasBaseReg)
7819       return false;
7820     break;
7821   default:  // Other stuff never works.
7822     return false;
7823   }
7824
7825   return true;
7826 }
7827
7828
7829 bool X86TargetLowering::isTruncateFree(const Type *Ty1, const Type *Ty2) const {
7830   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
7831     return false;
7832   unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
7833   unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
7834   if (NumBits1 <= NumBits2)
7835     return false;
7836   return true;
7837 }
7838
7839 bool X86TargetLowering::isTruncateFree(EVT VT1, EVT VT2) const {
7840   if (!VT1.isInteger() || !VT2.isInteger())
7841     return false;
7842   unsigned NumBits1 = VT1.getSizeInBits();
7843   unsigned NumBits2 = VT2.getSizeInBits();
7844   if (NumBits1 <= NumBits2)
7845     return false;
7846   return true;
7847 }
7848
7849 bool X86TargetLowering::isZExtFree(const Type *Ty1, const Type *Ty2) const {
7850   // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
7851   return Ty1->isIntegerTy(32) && Ty2->isIntegerTy(64) && Subtarget->is64Bit();
7852 }
7853
7854 bool X86TargetLowering::isZExtFree(EVT VT1, EVT VT2) const {
7855   // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
7856   return VT1 == MVT::i32 && VT2 == MVT::i64 && Subtarget->is64Bit();
7857 }
7858
7859 bool X86TargetLowering::isNarrowingProfitable(EVT VT1, EVT VT2) const {
7860   // i16 instructions are longer (0x66 prefix) and potentially slower.
7861   return !(VT1 == MVT::i32 && VT2 == MVT::i16);
7862 }
7863
7864 /// isShuffleMaskLegal - Targets can use this to indicate that they only
7865 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
7866 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
7867 /// are assumed to be legal.
7868 bool
7869 X86TargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M,
7870                                       EVT VT) const {
7871   // Only do shuffles on 128-bit vector types for now.
7872   if (VT.getSizeInBits() == 64)
7873     return false;
7874
7875   // FIXME: pshufb, blends, shifts.
7876   return (VT.getVectorNumElements() == 2 ||
7877           ShuffleVectorSDNode::isSplatMask(&M[0], VT) ||
7878           isMOVLMask(M, VT) ||
7879           isSHUFPMask(M, VT) ||
7880           isPSHUFDMask(M, VT) ||
7881           isPSHUFHWMask(M, VT) ||
7882           isPSHUFLWMask(M, VT) ||
7883           isPALIGNRMask(M, VT, Subtarget->hasSSSE3()) ||
7884           isUNPCKLMask(M, VT) ||
7885           isUNPCKHMask(M, VT) ||
7886           isUNPCKL_v_undef_Mask(M, VT) ||
7887           isUNPCKH_v_undef_Mask(M, VT));
7888 }
7889
7890 bool
7891 X86TargetLowering::isVectorClearMaskLegal(const SmallVectorImpl<int> &Mask,
7892                                           EVT VT) const {
7893   unsigned NumElts = VT.getVectorNumElements();
7894   // FIXME: This collection of masks seems suspect.
7895   if (NumElts == 2)
7896     return true;
7897   if (NumElts == 4 && VT.getSizeInBits() == 128) {
7898     return (isMOVLMask(Mask, VT)  ||
7899             isCommutedMOVLMask(Mask, VT, true) ||
7900             isSHUFPMask(Mask, VT) ||
7901             isCommutedSHUFPMask(Mask, VT));
7902   }
7903   return false;
7904 }
7905
7906 //===----------------------------------------------------------------------===//
7907 //                           X86 Scheduler Hooks
7908 //===----------------------------------------------------------------------===//
7909
7910 // private utility function
7911 MachineBasicBlock *
7912 X86TargetLowering::EmitAtomicBitwiseWithCustomInserter(MachineInstr *bInstr,
7913                                                        MachineBasicBlock *MBB,
7914                                                        unsigned regOpc,
7915                                                        unsigned immOpc,
7916                                                        unsigned LoadOpc,
7917                                                        unsigned CXchgOpc,
7918                                                        unsigned copyOpc,
7919                                                        unsigned notOpc,
7920                                                        unsigned EAXreg,
7921                                                        TargetRegisterClass *RC,
7922                                                        bool invSrc) const {
7923   // For the atomic bitwise operator, we generate
7924   //   thisMBB:
7925   //   newMBB:
7926   //     ld  t1 = [bitinstr.addr]
7927   //     op  t2 = t1, [bitinstr.val]
7928   //     mov EAX = t1
7929   //     lcs dest = [bitinstr.addr], t2  [EAX is implicit]
7930   //     bz  newMBB
7931   //     fallthrough -->nextMBB
7932   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
7933   const BasicBlock *LLVM_BB = MBB->getBasicBlock();
7934   MachineFunction::iterator MBBIter = MBB;
7935   ++MBBIter;
7936
7937   /// First build the CFG
7938   MachineFunction *F = MBB->getParent();
7939   MachineBasicBlock *thisMBB = MBB;
7940   MachineBasicBlock *newMBB = F->CreateMachineBasicBlock(LLVM_BB);
7941   MachineBasicBlock *nextMBB = F->CreateMachineBasicBlock(LLVM_BB);
7942   F->insert(MBBIter, newMBB);
7943   F->insert(MBBIter, nextMBB);
7944
7945   // Move all successors to thisMBB to nextMBB
7946   nextMBB->transferSuccessors(thisMBB);
7947
7948   // Update thisMBB to fall through to newMBB
7949   thisMBB->addSuccessor(newMBB);
7950
7951   // newMBB jumps to itself and fall through to nextMBB
7952   newMBB->addSuccessor(nextMBB);
7953   newMBB->addSuccessor(newMBB);
7954
7955   // Insert instructions into newMBB based on incoming instruction
7956   assert(bInstr->getNumOperands() < X86AddrNumOperands + 4 &&
7957          "unexpected number of operands");
7958   DebugLoc dl = bInstr->getDebugLoc();
7959   MachineOperand& destOper = bInstr->getOperand(0);
7960   MachineOperand* argOpers[2 + X86AddrNumOperands];
7961   int numArgs = bInstr->getNumOperands() - 1;
7962   for (int i=0; i < numArgs; ++i)
7963     argOpers[i] = &bInstr->getOperand(i+1);
7964
7965   // x86 address has 4 operands: base, index, scale, and displacement
7966   int lastAddrIndx = X86AddrNumOperands - 1; // [0,3]
7967   int valArgIndx = lastAddrIndx + 1;
7968
7969   unsigned t1 = F->getRegInfo().createVirtualRegister(RC);
7970   MachineInstrBuilder MIB = BuildMI(newMBB, dl, TII->get(LoadOpc), t1);
7971   for (int i=0; i <= lastAddrIndx; ++i)
7972     (*MIB).addOperand(*argOpers[i]);
7973
7974   unsigned tt = F->getRegInfo().createVirtualRegister(RC);
7975   if (invSrc) {
7976     MIB = BuildMI(newMBB, dl, TII->get(notOpc), tt).addReg(t1);
7977   }
7978   else
7979     tt = t1;
7980
7981   unsigned t2 = F->getRegInfo().createVirtualRegister(RC);
7982   assert((argOpers[valArgIndx]->isReg() ||
7983           argOpers[valArgIndx]->isImm()) &&
7984          "invalid operand");
7985   if (argOpers[valArgIndx]->isReg())
7986     MIB = BuildMI(newMBB, dl, TII->get(regOpc), t2);
7987   else
7988     MIB = BuildMI(newMBB, dl, TII->get(immOpc), t2);
7989   MIB.addReg(tt);
7990   (*MIB).addOperand(*argOpers[valArgIndx]);
7991
7992   MIB = BuildMI(newMBB, dl, TII->get(copyOpc), EAXreg);
7993   MIB.addReg(t1);
7994
7995   MIB = BuildMI(newMBB, dl, TII->get(CXchgOpc));
7996   for (int i=0; i <= lastAddrIndx; ++i)
7997     (*MIB).addOperand(*argOpers[i]);
7998   MIB.addReg(t2);
7999   assert(bInstr->hasOneMemOperand() && "Unexpected number of memoperand");
8000   (*MIB).setMemRefs(bInstr->memoperands_begin(),
8001                     bInstr->memoperands_end());
8002
8003   MIB = BuildMI(newMBB, dl, TII->get(copyOpc), destOper.getReg());
8004   MIB.addReg(EAXreg);
8005
8006   // insert branch
8007   BuildMI(newMBB, dl, TII->get(X86::JNE_4)).addMBB(newMBB);
8008
8009   F->DeleteMachineInstr(bInstr);   // The pseudo instruction is gone now.
8010   return nextMBB;
8011 }
8012
8013 // private utility function:  64 bit atomics on 32 bit host.
8014 MachineBasicBlock *
8015 X86TargetLowering::EmitAtomicBit6432WithCustomInserter(MachineInstr *bInstr,
8016                                                        MachineBasicBlock *MBB,
8017                                                        unsigned regOpcL,
8018                                                        unsigned regOpcH,
8019                                                        unsigned immOpcL,
8020                                                        unsigned immOpcH,
8021                                                        bool invSrc) const {
8022   // For the atomic bitwise operator, we generate
8023   //   thisMBB (instructions are in pairs, except cmpxchg8b)
8024   //     ld t1,t2 = [bitinstr.addr]
8025   //   newMBB:
8026   //     out1, out2 = phi (thisMBB, t1/t2) (newMBB, t3/t4)
8027   //     op  t5, t6 <- out1, out2, [bitinstr.val]
8028   //      (for SWAP, substitute:  mov t5, t6 <- [bitinstr.val])
8029   //     mov ECX, EBX <- t5, t6
8030   //     mov EAX, EDX <- t1, t2
8031   //     cmpxchg8b [bitinstr.addr]  [EAX, EDX, EBX, ECX implicit]
8032   //     mov t3, t4 <- EAX, EDX
8033   //     bz  newMBB
8034   //     result in out1, out2
8035   //     fallthrough -->nextMBB
8036
8037   const TargetRegisterClass *RC = X86::GR32RegisterClass;
8038   const unsigned LoadOpc = X86::MOV32rm;
8039   const unsigned copyOpc = X86::MOV32rr;
8040   const unsigned NotOpc = X86::NOT32r;
8041   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
8042   const BasicBlock *LLVM_BB = MBB->getBasicBlock();
8043   MachineFunction::iterator MBBIter = MBB;
8044   ++MBBIter;
8045
8046   /// First build the CFG
8047   MachineFunction *F = MBB->getParent();
8048   MachineBasicBlock *thisMBB = MBB;
8049   MachineBasicBlock *newMBB = F->CreateMachineBasicBlock(LLVM_BB);
8050   MachineBasicBlock *nextMBB = F->CreateMachineBasicBlock(LLVM_BB);
8051   F->insert(MBBIter, newMBB);
8052   F->insert(MBBIter, nextMBB);
8053
8054   // Move all successors to thisMBB to nextMBB
8055   nextMBB->transferSuccessors(thisMBB);
8056
8057   // Update thisMBB to fall through to newMBB
8058   thisMBB->addSuccessor(newMBB);
8059
8060   // newMBB jumps to itself and fall through to nextMBB
8061   newMBB->addSuccessor(nextMBB);
8062   newMBB->addSuccessor(newMBB);
8063
8064   DebugLoc dl = bInstr->getDebugLoc();
8065   // Insert instructions into newMBB based on incoming instruction
8066   // There are 8 "real" operands plus 9 implicit def/uses, ignored here.
8067   assert(bInstr->getNumOperands() < X86AddrNumOperands + 14 &&
8068          "unexpected number of operands");
8069   MachineOperand& dest1Oper = bInstr->getOperand(0);
8070   MachineOperand& dest2Oper = bInstr->getOperand(1);
8071   MachineOperand* argOpers[2 + X86AddrNumOperands];
8072   for (int i=0; i < 2 + X86AddrNumOperands; ++i)
8073     argOpers[i] = &bInstr->getOperand(i+2);
8074
8075   // x86 address has 5 operands: base, index, scale, displacement, and segment.
8076   int lastAddrIndx = X86AddrNumOperands - 1; // [0,3]
8077
8078   unsigned t1 = F->getRegInfo().createVirtualRegister(RC);
8079   MachineInstrBuilder MIB = BuildMI(thisMBB, dl, TII->get(LoadOpc), t1);
8080   for (int i=0; i <= lastAddrIndx; ++i)
8081     (*MIB).addOperand(*argOpers[i]);
8082   unsigned t2 = F->getRegInfo().createVirtualRegister(RC);
8083   MIB = BuildMI(thisMBB, dl, TII->get(LoadOpc), t2);
8084   // add 4 to displacement.
8085   for (int i=0; i <= lastAddrIndx-2; ++i)
8086     (*MIB).addOperand(*argOpers[i]);
8087   MachineOperand newOp3 = *(argOpers[3]);
8088   if (newOp3.isImm())
8089     newOp3.setImm(newOp3.getImm()+4);
8090   else
8091     newOp3.setOffset(newOp3.getOffset()+4);
8092   (*MIB).addOperand(newOp3);
8093   (*MIB).addOperand(*argOpers[lastAddrIndx]);
8094
8095   // t3/4 are defined later, at the bottom of the loop
8096   unsigned t3 = F->getRegInfo().createVirtualRegister(RC);
8097   unsigned t4 = F->getRegInfo().createVirtualRegister(RC);
8098   BuildMI(newMBB, dl, TII->get(X86::PHI), dest1Oper.getReg())
8099     .addReg(t1).addMBB(thisMBB).addReg(t3).addMBB(newMBB);
8100   BuildMI(newMBB, dl, TII->get(X86::PHI), dest2Oper.getReg())
8101     .addReg(t2).addMBB(thisMBB).addReg(t4).addMBB(newMBB);
8102
8103   // The subsequent operations should be using the destination registers of
8104   //the PHI instructions.
8105   if (invSrc) {
8106     t1 = F->getRegInfo().createVirtualRegister(RC);
8107     t2 = F->getRegInfo().createVirtualRegister(RC);
8108     MIB = BuildMI(newMBB, dl, TII->get(NotOpc), t1).addReg(dest1Oper.getReg());
8109     MIB = BuildMI(newMBB, dl, TII->get(NotOpc), t2).addReg(dest2Oper.getReg());
8110   } else {
8111     t1 = dest1Oper.getReg();
8112     t2 = dest2Oper.getReg();
8113   }
8114
8115   int valArgIndx = lastAddrIndx + 1;
8116   assert((argOpers[valArgIndx]->isReg() ||
8117           argOpers[valArgIndx]->isImm()) &&
8118          "invalid operand");
8119   unsigned t5 = F->getRegInfo().createVirtualRegister(RC);
8120   unsigned t6 = F->getRegInfo().createVirtualRegister(RC);
8121   if (argOpers[valArgIndx]->isReg())
8122     MIB = BuildMI(newMBB, dl, TII->get(regOpcL), t5);
8123   else
8124     MIB = BuildMI(newMBB, dl, TII->get(immOpcL), t5);
8125   if (regOpcL != X86::MOV32rr)
8126     MIB.addReg(t1);
8127   (*MIB).addOperand(*argOpers[valArgIndx]);
8128   assert(argOpers[valArgIndx + 1]->isReg() ==
8129          argOpers[valArgIndx]->isReg());
8130   assert(argOpers[valArgIndx + 1]->isImm() ==
8131          argOpers[valArgIndx]->isImm());
8132   if (argOpers[valArgIndx + 1]->isReg())
8133     MIB = BuildMI(newMBB, dl, TII->get(regOpcH), t6);
8134   else
8135     MIB = BuildMI(newMBB, dl, TII->get(immOpcH), t6);
8136   if (regOpcH != X86::MOV32rr)
8137     MIB.addReg(t2);
8138   (*MIB).addOperand(*argOpers[valArgIndx + 1]);
8139
8140   MIB = BuildMI(newMBB, dl, TII->get(copyOpc), X86::EAX);
8141   MIB.addReg(t1);
8142   MIB = BuildMI(newMBB, dl, TII->get(copyOpc), X86::EDX);
8143   MIB.addReg(t2);
8144
8145   MIB = BuildMI(newMBB, dl, TII->get(copyOpc), X86::EBX);
8146   MIB.addReg(t5);
8147   MIB = BuildMI(newMBB, dl, TII->get(copyOpc), X86::ECX);
8148   MIB.addReg(t6);
8149
8150   MIB = BuildMI(newMBB, dl, TII->get(X86::LCMPXCHG8B));
8151   for (int i=0; i <= lastAddrIndx; ++i)
8152     (*MIB).addOperand(*argOpers[i]);
8153
8154   assert(bInstr->hasOneMemOperand() && "Unexpected number of memoperand");
8155   (*MIB).setMemRefs(bInstr->memoperands_begin(),
8156                     bInstr->memoperands_end());
8157
8158   MIB = BuildMI(newMBB, dl, TII->get(copyOpc), t3);
8159   MIB.addReg(X86::EAX);
8160   MIB = BuildMI(newMBB, dl, TII->get(copyOpc), t4);
8161   MIB.addReg(X86::EDX);
8162
8163   // insert branch
8164   BuildMI(newMBB, dl, TII->get(X86::JNE_4)).addMBB(newMBB);
8165
8166   F->DeleteMachineInstr(bInstr);   // The pseudo instruction is gone now.
8167   return nextMBB;
8168 }
8169
8170 // private utility function
8171 MachineBasicBlock *
8172 X86TargetLowering::EmitAtomicMinMaxWithCustomInserter(MachineInstr *mInstr,
8173                                                       MachineBasicBlock *MBB,
8174                                                       unsigned cmovOpc) const {
8175   // For the atomic min/max operator, we generate
8176   //   thisMBB:
8177   //   newMBB:
8178   //     ld t1 = [min/max.addr]
8179   //     mov t2 = [min/max.val]
8180   //     cmp  t1, t2
8181   //     cmov[cond] t2 = t1
8182   //     mov EAX = t1
8183   //     lcs dest = [bitinstr.addr], t2  [EAX is implicit]
8184   //     bz   newMBB
8185   //     fallthrough -->nextMBB
8186   //
8187   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
8188   const BasicBlock *LLVM_BB = MBB->getBasicBlock();
8189   MachineFunction::iterator MBBIter = MBB;
8190   ++MBBIter;
8191
8192   /// First build the CFG
8193   MachineFunction *F = MBB->getParent();
8194   MachineBasicBlock *thisMBB = MBB;
8195   MachineBasicBlock *newMBB = F->CreateMachineBasicBlock(LLVM_BB);
8196   MachineBasicBlock *nextMBB = F->CreateMachineBasicBlock(LLVM_BB);
8197   F->insert(MBBIter, newMBB);
8198   F->insert(MBBIter, nextMBB);
8199
8200   // Move all successors of thisMBB to nextMBB
8201   nextMBB->transferSuccessors(thisMBB);
8202
8203   // Update thisMBB to fall through to newMBB
8204   thisMBB->addSuccessor(newMBB);
8205
8206   // newMBB jumps to newMBB and fall through to nextMBB
8207   newMBB->addSuccessor(nextMBB);
8208   newMBB->addSuccessor(newMBB);
8209
8210   DebugLoc dl = mInstr->getDebugLoc();
8211   // Insert instructions into newMBB based on incoming instruction
8212   assert(mInstr->getNumOperands() < X86AddrNumOperands + 4 &&
8213          "unexpected number of operands");
8214   MachineOperand& destOper = mInstr->getOperand(0);
8215   MachineOperand* argOpers[2 + X86AddrNumOperands];
8216   int numArgs = mInstr->getNumOperands() - 1;
8217   for (int i=0; i < numArgs; ++i)
8218     argOpers[i] = &mInstr->getOperand(i+1);
8219
8220   // x86 address has 4 operands: base, index, scale, and displacement
8221   int lastAddrIndx = X86AddrNumOperands - 1; // [0,3]
8222   int valArgIndx = lastAddrIndx + 1;
8223
8224   unsigned t1 = F->getRegInfo().createVirtualRegister(X86::GR32RegisterClass);
8225   MachineInstrBuilder MIB = BuildMI(newMBB, dl, TII->get(X86::MOV32rm), t1);
8226   for (int i=0; i <= lastAddrIndx; ++i)
8227     (*MIB).addOperand(*argOpers[i]);
8228
8229   // We only support register and immediate values
8230   assert((argOpers[valArgIndx]->isReg() ||
8231           argOpers[valArgIndx]->isImm()) &&
8232          "invalid operand");
8233
8234   unsigned t2 = F->getRegInfo().createVirtualRegister(X86::GR32RegisterClass);
8235   if (argOpers[valArgIndx]->isReg())
8236     MIB = BuildMI(newMBB, dl, TII->get(X86::MOV32rr), t2);
8237   else
8238     MIB = BuildMI(newMBB, dl, TII->get(X86::MOV32rr), t2);
8239   (*MIB).addOperand(*argOpers[valArgIndx]);
8240
8241   MIB = BuildMI(newMBB, dl, TII->get(X86::MOV32rr), X86::EAX);
8242   MIB.addReg(t1);
8243
8244   MIB = BuildMI(newMBB, dl, TII->get(X86::CMP32rr));
8245   MIB.addReg(t1);
8246   MIB.addReg(t2);
8247
8248   // Generate movc
8249   unsigned t3 = F->getRegInfo().createVirtualRegister(X86::GR32RegisterClass);
8250   MIB = BuildMI(newMBB, dl, TII->get(cmovOpc),t3);
8251   MIB.addReg(t2);
8252   MIB.addReg(t1);
8253
8254   // Cmp and exchange if none has modified the memory location
8255   MIB = BuildMI(newMBB, dl, TII->get(X86::LCMPXCHG32));
8256   for (int i=0; i <= lastAddrIndx; ++i)
8257     (*MIB).addOperand(*argOpers[i]);
8258   MIB.addReg(t3);
8259   assert(mInstr->hasOneMemOperand() && "Unexpected number of memoperand");
8260   (*MIB).setMemRefs(mInstr->memoperands_begin(),
8261                     mInstr->memoperands_end());
8262
8263   MIB = BuildMI(newMBB, dl, TII->get(X86::MOV32rr), destOper.getReg());
8264   MIB.addReg(X86::EAX);
8265
8266   // insert branch
8267   BuildMI(newMBB, dl, TII->get(X86::JNE_4)).addMBB(newMBB);
8268
8269   F->DeleteMachineInstr(mInstr);   // The pseudo instruction is gone now.
8270   return nextMBB;
8271 }
8272
8273 // FIXME: When we get size specific XMM0 registers, i.e. XMM0_V16I8
8274 // all of this code can be replaced with that in the .td file.
8275 MachineBasicBlock *
8276 X86TargetLowering::EmitPCMP(MachineInstr *MI, MachineBasicBlock *BB,
8277                             unsigned numArgs, bool memArg) const {
8278
8279   MachineFunction *F = BB->getParent();
8280   DebugLoc dl = MI->getDebugLoc();
8281   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
8282
8283   unsigned Opc;
8284   if (memArg)
8285     Opc = numArgs == 3 ? X86::PCMPISTRM128rm : X86::PCMPESTRM128rm;
8286   else
8287     Opc = numArgs == 3 ? X86::PCMPISTRM128rr : X86::PCMPESTRM128rr;
8288
8289   MachineInstrBuilder MIB = BuildMI(BB, dl, TII->get(Opc));
8290
8291   for (unsigned i = 0; i < numArgs; ++i) {
8292     MachineOperand &Op = MI->getOperand(i+1);
8293
8294     if (!(Op.isReg() && Op.isImplicit()))
8295       MIB.addOperand(Op);
8296   }
8297
8298   BuildMI(BB, dl, TII->get(X86::MOVAPSrr), MI->getOperand(0).getReg())
8299     .addReg(X86::XMM0);
8300
8301   F->DeleteMachineInstr(MI);
8302
8303   return BB;
8304 }
8305
8306 MachineBasicBlock *
8307 X86TargetLowering::EmitVAStartSaveXMMRegsWithCustomInserter(
8308                                                  MachineInstr *MI,
8309                                                  MachineBasicBlock *MBB) const {
8310   // Emit code to save XMM registers to the stack. The ABI says that the
8311   // number of registers to save is given in %al, so it's theoretically
8312   // possible to do an indirect jump trick to avoid saving all of them,
8313   // however this code takes a simpler approach and just executes all
8314   // of the stores if %al is non-zero. It's less code, and it's probably
8315   // easier on the hardware branch predictor, and stores aren't all that
8316   // expensive anyway.
8317
8318   // Create the new basic blocks. One block contains all the XMM stores,
8319   // and one block is the final destination regardless of whether any
8320   // stores were performed.
8321   const BasicBlock *LLVM_BB = MBB->getBasicBlock();
8322   MachineFunction *F = MBB->getParent();
8323   MachineFunction::iterator MBBIter = MBB;
8324   ++MBBIter;
8325   MachineBasicBlock *XMMSaveMBB = F->CreateMachineBasicBlock(LLVM_BB);
8326   MachineBasicBlock *EndMBB = F->CreateMachineBasicBlock(LLVM_BB);
8327   F->insert(MBBIter, XMMSaveMBB);
8328   F->insert(MBBIter, EndMBB);
8329
8330   // Set up the CFG.
8331   // Move any original successors of MBB to the end block.
8332   EndMBB->transferSuccessors(MBB);
8333   // The original block will now fall through to the XMM save block.
8334   MBB->addSuccessor(XMMSaveMBB);
8335   // The XMMSaveMBB will fall through to the end block.
8336   XMMSaveMBB->addSuccessor(EndMBB);
8337
8338   // Now add the instructions.
8339   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
8340   DebugLoc DL = MI->getDebugLoc();
8341
8342   unsigned CountReg = MI->getOperand(0).getReg();
8343   int64_t RegSaveFrameIndex = MI->getOperand(1).getImm();
8344   int64_t VarArgsFPOffset = MI->getOperand(2).getImm();
8345
8346   if (!Subtarget->isTargetWin64()) {
8347     // If %al is 0, branch around the XMM save block.
8348     BuildMI(MBB, DL, TII->get(X86::TEST8rr)).addReg(CountReg).addReg(CountReg);
8349     BuildMI(MBB, DL, TII->get(X86::JE_4)).addMBB(EndMBB);
8350     MBB->addSuccessor(EndMBB);
8351   }
8352
8353   // In the XMM save block, save all the XMM argument registers.
8354   for (int i = 3, e = MI->getNumOperands(); i != e; ++i) {
8355     int64_t Offset = (i - 3) * 16 + VarArgsFPOffset;
8356     MachineMemOperand *MMO =
8357       F->getMachineMemOperand(
8358         PseudoSourceValue::getFixedStack(RegSaveFrameIndex),
8359         MachineMemOperand::MOStore, Offset,
8360         /*Size=*/16, /*Align=*/16);
8361     BuildMI(XMMSaveMBB, DL, TII->get(X86::MOVAPSmr))
8362       .addFrameIndex(RegSaveFrameIndex)
8363       .addImm(/*Scale=*/1)
8364       .addReg(/*IndexReg=*/0)
8365       .addImm(/*Disp=*/Offset)
8366       .addReg(/*Segment=*/0)
8367       .addReg(MI->getOperand(i).getReg())
8368       .addMemOperand(MMO);
8369   }
8370
8371   F->DeleteMachineInstr(MI);   // The pseudo instruction is gone now.
8372
8373   return EndMBB;
8374 }
8375
8376 MachineBasicBlock *
8377 X86TargetLowering::EmitLoweredSelect(MachineInstr *MI,
8378                                      MachineBasicBlock *BB,
8379                    DenseMap<MachineBasicBlock*, MachineBasicBlock*> *EM) const {
8380   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
8381   DebugLoc DL = MI->getDebugLoc();
8382
8383   // To "insert" a SELECT_CC instruction, we actually have to insert the
8384   // diamond control-flow pattern.  The incoming instruction knows the
8385   // destination vreg to set, the condition code register to branch on, the
8386   // true/false values to select between, and a branch opcode to use.
8387   const BasicBlock *LLVM_BB = BB->getBasicBlock();
8388   MachineFunction::iterator It = BB;
8389   ++It;
8390
8391   //  thisMBB:
8392   //  ...
8393   //   TrueVal = ...
8394   //   cmpTY ccX, r1, r2
8395   //   bCC copy1MBB
8396   //   fallthrough --> copy0MBB
8397   MachineBasicBlock *thisMBB = BB;
8398   MachineFunction *F = BB->getParent();
8399   MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
8400   MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
8401   unsigned Opc =
8402     X86::GetCondBranchFromCond((X86::CondCode)MI->getOperand(3).getImm());
8403   BuildMI(BB, DL, TII->get(Opc)).addMBB(sinkMBB);
8404   F->insert(It, copy0MBB);
8405   F->insert(It, sinkMBB);
8406   // Update machine-CFG edges by first adding all successors of the current
8407   // block to the new block which will contain the Phi node for the select.
8408   // Also inform sdisel of the edge changes.
8409   for (MachineBasicBlock::succ_iterator I = BB->succ_begin(),
8410          E = BB->succ_end(); I != E; ++I) {
8411     EM->insert(std::make_pair(*I, sinkMBB));
8412     sinkMBB->addSuccessor(*I);
8413   }
8414   // Next, remove all successors of the current block, and add the true
8415   // and fallthrough blocks as its successors.
8416   while (!BB->succ_empty())
8417     BB->removeSuccessor(BB->succ_begin());
8418   // Add the true and fallthrough blocks as its successors.
8419   BB->addSuccessor(copy0MBB);
8420   BB->addSuccessor(sinkMBB);
8421
8422   //  copy0MBB:
8423   //   %FalseValue = ...
8424   //   # fallthrough to sinkMBB
8425   BB = copy0MBB;
8426
8427   // Update machine-CFG edges
8428   BB->addSuccessor(sinkMBB);
8429
8430   //  sinkMBB:
8431   //   %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
8432   //  ...
8433   BB = sinkMBB;
8434   BuildMI(BB, DL, TII->get(X86::PHI), MI->getOperand(0).getReg())
8435     .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB)
8436     .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
8437
8438   F->DeleteMachineInstr(MI);   // The pseudo instruction is gone now.
8439   return BB;
8440 }
8441
8442 MachineBasicBlock *
8443 X86TargetLowering::EmitLoweredMingwAlloca(MachineInstr *MI,
8444                                           MachineBasicBlock *BB,
8445                    DenseMap<MachineBasicBlock*, MachineBasicBlock*> *EM) const {
8446   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
8447   DebugLoc DL = MI->getDebugLoc();
8448   MachineFunction *F = BB->getParent();
8449
8450   // The lowering is pretty easy: we're just emitting the call to _alloca.  The
8451   // non-trivial part is impdef of ESP.
8452   // FIXME: The code should be tweaked as soon as we'll try to do codegen for
8453   // mingw-w64.
8454
8455   BuildMI(BB, DL, TII->get(X86::CALLpcrel32))
8456     .addExternalSymbol("_alloca")
8457     .addReg(X86::EAX, RegState::Implicit)
8458     .addReg(X86::ESP, RegState::Implicit)
8459     .addReg(X86::EAX, RegState::Define | RegState::Implicit)
8460     .addReg(X86::ESP, RegState::Define | RegState::Implicit);
8461
8462   F->DeleteMachineInstr(MI);   // The pseudo instruction is gone now.
8463   return BB;
8464 }
8465
8466 MachineBasicBlock *
8467 X86TargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
8468                                                MachineBasicBlock *BB,
8469                    DenseMap<MachineBasicBlock*, MachineBasicBlock*> *EM) const {
8470   switch (MI->getOpcode()) {
8471   default: assert(false && "Unexpected instr type to insert");
8472   case X86::MINGW_ALLOCA:
8473     return EmitLoweredMingwAlloca(MI, BB, EM);
8474   case X86::CMOV_GR8:
8475   case X86::CMOV_V1I64:
8476   case X86::CMOV_FR32:
8477   case X86::CMOV_FR64:
8478   case X86::CMOV_V4F32:
8479   case X86::CMOV_V2F64:
8480   case X86::CMOV_V2I64:
8481   case X86::CMOV_GR16:
8482   case X86::CMOV_GR32:
8483   case X86::CMOV_RFP32:
8484   case X86::CMOV_RFP64:
8485   case X86::CMOV_RFP80:
8486     return EmitLoweredSelect(MI, BB, EM);
8487
8488   case X86::FP32_TO_INT16_IN_MEM:
8489   case X86::FP32_TO_INT32_IN_MEM:
8490   case X86::FP32_TO_INT64_IN_MEM:
8491   case X86::FP64_TO_INT16_IN_MEM:
8492   case X86::FP64_TO_INT32_IN_MEM:
8493   case X86::FP64_TO_INT64_IN_MEM:
8494   case X86::FP80_TO_INT16_IN_MEM:
8495   case X86::FP80_TO_INT32_IN_MEM:
8496   case X86::FP80_TO_INT64_IN_MEM: {
8497     const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
8498     DebugLoc DL = MI->getDebugLoc();
8499
8500     // Change the floating point control register to use "round towards zero"
8501     // mode when truncating to an integer value.
8502     MachineFunction *F = BB->getParent();
8503     int CWFrameIdx = F->getFrameInfo()->CreateStackObject(2, 2, false);
8504     addFrameReference(BuildMI(BB, DL, TII->get(X86::FNSTCW16m)), CWFrameIdx);
8505
8506     // Load the old value of the high byte of the control word...
8507     unsigned OldCW =
8508       F->getRegInfo().createVirtualRegister(X86::GR16RegisterClass);
8509     addFrameReference(BuildMI(BB, DL, TII->get(X86::MOV16rm), OldCW),
8510                       CWFrameIdx);
8511
8512     // Set the high part to be round to zero...
8513     addFrameReference(BuildMI(BB, DL, TII->get(X86::MOV16mi)), CWFrameIdx)
8514       .addImm(0xC7F);
8515
8516     // Reload the modified control word now...
8517     addFrameReference(BuildMI(BB, DL, TII->get(X86::FLDCW16m)), CWFrameIdx);
8518
8519     // Restore the memory image of control word to original value
8520     addFrameReference(BuildMI(BB, DL, TII->get(X86::MOV16mr)), CWFrameIdx)
8521       .addReg(OldCW);
8522
8523     // Get the X86 opcode to use.
8524     unsigned Opc;
8525     switch (MI->getOpcode()) {
8526     default: llvm_unreachable("illegal opcode!");
8527     case X86::FP32_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m32; break;
8528     case X86::FP32_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m32; break;
8529     case X86::FP32_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m32; break;
8530     case X86::FP64_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m64; break;
8531     case X86::FP64_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m64; break;
8532     case X86::FP64_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m64; break;
8533     case X86::FP80_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m80; break;
8534     case X86::FP80_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m80; break;
8535     case X86::FP80_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m80; break;
8536     }
8537
8538     X86AddressMode AM;
8539     MachineOperand &Op = MI->getOperand(0);
8540     if (Op.isReg()) {
8541       AM.BaseType = X86AddressMode::RegBase;
8542       AM.Base.Reg = Op.getReg();
8543     } else {
8544       AM.BaseType = X86AddressMode::FrameIndexBase;
8545       AM.Base.FrameIndex = Op.getIndex();
8546     }
8547     Op = MI->getOperand(1);
8548     if (Op.isImm())
8549       AM.Scale = Op.getImm();
8550     Op = MI->getOperand(2);
8551     if (Op.isImm())
8552       AM.IndexReg = Op.getImm();
8553     Op = MI->getOperand(3);
8554     if (Op.isGlobal()) {
8555       AM.GV = Op.getGlobal();
8556     } else {
8557       AM.Disp = Op.getImm();
8558     }
8559     addFullAddress(BuildMI(BB, DL, TII->get(Opc)), AM)
8560                       .addReg(MI->getOperand(X86AddrNumOperands).getReg());
8561
8562     // Reload the original control word now.
8563     addFrameReference(BuildMI(BB, DL, TII->get(X86::FLDCW16m)), CWFrameIdx);
8564
8565     F->DeleteMachineInstr(MI);   // The pseudo instruction is gone now.
8566     return BB;
8567   }
8568     // DBG_VALUE.  Only the frame index case is done here.
8569   case X86::DBG_VALUE: {
8570     const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
8571     DebugLoc DL = MI->getDebugLoc();
8572     X86AddressMode AM;
8573     MachineFunction *F = BB->getParent();
8574     AM.BaseType = X86AddressMode::FrameIndexBase;
8575     AM.Base.FrameIndex = MI->getOperand(0).getImm();
8576     addFullAddress(BuildMI(BB, DL, TII->get(X86::DBG_VALUE)), AM).
8577       addImm(MI->getOperand(1).getImm()).
8578       addMetadata(MI->getOperand(2).getMetadata());
8579     F->DeleteMachineInstr(MI);      // Remove pseudo.
8580     return BB;
8581   }
8582
8583     // String/text processing lowering.
8584   case X86::PCMPISTRM128REG:
8585     return EmitPCMP(MI, BB, 3, false /* in-mem */);
8586   case X86::PCMPISTRM128MEM:
8587     return EmitPCMP(MI, BB, 3, true /* in-mem */);
8588   case X86::PCMPESTRM128REG:
8589     return EmitPCMP(MI, BB, 5, false /* in mem */);
8590   case X86::PCMPESTRM128MEM:
8591     return EmitPCMP(MI, BB, 5, true /* in mem */);
8592
8593     // Atomic Lowering.
8594   case X86::ATOMAND32:
8595     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND32rr,
8596                                                X86::AND32ri, X86::MOV32rm,
8597                                                X86::LCMPXCHG32, X86::MOV32rr,
8598                                                X86::NOT32r, X86::EAX,
8599                                                X86::GR32RegisterClass);
8600   case X86::ATOMOR32:
8601     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR32rr,
8602                                                X86::OR32ri, X86::MOV32rm,
8603                                                X86::LCMPXCHG32, X86::MOV32rr,
8604                                                X86::NOT32r, X86::EAX,
8605                                                X86::GR32RegisterClass);
8606   case X86::ATOMXOR32:
8607     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR32rr,
8608                                                X86::XOR32ri, X86::MOV32rm,
8609                                                X86::LCMPXCHG32, X86::MOV32rr,
8610                                                X86::NOT32r, X86::EAX,
8611                                                X86::GR32RegisterClass);
8612   case X86::ATOMNAND32:
8613     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND32rr,
8614                                                X86::AND32ri, X86::MOV32rm,
8615                                                X86::LCMPXCHG32, X86::MOV32rr,
8616                                                X86::NOT32r, X86::EAX,
8617                                                X86::GR32RegisterClass, true);
8618   case X86::ATOMMIN32:
8619     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVL32rr);
8620   case X86::ATOMMAX32:
8621     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVG32rr);
8622   case X86::ATOMUMIN32:
8623     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVB32rr);
8624   case X86::ATOMUMAX32:
8625     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVA32rr);
8626
8627   case X86::ATOMAND16:
8628     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND16rr,
8629                                                X86::AND16ri, X86::MOV16rm,
8630                                                X86::LCMPXCHG16, X86::MOV16rr,
8631                                                X86::NOT16r, X86::AX,
8632                                                X86::GR16RegisterClass);
8633   case X86::ATOMOR16:
8634     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR16rr,
8635                                                X86::OR16ri, X86::MOV16rm,
8636                                                X86::LCMPXCHG16, X86::MOV16rr,
8637                                                X86::NOT16r, X86::AX,
8638                                                X86::GR16RegisterClass);
8639   case X86::ATOMXOR16:
8640     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR16rr,
8641                                                X86::XOR16ri, X86::MOV16rm,
8642                                                X86::LCMPXCHG16, X86::MOV16rr,
8643                                                X86::NOT16r, X86::AX,
8644                                                X86::GR16RegisterClass);
8645   case X86::ATOMNAND16:
8646     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND16rr,
8647                                                X86::AND16ri, X86::MOV16rm,
8648                                                X86::LCMPXCHG16, X86::MOV16rr,
8649                                                X86::NOT16r, X86::AX,
8650                                                X86::GR16RegisterClass, true);
8651   case X86::ATOMMIN16:
8652     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVL16rr);
8653   case X86::ATOMMAX16:
8654     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVG16rr);
8655   case X86::ATOMUMIN16:
8656     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVB16rr);
8657   case X86::ATOMUMAX16:
8658     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVA16rr);
8659
8660   case X86::ATOMAND8:
8661     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND8rr,
8662                                                X86::AND8ri, X86::MOV8rm,
8663                                                X86::LCMPXCHG8, X86::MOV8rr,
8664                                                X86::NOT8r, X86::AL,
8665                                                X86::GR8RegisterClass);
8666   case X86::ATOMOR8:
8667     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR8rr,
8668                                                X86::OR8ri, X86::MOV8rm,
8669                                                X86::LCMPXCHG8, X86::MOV8rr,
8670                                                X86::NOT8r, X86::AL,
8671                                                X86::GR8RegisterClass);
8672   case X86::ATOMXOR8:
8673     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR8rr,
8674                                                X86::XOR8ri, X86::MOV8rm,
8675                                                X86::LCMPXCHG8, X86::MOV8rr,
8676                                                X86::NOT8r, X86::AL,
8677                                                X86::GR8RegisterClass);
8678   case X86::ATOMNAND8:
8679     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND8rr,
8680                                                X86::AND8ri, X86::MOV8rm,
8681                                                X86::LCMPXCHG8, X86::MOV8rr,
8682                                                X86::NOT8r, X86::AL,
8683                                                X86::GR8RegisterClass, true);
8684   // FIXME: There are no CMOV8 instructions; MIN/MAX need some other way.
8685   // This group is for 64-bit host.
8686   case X86::ATOMAND64:
8687     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND64rr,
8688                                                X86::AND64ri32, X86::MOV64rm,
8689                                                X86::LCMPXCHG64, X86::MOV64rr,
8690                                                X86::NOT64r, X86::RAX,
8691                                                X86::GR64RegisterClass);
8692   case X86::ATOMOR64:
8693     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR64rr,
8694                                                X86::OR64ri32, X86::MOV64rm,
8695                                                X86::LCMPXCHG64, X86::MOV64rr,
8696                                                X86::NOT64r, X86::RAX,
8697                                                X86::GR64RegisterClass);
8698   case X86::ATOMXOR64:
8699     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR64rr,
8700                                                X86::XOR64ri32, X86::MOV64rm,
8701                                                X86::LCMPXCHG64, X86::MOV64rr,
8702                                                X86::NOT64r, X86::RAX,
8703                                                X86::GR64RegisterClass);
8704   case X86::ATOMNAND64:
8705     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND64rr,
8706                                                X86::AND64ri32, X86::MOV64rm,
8707                                                X86::LCMPXCHG64, X86::MOV64rr,
8708                                                X86::NOT64r, X86::RAX,
8709                                                X86::GR64RegisterClass, true);
8710   case X86::ATOMMIN64:
8711     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVL64rr);
8712   case X86::ATOMMAX64:
8713     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVG64rr);
8714   case X86::ATOMUMIN64:
8715     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVB64rr);
8716   case X86::ATOMUMAX64:
8717     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVA64rr);
8718
8719   // This group does 64-bit operations on a 32-bit host.
8720   case X86::ATOMAND6432:
8721     return EmitAtomicBit6432WithCustomInserter(MI, BB,
8722                                                X86::AND32rr, X86::AND32rr,
8723                                                X86::AND32ri, X86::AND32ri,
8724                                                false);
8725   case X86::ATOMOR6432:
8726     return EmitAtomicBit6432WithCustomInserter(MI, BB,
8727                                                X86::OR32rr, X86::OR32rr,
8728                                                X86::OR32ri, X86::OR32ri,
8729                                                false);
8730   case X86::ATOMXOR6432:
8731     return EmitAtomicBit6432WithCustomInserter(MI, BB,
8732                                                X86::XOR32rr, X86::XOR32rr,
8733                                                X86::XOR32ri, X86::XOR32ri,
8734                                                false);
8735   case X86::ATOMNAND6432:
8736     return EmitAtomicBit6432WithCustomInserter(MI, BB,
8737                                                X86::AND32rr, X86::AND32rr,
8738                                                X86::AND32ri, X86::AND32ri,
8739                                                true);
8740   case X86::ATOMADD6432:
8741     return EmitAtomicBit6432WithCustomInserter(MI, BB,
8742                                                X86::ADD32rr, X86::ADC32rr,
8743                                                X86::ADD32ri, X86::ADC32ri,
8744                                                false);
8745   case X86::ATOMSUB6432:
8746     return EmitAtomicBit6432WithCustomInserter(MI, BB,
8747                                                X86::SUB32rr, X86::SBB32rr,
8748                                                X86::SUB32ri, X86::SBB32ri,
8749                                                false);
8750   case X86::ATOMSWAP6432:
8751     return EmitAtomicBit6432WithCustomInserter(MI, BB,
8752                                                X86::MOV32rr, X86::MOV32rr,
8753                                                X86::MOV32ri, X86::MOV32ri,
8754                                                false);
8755   case X86::VASTART_SAVE_XMM_REGS:
8756     return EmitVAStartSaveXMMRegsWithCustomInserter(MI, BB);
8757   }
8758 }
8759
8760 //===----------------------------------------------------------------------===//
8761 //                           X86 Optimization Hooks
8762 //===----------------------------------------------------------------------===//
8763
8764 void X86TargetLowering::computeMaskedBitsForTargetNode(const SDValue Op,
8765                                                        const APInt &Mask,
8766                                                        APInt &KnownZero,
8767                                                        APInt &KnownOne,
8768                                                        const SelectionDAG &DAG,
8769                                                        unsigned Depth) const {
8770   unsigned Opc = Op.getOpcode();
8771   assert((Opc >= ISD::BUILTIN_OP_END ||
8772           Opc == ISD::INTRINSIC_WO_CHAIN ||
8773           Opc == ISD::INTRINSIC_W_CHAIN ||
8774           Opc == ISD::INTRINSIC_VOID) &&
8775          "Should use MaskedValueIsZero if you don't know whether Op"
8776          " is a target node!");
8777
8778   KnownZero = KnownOne = APInt(Mask.getBitWidth(), 0);   // Don't know anything.
8779   switch (Opc) {
8780   default: break;
8781   case X86ISD::ADD:
8782   case X86ISD::SUB:
8783   case X86ISD::SMUL:
8784   case X86ISD::UMUL:
8785   case X86ISD::INC:
8786   case X86ISD::DEC:
8787   case X86ISD::OR:
8788   case X86ISD::XOR:
8789   case X86ISD::AND:
8790     // These nodes' second result is a boolean.
8791     if (Op.getResNo() == 0)
8792       break;
8793     // Fallthrough
8794   case X86ISD::SETCC:
8795     KnownZero |= APInt::getHighBitsSet(Mask.getBitWidth(),
8796                                        Mask.getBitWidth() - 1);
8797     break;
8798   }
8799 }
8800
8801 /// isGAPlusOffset - Returns true (and the GlobalValue and the offset) if the
8802 /// node is a GlobalAddress + offset.
8803 bool X86TargetLowering::isGAPlusOffset(SDNode *N,
8804                                        GlobalValue* &GA, int64_t &Offset) const{
8805   if (N->getOpcode() == X86ISD::Wrapper) {
8806     if (isa<GlobalAddressSDNode>(N->getOperand(0))) {
8807       GA = cast<GlobalAddressSDNode>(N->getOperand(0))->getGlobal();
8808       Offset = cast<GlobalAddressSDNode>(N->getOperand(0))->getOffset();
8809       return true;
8810     }
8811   }
8812   return TargetLowering::isGAPlusOffset(N, GA, Offset);
8813 }
8814
8815 static bool EltsFromConsecutiveLoads(ShuffleVectorSDNode *N, unsigned NumElems,
8816                                      EVT EltVT, LoadSDNode *&LDBase,
8817                                      unsigned &LastLoadedElt,
8818                                      SelectionDAG &DAG, MachineFrameInfo *MFI,
8819                                      const TargetLowering &TLI) {
8820   LDBase = NULL;
8821   LastLoadedElt = -1U;
8822   for (unsigned i = 0; i < NumElems; ++i) {
8823     if (N->getMaskElt(i) < 0) {
8824       if (!LDBase)
8825         return false;
8826       continue;
8827     }
8828
8829     SDValue Elt = DAG.getShuffleScalarElt(N, i);
8830     if (!Elt.getNode() ||
8831         (Elt.getOpcode() != ISD::UNDEF && !ISD::isNON_EXTLoad(Elt.getNode())))
8832       return false;
8833     if (!LDBase) {
8834       if (Elt.getNode()->getOpcode() == ISD::UNDEF)
8835         return false;
8836       LDBase = cast<LoadSDNode>(Elt.getNode());
8837       LastLoadedElt = i;
8838       continue;
8839     }
8840     if (Elt.getOpcode() == ISD::UNDEF)
8841       continue;
8842
8843     LoadSDNode *LD = cast<LoadSDNode>(Elt);
8844     if (!DAG.isConsecutiveLoad(LD, LDBase, EltVT.getSizeInBits()/8, i))
8845       return false;
8846     LastLoadedElt = i;
8847   }
8848   return true;
8849 }
8850
8851 /// PerformShuffleCombine - Combine a vector_shuffle that is equal to
8852 /// build_vector load1, load2, load3, load4, <0, 1, 2, 3> into a 128-bit load
8853 /// if the load addresses are consecutive, non-overlapping, and in the right
8854 /// order.  In the case of v2i64, it will see if it can rewrite the
8855 /// shuffle to be an appropriate build vector so it can take advantage of
8856 // performBuildVectorCombine.
8857 static SDValue PerformShuffleCombine(SDNode *N, SelectionDAG &DAG,
8858                                      const TargetLowering &TLI) {
8859   DebugLoc dl = N->getDebugLoc();
8860   EVT VT = N->getValueType(0);
8861   EVT EltVT = VT.getVectorElementType();
8862   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
8863   unsigned NumElems = VT.getVectorNumElements();
8864
8865   if (VT.getSizeInBits() != 128)
8866     return SDValue();
8867
8868   // Try to combine a vector_shuffle into a 128-bit load.
8869   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
8870   LoadSDNode *LD = NULL;
8871   unsigned LastLoadedElt;
8872   if (!EltsFromConsecutiveLoads(SVN, NumElems, EltVT, LD, LastLoadedElt, DAG,
8873                                 MFI, TLI))
8874     return SDValue();
8875
8876   if (LastLoadedElt == NumElems - 1) {
8877     if (DAG.InferPtrAlignment(LD->getBasePtr()) >= 16)
8878       return DAG.getLoad(VT, dl, LD->getChain(), LD->getBasePtr(),
8879                          LD->getSrcValue(), LD->getSrcValueOffset(),
8880                          LD->isVolatile(), LD->isNonTemporal(), 0);
8881     return DAG.getLoad(VT, dl, LD->getChain(), LD->getBasePtr(),
8882                        LD->getSrcValue(), LD->getSrcValueOffset(),
8883                        LD->isVolatile(), LD->isNonTemporal(),
8884                        LD->getAlignment());
8885   } else if (NumElems == 4 && LastLoadedElt == 1) {
8886     SDVTList Tys = DAG.getVTList(MVT::v2i64, MVT::Other);
8887     SDValue Ops[] = { LD->getChain(), LD->getBasePtr() };
8888     SDValue ResNode = DAG.getNode(X86ISD::VZEXT_LOAD, dl, Tys, Ops, 2);
8889     return DAG.getNode(ISD::BIT_CONVERT, dl, VT, ResNode);
8890   }
8891   return SDValue();
8892 }
8893
8894 /// PerformSELECTCombine - Do target-specific dag combines on SELECT nodes.
8895 static SDValue PerformSELECTCombine(SDNode *N, SelectionDAG &DAG,
8896                                     const X86Subtarget *Subtarget) {
8897   DebugLoc DL = N->getDebugLoc();
8898   SDValue Cond = N->getOperand(0);
8899   // Get the LHS/RHS of the select.
8900   SDValue LHS = N->getOperand(1);
8901   SDValue RHS = N->getOperand(2);
8902
8903   // If we have SSE[12] support, try to form min/max nodes. SSE min/max
8904   // instructions match the semantics of the common C idiom x<y?x:y but not
8905   // x<=y?x:y, because of how they handle negative zero (which can be
8906   // ignored in unsafe-math mode).
8907   if (Subtarget->hasSSE2() &&
8908       (LHS.getValueType() == MVT::f32 || LHS.getValueType() == MVT::f64) &&
8909       Cond.getOpcode() == ISD::SETCC) {
8910     ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
8911
8912     unsigned Opcode = 0;
8913     // Check for x CC y ? x : y.
8914     if (DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
8915         DAG.isEqualTo(RHS, Cond.getOperand(1))) {
8916       switch (CC) {
8917       default: break;
8918       case ISD::SETULT:
8919         // Converting this to a min would handle NaNs incorrectly, and swapping
8920         // the operands would cause it to handle comparisons between positive
8921         // and negative zero incorrectly.
8922         if (!FiniteOnlyFPMath() &&
8923             (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))) {
8924           if (!UnsafeFPMath &&
8925               !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
8926             break;
8927           std::swap(LHS, RHS);
8928         }
8929         Opcode = X86ISD::FMIN;
8930         break;
8931       case ISD::SETOLE:
8932         // Converting this to a min would handle comparisons between positive
8933         // and negative zero incorrectly.
8934         if (!UnsafeFPMath &&
8935             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
8936           break;
8937         Opcode = X86ISD::FMIN;
8938         break;
8939       case ISD::SETULE:
8940         // Converting this to a min would handle both negative zeros and NaNs
8941         // incorrectly, but we can swap the operands to fix both.
8942         std::swap(LHS, RHS);
8943       case ISD::SETOLT:
8944       case ISD::SETLT:
8945       case ISD::SETLE:
8946         Opcode = X86ISD::FMIN;
8947         break;
8948
8949       case ISD::SETOGE:
8950         // Converting this to a max would handle comparisons between positive
8951         // and negative zero incorrectly.
8952         if (!UnsafeFPMath &&
8953             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(LHS))
8954           break;
8955         Opcode = X86ISD::FMAX;
8956         break;
8957       case ISD::SETUGT:
8958         // Converting this to a max would handle NaNs incorrectly, and swapping
8959         // the operands would cause it to handle comparisons between positive
8960         // and negative zero incorrectly.
8961         if (!FiniteOnlyFPMath() &&
8962             (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))) {
8963           if (!UnsafeFPMath &&
8964               !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
8965             break;
8966           std::swap(LHS, RHS);
8967         }
8968         Opcode = X86ISD::FMAX;
8969         break;
8970       case ISD::SETUGE:
8971         // Converting this to a max would handle both negative zeros and NaNs
8972         // incorrectly, but we can swap the operands to fix both.
8973         std::swap(LHS, RHS);
8974       case ISD::SETOGT:
8975       case ISD::SETGT:
8976       case ISD::SETGE:
8977         Opcode = X86ISD::FMAX;
8978         break;
8979       }
8980     // Check for x CC y ? y : x -- a min/max with reversed arms.
8981     } else if (DAG.isEqualTo(LHS, Cond.getOperand(1)) &&
8982                DAG.isEqualTo(RHS, Cond.getOperand(0))) {
8983       switch (CC) {
8984       default: break;
8985       case ISD::SETOGE:
8986         // Converting this to a min would handle comparisons between positive
8987         // and negative zero incorrectly, and swapping the operands would
8988         // cause it to handle NaNs incorrectly.
8989         if (!UnsafeFPMath &&
8990             !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS))) {
8991           if (!FiniteOnlyFPMath() &&
8992               (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)))
8993             break;
8994           std::swap(LHS, RHS);
8995         }
8996         Opcode = X86ISD::FMIN;
8997         break;
8998       case ISD::SETUGT:
8999         // Converting this to a min would handle NaNs incorrectly.
9000         if (!UnsafeFPMath &&
9001             (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)))
9002           break;
9003         Opcode = X86ISD::FMIN;
9004         break;
9005       case ISD::SETUGE:
9006         // Converting this to a min would handle both negative zeros and NaNs
9007         // incorrectly, but we can swap the operands to fix both.
9008         std::swap(LHS, RHS);
9009       case ISD::SETOGT:
9010       case ISD::SETGT:
9011       case ISD::SETGE:
9012         Opcode = X86ISD::FMIN;
9013         break;
9014
9015       case ISD::SETULT:
9016         // Converting this to a max would handle NaNs incorrectly.
9017         if (!FiniteOnlyFPMath() &&
9018             (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)))
9019           break;
9020         Opcode = X86ISD::FMAX;
9021         break;
9022       case ISD::SETOLE:
9023         // Converting this to a max would handle comparisons between positive
9024         // and negative zero incorrectly, and swapping the operands would
9025         // cause it to handle NaNs incorrectly.
9026         if (!UnsafeFPMath &&
9027             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS)) {
9028           if (!FiniteOnlyFPMath() &&
9029               (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)))
9030             break;
9031           std::swap(LHS, RHS);
9032         }
9033         Opcode = X86ISD::FMAX;
9034         break;
9035       case ISD::SETULE:
9036         // Converting this to a max would handle both negative zeros and NaNs
9037         // incorrectly, but we can swap the operands to fix both.
9038         std::swap(LHS, RHS);
9039       case ISD::SETOLT:
9040       case ISD::SETLT:
9041       case ISD::SETLE:
9042         Opcode = X86ISD::FMAX;
9043         break;
9044       }
9045     }
9046
9047     if (Opcode)
9048       return DAG.getNode(Opcode, DL, N->getValueType(0), LHS, RHS);
9049   }
9050
9051   // If this is a select between two integer constants, try to do some
9052   // optimizations.
9053   if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(LHS)) {
9054     if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(RHS))
9055       // Don't do this for crazy integer types.
9056       if (DAG.getTargetLoweringInfo().isTypeLegal(LHS.getValueType())) {
9057         // If this is efficiently invertible, canonicalize the LHSC/RHSC values
9058         // so that TrueC (the true value) is larger than FalseC.
9059         bool NeedsCondInvert = false;
9060
9061         if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue()) &&
9062             // Efficiently invertible.
9063             (Cond.getOpcode() == ISD::SETCC ||  // setcc -> invertible.
9064              (Cond.getOpcode() == ISD::XOR &&   // xor(X, C) -> invertible.
9065               isa<ConstantSDNode>(Cond.getOperand(1))))) {
9066           NeedsCondInvert = true;
9067           std::swap(TrueC, FalseC);
9068         }
9069
9070         // Optimize C ? 8 : 0 -> zext(C) << 3.  Likewise for any pow2/0.
9071         if (FalseC->getAPIntValue() == 0 &&
9072             TrueC->getAPIntValue().isPowerOf2()) {
9073           if (NeedsCondInvert) // Invert the condition if needed.
9074             Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
9075                                DAG.getConstant(1, Cond.getValueType()));
9076
9077           // Zero extend the condition if needed.
9078           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, LHS.getValueType(), Cond);
9079
9080           unsigned ShAmt = TrueC->getAPIntValue().logBase2();
9081           return DAG.getNode(ISD::SHL, DL, LHS.getValueType(), Cond,
9082                              DAG.getConstant(ShAmt, MVT::i8));
9083         }
9084
9085         // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.
9086         if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
9087           if (NeedsCondInvert) // Invert the condition if needed.
9088             Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
9089                                DAG.getConstant(1, Cond.getValueType()));
9090
9091           // Zero extend the condition if needed.
9092           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
9093                              FalseC->getValueType(0), Cond);
9094           return DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
9095                              SDValue(FalseC, 0));
9096         }
9097
9098         // Optimize cases that will turn into an LEA instruction.  This requires
9099         // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
9100         if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
9101           uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
9102           if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
9103
9104           bool isFastMultiplier = false;
9105           if (Diff < 10) {
9106             switch ((unsigned char)Diff) {
9107               default: break;
9108               case 1:  // result = add base, cond
9109               case 2:  // result = lea base(    , cond*2)
9110               case 3:  // result = lea base(cond, cond*2)
9111               case 4:  // result = lea base(    , cond*4)
9112               case 5:  // result = lea base(cond, cond*4)
9113               case 8:  // result = lea base(    , cond*8)
9114               case 9:  // result = lea base(cond, cond*8)
9115                 isFastMultiplier = true;
9116                 break;
9117             }
9118           }
9119
9120           if (isFastMultiplier) {
9121             APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
9122             if (NeedsCondInvert) // Invert the condition if needed.
9123               Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
9124                                  DAG.getConstant(1, Cond.getValueType()));
9125
9126             // Zero extend the condition if needed.
9127             Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
9128                                Cond);
9129             // Scale the condition by the difference.
9130             if (Diff != 1)
9131               Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
9132                                  DAG.getConstant(Diff, Cond.getValueType()));
9133
9134             // Add the base if non-zero.
9135             if (FalseC->getAPIntValue() != 0)
9136               Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
9137                                  SDValue(FalseC, 0));
9138             return Cond;
9139           }
9140         }
9141       }
9142   }
9143
9144   return SDValue();
9145 }
9146
9147 /// Optimize X86ISD::CMOV [LHS, RHS, CONDCODE (e.g. X86::COND_NE), CONDVAL]
9148 static SDValue PerformCMOVCombine(SDNode *N, SelectionDAG &DAG,
9149                                   TargetLowering::DAGCombinerInfo &DCI) {
9150   DebugLoc DL = N->getDebugLoc();
9151
9152   // If the flag operand isn't dead, don't touch this CMOV.
9153   if (N->getNumValues() == 2 && !SDValue(N, 1).use_empty())
9154     return SDValue();
9155
9156   // If this is a select between two integer constants, try to do some
9157   // optimizations.  Note that the operands are ordered the opposite of SELECT
9158   // operands.
9159   if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(N->getOperand(1))) {
9160     if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(N->getOperand(0))) {
9161       // Canonicalize the TrueC/FalseC values so that TrueC (the true value) is
9162       // larger than FalseC (the false value).
9163       X86::CondCode CC = (X86::CondCode)N->getConstantOperandVal(2);
9164
9165       if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue())) {
9166         CC = X86::GetOppositeBranchCondition(CC);
9167         std::swap(TrueC, FalseC);
9168       }
9169
9170       // Optimize C ? 8 : 0 -> zext(setcc(C)) << 3.  Likewise for any pow2/0.
9171       // This is efficient for any integer data type (including i8/i16) and
9172       // shift amount.
9173       if (FalseC->getAPIntValue() == 0 && TrueC->getAPIntValue().isPowerOf2()) {
9174         SDValue Cond = N->getOperand(3);
9175         Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
9176                            DAG.getConstant(CC, MVT::i8), Cond);
9177
9178         // Zero extend the condition if needed.
9179         Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, TrueC->getValueType(0), Cond);
9180
9181         unsigned ShAmt = TrueC->getAPIntValue().logBase2();
9182         Cond = DAG.getNode(ISD::SHL, DL, Cond.getValueType(), Cond,
9183                            DAG.getConstant(ShAmt, MVT::i8));
9184         if (N->getNumValues() == 2)  // Dead flag value?
9185           return DCI.CombineTo(N, Cond, SDValue());
9186         return Cond;
9187       }
9188
9189       // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.  This is efficient
9190       // for any integer data type, including i8/i16.
9191       if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
9192         SDValue Cond = N->getOperand(3);
9193         Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
9194                            DAG.getConstant(CC, MVT::i8), Cond);
9195
9196         // Zero extend the condition if needed.
9197         Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
9198                            FalseC->getValueType(0), Cond);
9199         Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
9200                            SDValue(FalseC, 0));
9201
9202         if (N->getNumValues() == 2)  // Dead flag value?
9203           return DCI.CombineTo(N, Cond, SDValue());
9204         return Cond;
9205       }
9206
9207       // Optimize cases that will turn into an LEA instruction.  This requires
9208       // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
9209       if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
9210         uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
9211         if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
9212
9213         bool isFastMultiplier = false;
9214         if (Diff < 10) {
9215           switch ((unsigned char)Diff) {
9216           default: break;
9217           case 1:  // result = add base, cond
9218           case 2:  // result = lea base(    , cond*2)
9219           case 3:  // result = lea base(cond, cond*2)
9220           case 4:  // result = lea base(    , cond*4)
9221           case 5:  // result = lea base(cond, cond*4)
9222           case 8:  // result = lea base(    , cond*8)
9223           case 9:  // result = lea base(cond, cond*8)
9224             isFastMultiplier = true;
9225             break;
9226           }
9227         }
9228
9229         if (isFastMultiplier) {
9230           APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
9231           SDValue Cond = N->getOperand(3);
9232           Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
9233                              DAG.getConstant(CC, MVT::i8), Cond);
9234           // Zero extend the condition if needed.
9235           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
9236                              Cond);
9237           // Scale the condition by the difference.
9238           if (Diff != 1)
9239             Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
9240                                DAG.getConstant(Diff, Cond.getValueType()));
9241
9242           // Add the base if non-zero.
9243           if (FalseC->getAPIntValue() != 0)
9244             Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
9245                                SDValue(FalseC, 0));
9246           if (N->getNumValues() == 2)  // Dead flag value?
9247             return DCI.CombineTo(N, Cond, SDValue());
9248           return Cond;
9249         }
9250       }
9251     }
9252   }
9253   return SDValue();
9254 }
9255
9256
9257 /// PerformMulCombine - Optimize a single multiply with constant into two
9258 /// in order to implement it with two cheaper instructions, e.g.
9259 /// LEA + SHL, LEA + LEA.
9260 static SDValue PerformMulCombine(SDNode *N, SelectionDAG &DAG,
9261                                  TargetLowering::DAGCombinerInfo &DCI) {
9262   if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
9263     return SDValue();
9264
9265   EVT VT = N->getValueType(0);
9266   if (VT != MVT::i64)
9267     return SDValue();
9268
9269   ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
9270   if (!C)
9271     return SDValue();
9272   uint64_t MulAmt = C->getZExtValue();
9273   if (isPowerOf2_64(MulAmt) || MulAmt == 3 || MulAmt == 5 || MulAmt == 9)
9274     return SDValue();
9275
9276   uint64_t MulAmt1 = 0;
9277   uint64_t MulAmt2 = 0;
9278   if ((MulAmt % 9) == 0) {
9279     MulAmt1 = 9;
9280     MulAmt2 = MulAmt / 9;
9281   } else if ((MulAmt % 5) == 0) {
9282     MulAmt1 = 5;
9283     MulAmt2 = MulAmt / 5;
9284   } else if ((MulAmt % 3) == 0) {
9285     MulAmt1 = 3;
9286     MulAmt2 = MulAmt / 3;
9287   }
9288   if (MulAmt2 &&
9289       (isPowerOf2_64(MulAmt2) || MulAmt2 == 3 || MulAmt2 == 5 || MulAmt2 == 9)){
9290     DebugLoc DL = N->getDebugLoc();
9291
9292     if (isPowerOf2_64(MulAmt2) &&
9293         !(N->hasOneUse() && N->use_begin()->getOpcode() == ISD::ADD))
9294       // If second multiplifer is pow2, issue it first. We want the multiply by
9295       // 3, 5, or 9 to be folded into the addressing mode unless the lone use
9296       // is an add.
9297       std::swap(MulAmt1, MulAmt2);
9298
9299     SDValue NewMul;
9300     if (isPowerOf2_64(MulAmt1))
9301       NewMul = DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
9302                            DAG.getConstant(Log2_64(MulAmt1), MVT::i8));
9303     else
9304       NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, N->getOperand(0),
9305                            DAG.getConstant(MulAmt1, VT));
9306
9307     if (isPowerOf2_64(MulAmt2))
9308       NewMul = DAG.getNode(ISD::SHL, DL, VT, NewMul,
9309                            DAG.getConstant(Log2_64(MulAmt2), MVT::i8));
9310     else
9311       NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, NewMul,
9312                            DAG.getConstant(MulAmt2, VT));
9313
9314     // Do not add new nodes to DAG combiner worklist.
9315     DCI.CombineTo(N, NewMul, false);
9316   }
9317   return SDValue();
9318 }
9319
9320 static SDValue PerformSHLCombine(SDNode *N, SelectionDAG &DAG) {
9321   SDValue N0 = N->getOperand(0);
9322   SDValue N1 = N->getOperand(1);
9323   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
9324   EVT VT = N0.getValueType();
9325
9326   // fold (shl (and (setcc_c), c1), c2) -> (and setcc_c, (c1 << c2))
9327   // since the result of setcc_c is all zero's or all ones.
9328   if (N1C && N0.getOpcode() == ISD::AND &&
9329       N0.getOperand(1).getOpcode() == ISD::Constant) {
9330     SDValue N00 = N0.getOperand(0);
9331     if (N00.getOpcode() == X86ISD::SETCC_CARRY ||
9332         ((N00.getOpcode() == ISD::ANY_EXTEND ||
9333           N00.getOpcode() == ISD::ZERO_EXTEND) &&
9334          N00.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY)) {
9335       APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
9336       APInt ShAmt = N1C->getAPIntValue();
9337       Mask = Mask.shl(ShAmt);
9338       if (Mask != 0)
9339         return DAG.getNode(ISD::AND, N->getDebugLoc(), VT,
9340                            N00, DAG.getConstant(Mask, VT));
9341     }
9342   }
9343
9344   return SDValue();
9345 }
9346
9347 /// PerformShiftCombine - Transforms vector shift nodes to use vector shifts
9348 ///                       when possible.
9349 static SDValue PerformShiftCombine(SDNode* N, SelectionDAG &DAG,
9350                                    const X86Subtarget *Subtarget) {
9351   EVT VT = N->getValueType(0);
9352   if (!VT.isVector() && VT.isInteger() &&
9353       N->getOpcode() == ISD::SHL)
9354     return PerformSHLCombine(N, DAG);
9355
9356   // On X86 with SSE2 support, we can transform this to a vector shift if
9357   // all elements are shifted by the same amount.  We can't do this in legalize
9358   // because the a constant vector is typically transformed to a constant pool
9359   // so we have no knowledge of the shift amount.
9360   if (!Subtarget->hasSSE2())
9361     return SDValue();
9362
9363   if (VT != MVT::v2i64 && VT != MVT::v4i32 && VT != MVT::v8i16)
9364     return SDValue();
9365
9366   SDValue ShAmtOp = N->getOperand(1);
9367   EVT EltVT = VT.getVectorElementType();
9368   DebugLoc DL = N->getDebugLoc();
9369   SDValue BaseShAmt = SDValue();
9370   if (ShAmtOp.getOpcode() == ISD::BUILD_VECTOR) {
9371     unsigned NumElts = VT.getVectorNumElements();
9372     unsigned i = 0;
9373     for (; i != NumElts; ++i) {
9374       SDValue Arg = ShAmtOp.getOperand(i);
9375       if (Arg.getOpcode() == ISD::UNDEF) continue;
9376       BaseShAmt = Arg;
9377       break;
9378     }
9379     for (; i != NumElts; ++i) {
9380       SDValue Arg = ShAmtOp.getOperand(i);
9381       if (Arg.getOpcode() == ISD::UNDEF) continue;
9382       if (Arg != BaseShAmt) {
9383         return SDValue();
9384       }
9385     }
9386   } else if (ShAmtOp.getOpcode() == ISD::VECTOR_SHUFFLE &&
9387              cast<ShuffleVectorSDNode>(ShAmtOp)->isSplat()) {
9388     SDValue InVec = ShAmtOp.getOperand(0);
9389     if (InVec.getOpcode() == ISD::BUILD_VECTOR) {
9390       unsigned NumElts = InVec.getValueType().getVectorNumElements();
9391       unsigned i = 0;
9392       for (; i != NumElts; ++i) {
9393         SDValue Arg = InVec.getOperand(i);
9394         if (Arg.getOpcode() == ISD::UNDEF) continue;
9395         BaseShAmt = Arg;
9396         break;
9397       }
9398     } else if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT) {
9399        if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(InVec.getOperand(2))) {
9400          unsigned SplatIdx= cast<ShuffleVectorSDNode>(ShAmtOp)->getSplatIndex();
9401          if (C->getZExtValue() == SplatIdx)
9402            BaseShAmt = InVec.getOperand(1);
9403        }
9404     }
9405     if (BaseShAmt.getNode() == 0)
9406       BaseShAmt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, EltVT, ShAmtOp,
9407                               DAG.getIntPtrConstant(0));
9408   } else
9409     return SDValue();
9410
9411   // The shift amount is an i32.
9412   if (EltVT.bitsGT(MVT::i32))
9413     BaseShAmt = DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, BaseShAmt);
9414   else if (EltVT.bitsLT(MVT::i32))
9415     BaseShAmt = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, BaseShAmt);
9416
9417   // The shift amount is identical so we can do a vector shift.
9418   SDValue  ValOp = N->getOperand(0);
9419   switch (N->getOpcode()) {
9420   default:
9421     llvm_unreachable("Unknown shift opcode!");
9422     break;
9423   case ISD::SHL:
9424     if (VT == MVT::v2i64)
9425       return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
9426                          DAG.getConstant(Intrinsic::x86_sse2_pslli_q, MVT::i32),
9427                          ValOp, BaseShAmt);
9428     if (VT == MVT::v4i32)
9429       return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
9430                          DAG.getConstant(Intrinsic::x86_sse2_pslli_d, MVT::i32),
9431                          ValOp, BaseShAmt);
9432     if (VT == MVT::v8i16)
9433       return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
9434                          DAG.getConstant(Intrinsic::x86_sse2_pslli_w, MVT::i32),
9435                          ValOp, BaseShAmt);
9436     break;
9437   case ISD::SRA:
9438     if (VT == MVT::v4i32)
9439       return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
9440                          DAG.getConstant(Intrinsic::x86_sse2_psrai_d, MVT::i32),
9441                          ValOp, BaseShAmt);
9442     if (VT == MVT::v8i16)
9443       return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
9444                          DAG.getConstant(Intrinsic::x86_sse2_psrai_w, MVT::i32),
9445                          ValOp, BaseShAmt);
9446     break;
9447   case ISD::SRL:
9448     if (VT == MVT::v2i64)
9449       return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
9450                          DAG.getConstant(Intrinsic::x86_sse2_psrli_q, MVT::i32),
9451                          ValOp, BaseShAmt);
9452     if (VT == MVT::v4i32)
9453       return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
9454                          DAG.getConstant(Intrinsic::x86_sse2_psrli_d, MVT::i32),
9455                          ValOp, BaseShAmt);
9456     if (VT ==  MVT::v8i16)
9457       return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
9458                          DAG.getConstant(Intrinsic::x86_sse2_psrli_w, MVT::i32),
9459                          ValOp, BaseShAmt);
9460     break;
9461   }
9462   return SDValue();
9463 }
9464
9465 static SDValue PerformOrCombine(SDNode *N, SelectionDAG &DAG,
9466                                 const X86Subtarget *Subtarget) {
9467   EVT VT = N->getValueType(0);
9468   if (VT != MVT::i64 || !Subtarget->is64Bit())
9469     return SDValue();
9470
9471   // fold (or (x << c) | (y >> (64 - c))) ==> (shld64 x, y, c)
9472   SDValue N0 = N->getOperand(0);
9473   SDValue N1 = N->getOperand(1);
9474   if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL)
9475     std::swap(N0, N1);
9476   if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL)
9477     return SDValue();
9478
9479   SDValue ShAmt0 = N0.getOperand(1);
9480   if (ShAmt0.getValueType() != MVT::i8)
9481     return SDValue();
9482   SDValue ShAmt1 = N1.getOperand(1);
9483   if (ShAmt1.getValueType() != MVT::i8)
9484     return SDValue();
9485   if (ShAmt0.getOpcode() == ISD::TRUNCATE)
9486     ShAmt0 = ShAmt0.getOperand(0);
9487   if (ShAmt1.getOpcode() == ISD::TRUNCATE)
9488     ShAmt1 = ShAmt1.getOperand(0);
9489
9490   DebugLoc DL = N->getDebugLoc();
9491   unsigned Opc = X86ISD::SHLD;
9492   SDValue Op0 = N0.getOperand(0);
9493   SDValue Op1 = N1.getOperand(0);
9494   if (ShAmt0.getOpcode() == ISD::SUB) {
9495     Opc = X86ISD::SHRD;
9496     std::swap(Op0, Op1);
9497     std::swap(ShAmt0, ShAmt1);
9498   }
9499
9500   if (ShAmt1.getOpcode() == ISD::SUB) {
9501     SDValue Sum = ShAmt1.getOperand(0);
9502     if (ConstantSDNode *SumC = dyn_cast<ConstantSDNode>(Sum)) {
9503       if (SumC->getSExtValue() == 64 &&
9504           ShAmt1.getOperand(1) == ShAmt0)
9505         return DAG.getNode(Opc, DL, VT,
9506                            Op0, Op1,
9507                            DAG.getNode(ISD::TRUNCATE, DL,
9508                                        MVT::i8, ShAmt0));
9509     }
9510   } else if (ConstantSDNode *ShAmt1C = dyn_cast<ConstantSDNode>(ShAmt1)) {
9511     ConstantSDNode *ShAmt0C = dyn_cast<ConstantSDNode>(ShAmt0);
9512     if (ShAmt0C &&
9513         ShAmt0C->getSExtValue() + ShAmt1C->getSExtValue() == 64)
9514       return DAG.getNode(Opc, DL, VT,
9515                          N0.getOperand(0), N1.getOperand(0),
9516                          DAG.getNode(ISD::TRUNCATE, DL,
9517                                        MVT::i8, ShAmt0));
9518   }
9519
9520   return SDValue();
9521 }
9522
9523 /// PerformSTORECombine - Do target-specific dag combines on STORE nodes.
9524 static SDValue PerformSTORECombine(SDNode *N, SelectionDAG &DAG,
9525                                    const X86Subtarget *Subtarget) {
9526   // Turn load->store of MMX types into GPR load/stores.  This avoids clobbering
9527   // the FP state in cases where an emms may be missing.
9528   // A preferable solution to the general problem is to figure out the right
9529   // places to insert EMMS.  This qualifies as a quick hack.
9530
9531   // Similarly, turn load->store of i64 into double load/stores in 32-bit mode.
9532   StoreSDNode *St = cast<StoreSDNode>(N);
9533   EVT VT = St->getValue().getValueType();
9534   if (VT.getSizeInBits() != 64)
9535     return SDValue();
9536
9537   const Function *F = DAG.getMachineFunction().getFunction();
9538   bool NoImplicitFloatOps = F->hasFnAttr(Attribute::NoImplicitFloat);
9539   bool F64IsLegal = !UseSoftFloat && !NoImplicitFloatOps
9540     && Subtarget->hasSSE2();
9541   if ((VT.isVector() ||
9542        (VT == MVT::i64 && F64IsLegal && !Subtarget->is64Bit())) &&
9543       isa<LoadSDNode>(St->getValue()) &&
9544       !cast<LoadSDNode>(St->getValue())->isVolatile() &&
9545       St->getChain().hasOneUse() && !St->isVolatile()) {
9546     SDNode* LdVal = St->getValue().getNode();
9547     LoadSDNode *Ld = 0;
9548     int TokenFactorIndex = -1;
9549     SmallVector<SDValue, 8> Ops;
9550     SDNode* ChainVal = St->getChain().getNode();
9551     // Must be a store of a load.  We currently handle two cases:  the load
9552     // is a direct child, and it's under an intervening TokenFactor.  It is
9553     // possible to dig deeper under nested TokenFactors.
9554     if (ChainVal == LdVal)
9555       Ld = cast<LoadSDNode>(St->getChain());
9556     else if (St->getValue().hasOneUse() &&
9557              ChainVal->getOpcode() == ISD::TokenFactor) {
9558       for (unsigned i=0, e = ChainVal->getNumOperands(); i != e; ++i) {
9559         if (ChainVal->getOperand(i).getNode() == LdVal) {
9560           TokenFactorIndex = i;
9561           Ld = cast<LoadSDNode>(St->getValue());
9562         } else
9563           Ops.push_back(ChainVal->getOperand(i));
9564       }
9565     }
9566
9567     if (!Ld || !ISD::isNormalLoad(Ld))
9568       return SDValue();
9569
9570     // If this is not the MMX case, i.e. we are just turning i64 load/store
9571     // into f64 load/store, avoid the transformation if there are multiple
9572     // uses of the loaded value.
9573     if (!VT.isVector() && !Ld->hasNUsesOfValue(1, 0))
9574       return SDValue();
9575
9576     DebugLoc LdDL = Ld->getDebugLoc();
9577     DebugLoc StDL = N->getDebugLoc();
9578     // If we are a 64-bit capable x86, lower to a single movq load/store pair.
9579     // Otherwise, if it's legal to use f64 SSE instructions, use f64 load/store
9580     // pair instead.
9581     if (Subtarget->is64Bit() || F64IsLegal) {
9582       EVT LdVT = Subtarget->is64Bit() ? MVT::i64 : MVT::f64;
9583       SDValue NewLd = DAG.getLoad(LdVT, LdDL, Ld->getChain(),
9584                                   Ld->getBasePtr(), Ld->getSrcValue(),
9585                                   Ld->getSrcValueOffset(), Ld->isVolatile(),
9586                                   Ld->isNonTemporal(), Ld->getAlignment());
9587       SDValue NewChain = NewLd.getValue(1);
9588       if (TokenFactorIndex != -1) {
9589         Ops.push_back(NewChain);
9590         NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, &Ops[0],
9591                                Ops.size());
9592       }
9593       return DAG.getStore(NewChain, StDL, NewLd, St->getBasePtr(),
9594                           St->getSrcValue(), St->getSrcValueOffset(),
9595                           St->isVolatile(), St->isNonTemporal(),
9596                           St->getAlignment());
9597     }
9598
9599     // Otherwise, lower to two pairs of 32-bit loads / stores.
9600     SDValue LoAddr = Ld->getBasePtr();
9601     SDValue HiAddr = DAG.getNode(ISD::ADD, LdDL, MVT::i32, LoAddr,
9602                                  DAG.getConstant(4, MVT::i32));
9603
9604     SDValue LoLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), LoAddr,
9605                                Ld->getSrcValue(), Ld->getSrcValueOffset(),
9606                                Ld->isVolatile(), Ld->isNonTemporal(),
9607                                Ld->getAlignment());
9608     SDValue HiLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), HiAddr,
9609                                Ld->getSrcValue(), Ld->getSrcValueOffset()+4,
9610                                Ld->isVolatile(), Ld->isNonTemporal(),
9611                                MinAlign(Ld->getAlignment(), 4));
9612
9613     SDValue NewChain = LoLd.getValue(1);
9614     if (TokenFactorIndex != -1) {
9615       Ops.push_back(LoLd);
9616       Ops.push_back(HiLd);
9617       NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, &Ops[0],
9618                              Ops.size());
9619     }
9620
9621     LoAddr = St->getBasePtr();
9622     HiAddr = DAG.getNode(ISD::ADD, StDL, MVT::i32, LoAddr,
9623                          DAG.getConstant(4, MVT::i32));
9624
9625     SDValue LoSt = DAG.getStore(NewChain, StDL, LoLd, LoAddr,
9626                                 St->getSrcValue(), St->getSrcValueOffset(),
9627                                 St->isVolatile(), St->isNonTemporal(),
9628                                 St->getAlignment());
9629     SDValue HiSt = DAG.getStore(NewChain, StDL, HiLd, HiAddr,
9630                                 St->getSrcValue(),
9631                                 St->getSrcValueOffset() + 4,
9632                                 St->isVolatile(),
9633                                 St->isNonTemporal(),
9634                                 MinAlign(St->getAlignment(), 4));
9635     return DAG.getNode(ISD::TokenFactor, StDL, MVT::Other, LoSt, HiSt);
9636   }
9637   return SDValue();
9638 }
9639
9640 /// PerformFORCombine - Do target-specific dag combines on X86ISD::FOR and
9641 /// X86ISD::FXOR nodes.
9642 static SDValue PerformFORCombine(SDNode *N, SelectionDAG &DAG) {
9643   assert(N->getOpcode() == X86ISD::FOR || N->getOpcode() == X86ISD::FXOR);
9644   // F[X]OR(0.0, x) -> x
9645   // F[X]OR(x, 0.0) -> x
9646   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
9647     if (C->getValueAPF().isPosZero())
9648       return N->getOperand(1);
9649   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
9650     if (C->getValueAPF().isPosZero())
9651       return N->getOperand(0);
9652   return SDValue();
9653 }
9654
9655 /// PerformFANDCombine - Do target-specific dag combines on X86ISD::FAND nodes.
9656 static SDValue PerformFANDCombine(SDNode *N, SelectionDAG &DAG) {
9657   // FAND(0.0, x) -> 0.0
9658   // FAND(x, 0.0) -> 0.0
9659   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
9660     if (C->getValueAPF().isPosZero())
9661       return N->getOperand(0);
9662   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
9663     if (C->getValueAPF().isPosZero())
9664       return N->getOperand(1);
9665   return SDValue();
9666 }
9667
9668 static SDValue PerformBTCombine(SDNode *N,
9669                                 SelectionDAG &DAG,
9670                                 TargetLowering::DAGCombinerInfo &DCI) {
9671   // BT ignores high bits in the bit index operand.
9672   SDValue Op1 = N->getOperand(1);
9673   if (Op1.hasOneUse()) {
9674     unsigned BitWidth = Op1.getValueSizeInBits();
9675     APInt DemandedMask = APInt::getLowBitsSet(BitWidth, Log2_32(BitWidth));
9676     APInt KnownZero, KnownOne;
9677     TargetLowering::TargetLoweringOpt TLO(DAG);
9678     TargetLowering &TLI = DAG.getTargetLoweringInfo();
9679     if (TLO.ShrinkDemandedConstant(Op1, DemandedMask) ||
9680         TLI.SimplifyDemandedBits(Op1, DemandedMask, KnownZero, KnownOne, TLO))
9681       DCI.CommitTargetLoweringOpt(TLO);
9682   }
9683   return SDValue();
9684 }
9685
9686 static SDValue PerformVZEXT_MOVLCombine(SDNode *N, SelectionDAG &DAG) {
9687   SDValue Op = N->getOperand(0);
9688   if (Op.getOpcode() == ISD::BIT_CONVERT)
9689     Op = Op.getOperand(0);
9690   EVT VT = N->getValueType(0), OpVT = Op.getValueType();
9691   if (Op.getOpcode() == X86ISD::VZEXT_LOAD &&
9692       VT.getVectorElementType().getSizeInBits() ==
9693       OpVT.getVectorElementType().getSizeInBits()) {
9694     return DAG.getNode(ISD::BIT_CONVERT, N->getDebugLoc(), VT, Op);
9695   }
9696   return SDValue();
9697 }
9698
9699 // On X86 and X86-64, atomic operations are lowered to locked instructions.
9700 // Locked instructions, in turn, have implicit fence semantics (all memory
9701 // operations are flushed before issuing the locked instruction, and the
9702 // are not buffered), so we can fold away the common pattern of
9703 // fence-atomic-fence.
9704 static SDValue PerformMEMBARRIERCombine(SDNode* N, SelectionDAG &DAG) {
9705   SDValue atomic = N->getOperand(0);
9706   switch (atomic.getOpcode()) {
9707     case ISD::ATOMIC_CMP_SWAP:
9708     case ISD::ATOMIC_SWAP:
9709     case ISD::ATOMIC_LOAD_ADD:
9710     case ISD::ATOMIC_LOAD_SUB:
9711     case ISD::ATOMIC_LOAD_AND:
9712     case ISD::ATOMIC_LOAD_OR:
9713     case ISD::ATOMIC_LOAD_XOR:
9714     case ISD::ATOMIC_LOAD_NAND:
9715     case ISD::ATOMIC_LOAD_MIN:
9716     case ISD::ATOMIC_LOAD_MAX:
9717     case ISD::ATOMIC_LOAD_UMIN:
9718     case ISD::ATOMIC_LOAD_UMAX:
9719       break;
9720     default:
9721       return SDValue();
9722   }
9723
9724   SDValue fence = atomic.getOperand(0);
9725   if (fence.getOpcode() != ISD::MEMBARRIER)
9726     return SDValue();
9727
9728   switch (atomic.getOpcode()) {
9729     case ISD::ATOMIC_CMP_SWAP:
9730       return DAG.UpdateNodeOperands(atomic, fence.getOperand(0),
9731                                     atomic.getOperand(1), atomic.getOperand(2),
9732                                     atomic.getOperand(3));
9733     case ISD::ATOMIC_SWAP:
9734     case ISD::ATOMIC_LOAD_ADD:
9735     case ISD::ATOMIC_LOAD_SUB:
9736     case ISD::ATOMIC_LOAD_AND:
9737     case ISD::ATOMIC_LOAD_OR:
9738     case ISD::ATOMIC_LOAD_XOR:
9739     case ISD::ATOMIC_LOAD_NAND:
9740     case ISD::ATOMIC_LOAD_MIN:
9741     case ISD::ATOMIC_LOAD_MAX:
9742     case ISD::ATOMIC_LOAD_UMIN:
9743     case ISD::ATOMIC_LOAD_UMAX:
9744       return DAG.UpdateNodeOperands(atomic, fence.getOperand(0),
9745                                     atomic.getOperand(1), atomic.getOperand(2));
9746     default:
9747       return SDValue();
9748   }
9749 }
9750
9751 static SDValue PerformZExtCombine(SDNode *N, SelectionDAG &DAG) {
9752   // (i32 zext (and (i8  x86isd::setcc_carry), 1)) ->
9753   //           (and (i32 x86isd::setcc_carry), 1)
9754   // This eliminates the zext. This transformation is necessary because
9755   // ISD::SETCC is always legalized to i8.
9756   DebugLoc dl = N->getDebugLoc();
9757   SDValue N0 = N->getOperand(0);
9758   EVT VT = N->getValueType(0);
9759   if (N0.getOpcode() == ISD::AND &&
9760       N0.hasOneUse() &&
9761       N0.getOperand(0).hasOneUse()) {
9762     SDValue N00 = N0.getOperand(0);
9763     if (N00.getOpcode() != X86ISD::SETCC_CARRY)
9764       return SDValue();
9765     ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
9766     if (!C || C->getZExtValue() != 1)
9767       return SDValue();
9768     return DAG.getNode(ISD::AND, dl, VT,
9769                        DAG.getNode(X86ISD::SETCC_CARRY, dl, VT,
9770                                    N00.getOperand(0), N00.getOperand(1)),
9771                        DAG.getConstant(1, VT));
9772   }
9773
9774   return SDValue();
9775 }
9776
9777 SDValue X86TargetLowering::PerformDAGCombine(SDNode *N,
9778                                              DAGCombinerInfo &DCI) const {
9779   SelectionDAG &DAG = DCI.DAG;
9780   switch (N->getOpcode()) {
9781   default: break;
9782   case ISD::VECTOR_SHUFFLE: return PerformShuffleCombine(N, DAG, *this);
9783   case ISD::SELECT:         return PerformSELECTCombine(N, DAG, Subtarget);
9784   case X86ISD::CMOV:        return PerformCMOVCombine(N, DAG, DCI);
9785   case ISD::MUL:            return PerformMulCombine(N, DAG, DCI);
9786   case ISD::SHL:
9787   case ISD::SRA:
9788   case ISD::SRL:            return PerformShiftCombine(N, DAG, Subtarget);
9789   case ISD::OR:             return PerformOrCombine(N, DAG, Subtarget);
9790   case ISD::STORE:          return PerformSTORECombine(N, DAG, Subtarget);
9791   case X86ISD::FXOR:
9792   case X86ISD::FOR:         return PerformFORCombine(N, DAG);
9793   case X86ISD::FAND:        return PerformFANDCombine(N, DAG);
9794   case X86ISD::BT:          return PerformBTCombine(N, DAG, DCI);
9795   case X86ISD::VZEXT_MOVL:  return PerformVZEXT_MOVLCombine(N, DAG);
9796   case ISD::MEMBARRIER:     return PerformMEMBARRIERCombine(N, DAG);
9797   case ISD::ZERO_EXTEND:    return PerformZExtCombine(N, DAG);
9798   }
9799
9800   return SDValue();
9801 }
9802
9803 //===----------------------------------------------------------------------===//
9804 //                           X86 Inline Assembly Support
9805 //===----------------------------------------------------------------------===//
9806
9807 static bool LowerToBSwap(CallInst *CI) {
9808   // FIXME: this should verify that we are targetting a 486 or better.  If not,
9809   // we will turn this bswap into something that will be lowered to logical ops
9810   // instead of emitting the bswap asm.  For now, we don't support 486 or lower
9811   // so don't worry about this.
9812
9813   // Verify this is a simple bswap.
9814   if (CI->getNumOperands() != 2 ||
9815       CI->getType() != CI->getOperand(1)->getType() ||
9816       !CI->getType()->isIntegerTy())
9817     return false;
9818
9819   const IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
9820   if (!Ty || Ty->getBitWidth() % 16 != 0)
9821     return false;
9822
9823   // Okay, we can do this xform, do so now.
9824   const Type *Tys[] = { Ty };
9825   Module *M = CI->getParent()->getParent()->getParent();
9826   Constant *Int = Intrinsic::getDeclaration(M, Intrinsic::bswap, Tys, 1);
9827
9828   Value *Op = CI->getOperand(1);
9829   Op = CallInst::Create(Int, Op, CI->getName(), CI);
9830
9831   CI->replaceAllUsesWith(Op);
9832   CI->eraseFromParent();
9833   return true;
9834 }
9835
9836 bool X86TargetLowering::ExpandInlineAsm(CallInst *CI) const {
9837   InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue());
9838   std::vector<InlineAsm::ConstraintInfo> Constraints = IA->ParseConstraints();
9839
9840   std::string AsmStr = IA->getAsmString();
9841
9842   // TODO: should remove alternatives from the asmstring: "foo {a|b}" -> "foo a"
9843   SmallVector<StringRef, 4> AsmPieces;
9844   SplitString(AsmStr, AsmPieces, "\n");  // ; as separator?
9845
9846   switch (AsmPieces.size()) {
9847   default: return false;
9848   case 1:
9849     AsmStr = AsmPieces[0];
9850     AsmPieces.clear();
9851     SplitString(AsmStr, AsmPieces, " \t");  // Split with whitespace.
9852
9853     // bswap $0
9854     if (AsmPieces.size() == 2 &&
9855         (AsmPieces[0] == "bswap" ||
9856          AsmPieces[0] == "bswapq" ||
9857          AsmPieces[0] == "bswapl") &&
9858         (AsmPieces[1] == "$0" ||
9859          AsmPieces[1] == "${0:q}")) {
9860       // No need to check constraints, nothing other than the equivalent of
9861       // "=r,0" would be valid here.
9862       return LowerToBSwap(CI);
9863     }
9864     // rorw $$8, ${0:w}  -->  llvm.bswap.i16
9865     if (CI->getType()->isIntegerTy(16) &&
9866         AsmPieces.size() == 3 &&
9867         (AsmPieces[0] == "rorw" || AsmPieces[0] == "rolw") &&
9868         AsmPieces[1] == "$$8," &&
9869         AsmPieces[2] == "${0:w}" &&
9870         IA->getConstraintString().compare(0, 5, "=r,0,") == 0) {
9871       AsmPieces.clear();
9872       const std::string &Constraints = IA->getConstraintString();
9873       SplitString(StringRef(Constraints).substr(5), AsmPieces, ",");
9874       std::sort(AsmPieces.begin(), AsmPieces.end());
9875       if (AsmPieces.size() == 4 &&
9876           AsmPieces[0] == "~{cc}" &&
9877           AsmPieces[1] == "~{dirflag}" &&
9878           AsmPieces[2] == "~{flags}" &&
9879           AsmPieces[3] == "~{fpsr}") {
9880         return LowerToBSwap(CI);
9881       }
9882     }
9883     break;
9884   case 3:
9885     if (CI->getType()->isIntegerTy(64) &&
9886         Constraints.size() >= 2 &&
9887         Constraints[0].Codes.size() == 1 && Constraints[0].Codes[0] == "A" &&
9888         Constraints[1].Codes.size() == 1 && Constraints[1].Codes[0] == "0") {
9889       // bswap %eax / bswap %edx / xchgl %eax, %edx  -> llvm.bswap.i64
9890       SmallVector<StringRef, 4> Words;
9891       SplitString(AsmPieces[0], Words, " \t");
9892       if (Words.size() == 2 && Words[0] == "bswap" && Words[1] == "%eax") {
9893         Words.clear();
9894         SplitString(AsmPieces[1], Words, " \t");
9895         if (Words.size() == 2 && Words[0] == "bswap" && Words[1] == "%edx") {
9896           Words.clear();
9897           SplitString(AsmPieces[2], Words, " \t,");
9898           if (Words.size() == 3 && Words[0] == "xchgl" && Words[1] == "%eax" &&
9899               Words[2] == "%edx") {
9900             return LowerToBSwap(CI);
9901           }
9902         }
9903       }
9904     }
9905     break;
9906   }
9907   return false;
9908 }
9909
9910
9911
9912 /// getConstraintType - Given a constraint letter, return the type of
9913 /// constraint it is for this target.
9914 X86TargetLowering::ConstraintType
9915 X86TargetLowering::getConstraintType(const std::string &Constraint) const {
9916   if (Constraint.size() == 1) {
9917     switch (Constraint[0]) {
9918     case 'A':
9919       return C_Register;
9920     case 'f':
9921     case 'r':
9922     case 'R':
9923     case 'l':
9924     case 'q':
9925     case 'Q':
9926     case 'x':
9927     case 'y':
9928     case 'Y':
9929       return C_RegisterClass;
9930     case 'e':
9931     case 'Z':
9932       return C_Other;
9933     default:
9934       break;
9935     }
9936   }
9937   return TargetLowering::getConstraintType(Constraint);
9938 }
9939
9940 /// LowerXConstraint - try to replace an X constraint, which matches anything,
9941 /// with another that has more specific requirements based on the type of the
9942 /// corresponding operand.
9943 const char *X86TargetLowering::
9944 LowerXConstraint(EVT ConstraintVT) const {
9945   // FP X constraints get lowered to SSE1/2 registers if available, otherwise
9946   // 'f' like normal targets.
9947   if (ConstraintVT.isFloatingPoint()) {
9948     if (Subtarget->hasSSE2())
9949       return "Y";
9950     if (Subtarget->hasSSE1())
9951       return "x";
9952   }
9953
9954   return TargetLowering::LowerXConstraint(ConstraintVT);
9955 }
9956
9957 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
9958 /// vector.  If it is invalid, don't add anything to Ops.
9959 void X86TargetLowering::LowerAsmOperandForConstraint(SDValue Op,
9960                                                      char Constraint,
9961                                                      bool hasMemory,
9962                                                      std::vector<SDValue>&Ops,
9963                                                      SelectionDAG &DAG) const {
9964   SDValue Result(0, 0);
9965
9966   switch (Constraint) {
9967   default: break;
9968   case 'I':
9969     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
9970       if (C->getZExtValue() <= 31) {
9971         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
9972         break;
9973       }
9974     }
9975     return;
9976   case 'J':
9977     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
9978       if (C->getZExtValue() <= 63) {
9979         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
9980         break;
9981       }
9982     }
9983     return;
9984   case 'K':
9985     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
9986       if ((int8_t)C->getSExtValue() == C->getSExtValue()) {
9987         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
9988         break;
9989       }
9990     }
9991     return;
9992   case 'N':
9993     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
9994       if (C->getZExtValue() <= 255) {
9995         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
9996         break;
9997       }
9998     }
9999     return;
10000   case 'e': {
10001     // 32-bit signed value
10002     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
10003       const ConstantInt *CI = C->getConstantIntValue();
10004       if (CI->isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
10005                                   C->getSExtValue())) {
10006         // Widen to 64 bits here to get it sign extended.
10007         Result = DAG.getTargetConstant(C->getSExtValue(), MVT::i64);
10008         break;
10009       }
10010     // FIXME gcc accepts some relocatable values here too, but only in certain
10011     // memory models; it's complicated.
10012     }
10013     return;
10014   }
10015   case 'Z': {
10016     // 32-bit unsigned value
10017     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
10018       const ConstantInt *CI = C->getConstantIntValue();
10019       if (CI->isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
10020                                   C->getZExtValue())) {
10021         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
10022         break;
10023       }
10024     }
10025     // FIXME gcc accepts some relocatable values here too, but only in certain
10026     // memory models; it's complicated.
10027     return;
10028   }
10029   case 'i': {
10030     // Literal immediates are always ok.
10031     if (ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op)) {
10032       // Widen to 64 bits here to get it sign extended.
10033       Result = DAG.getTargetConstant(CST->getSExtValue(), MVT::i64);
10034       break;
10035     }
10036
10037     // If we are in non-pic codegen mode, we allow the address of a global (with
10038     // an optional displacement) to be used with 'i'.
10039     GlobalAddressSDNode *GA = 0;
10040     int64_t Offset = 0;
10041
10042     // Match either (GA), (GA+C), (GA+C1+C2), etc.
10043     while (1) {
10044       if ((GA = dyn_cast<GlobalAddressSDNode>(Op))) {
10045         Offset += GA->getOffset();
10046         break;
10047       } else if (Op.getOpcode() == ISD::ADD) {
10048         if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
10049           Offset += C->getZExtValue();
10050           Op = Op.getOperand(0);
10051           continue;
10052         }
10053       } else if (Op.getOpcode() == ISD::SUB) {
10054         if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
10055           Offset += -C->getZExtValue();
10056           Op = Op.getOperand(0);
10057           continue;
10058         }
10059       }
10060
10061       // Otherwise, this isn't something we can handle, reject it.
10062       return;
10063     }
10064
10065     GlobalValue *GV = GA->getGlobal();
10066     // If we require an extra load to get this address, as in PIC mode, we
10067     // can't accept it.
10068     if (isGlobalStubReference(Subtarget->ClassifyGlobalReference(GV,
10069                                                         getTargetMachine())))
10070       return;
10071
10072     if (hasMemory)
10073       Op = LowerGlobalAddress(GV, Op.getDebugLoc(), Offset, DAG);
10074     else
10075       Op = DAG.getTargetGlobalAddress(GV, GA->getValueType(0), Offset);
10076     Result = Op;
10077     break;
10078   }
10079   }
10080
10081   if (Result.getNode()) {
10082     Ops.push_back(Result);
10083     return;
10084   }
10085   return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, hasMemory,
10086                                                       Ops, DAG);
10087 }
10088
10089 std::vector<unsigned> X86TargetLowering::
10090 getRegClassForInlineAsmConstraint(const std::string &Constraint,
10091                                   EVT VT) const {
10092   if (Constraint.size() == 1) {
10093     // FIXME: not handling fp-stack yet!
10094     switch (Constraint[0]) {      // GCC X86 Constraint Letters
10095     default: break;  // Unknown constraint letter
10096     case 'q':   // GENERAL_REGS in 64-bit mode, Q_REGS in 32-bit mode.
10097       if (Subtarget->is64Bit()) {
10098         if (VT == MVT::i32)
10099           return make_vector<unsigned>(X86::EAX, X86::EDX, X86::ECX, X86::EBX,
10100                                        X86::ESI, X86::EDI, X86::R8D, X86::R9D,
10101                                        X86::R10D,X86::R11D,X86::R12D,
10102                                        X86::R13D,X86::R14D,X86::R15D,
10103                                        X86::EBP, X86::ESP, 0);
10104         else if (VT == MVT::i16)
10105           return make_vector<unsigned>(X86::AX,  X86::DX,  X86::CX, X86::BX,
10106                                        X86::SI,  X86::DI,  X86::R8W,X86::R9W,
10107                                        X86::R10W,X86::R11W,X86::R12W,
10108                                        X86::R13W,X86::R14W,X86::R15W,
10109                                        X86::BP,  X86::SP, 0);
10110         else if (VT == MVT::i8)
10111           return make_vector<unsigned>(X86::AL,  X86::DL,  X86::CL, X86::BL,
10112                                        X86::SIL, X86::DIL, X86::R8B,X86::R9B,
10113                                        X86::R10B,X86::R11B,X86::R12B,
10114                                        X86::R13B,X86::R14B,X86::R15B,
10115                                        X86::BPL, X86::SPL, 0);
10116
10117         else if (VT == MVT::i64)
10118           return make_vector<unsigned>(X86::RAX, X86::RDX, X86::RCX, X86::RBX,
10119                                        X86::RSI, X86::RDI, X86::R8,  X86::R9,
10120                                        X86::R10, X86::R11, X86::R12,
10121                                        X86::R13, X86::R14, X86::R15,
10122                                        X86::RBP, X86::RSP, 0);
10123
10124         break;
10125       }
10126       // 32-bit fallthrough
10127     case 'Q':   // Q_REGS
10128       if (VT == MVT::i32)
10129         return make_vector<unsigned>(X86::EAX, X86::EDX, X86::ECX, X86::EBX, 0);
10130       else if (VT == MVT::i16)
10131         return make_vector<unsigned>(X86::AX, X86::DX, X86::CX, X86::BX, 0);
10132       else if (VT == MVT::i8)
10133         return make_vector<unsigned>(X86::AL, X86::DL, X86::CL, X86::BL, 0);
10134       else if (VT == MVT::i64)
10135         return make_vector<unsigned>(X86::RAX, X86::RDX, X86::RCX, X86::RBX, 0);
10136       break;
10137     }
10138   }
10139
10140   return std::vector<unsigned>();
10141 }
10142
10143 std::pair<unsigned, const TargetRegisterClass*>
10144 X86TargetLowering::getRegForInlineAsmConstraint(const std::string &Constraint,
10145                                                 EVT VT) const {
10146   // First, see if this is a constraint that directly corresponds to an LLVM
10147   // register class.
10148   if (Constraint.size() == 1) {
10149     // GCC Constraint Letters
10150     switch (Constraint[0]) {
10151     default: break;
10152     case 'r':   // GENERAL_REGS
10153     case 'l':   // INDEX_REGS
10154       if (VT == MVT::i8)
10155         return std::make_pair(0U, X86::GR8RegisterClass);
10156       if (VT == MVT::i16)
10157         return std::make_pair(0U, X86::GR16RegisterClass);
10158       if (VT == MVT::i32 || !Subtarget->is64Bit())
10159         return std::make_pair(0U, X86::GR32RegisterClass);
10160       return std::make_pair(0U, X86::GR64RegisterClass);
10161     case 'R':   // LEGACY_REGS
10162       if (VT == MVT::i8)
10163         return std::make_pair(0U, X86::GR8_NOREXRegisterClass);
10164       if (VT == MVT::i16)
10165         return std::make_pair(0U, X86::GR16_NOREXRegisterClass);
10166       if (VT == MVT::i32 || !Subtarget->is64Bit())
10167         return std::make_pair(0U, X86::GR32_NOREXRegisterClass);
10168       return std::make_pair(0U, X86::GR64_NOREXRegisterClass);
10169     case 'f':  // FP Stack registers.
10170       // If SSE is enabled for this VT, use f80 to ensure the isel moves the
10171       // value to the correct fpstack register class.
10172       if (VT == MVT::f32 && !isScalarFPTypeInSSEReg(VT))
10173         return std::make_pair(0U, X86::RFP32RegisterClass);
10174       if (VT == MVT::f64 && !isScalarFPTypeInSSEReg(VT))
10175         return std::make_pair(0U, X86::RFP64RegisterClass);
10176       return std::make_pair(0U, X86::RFP80RegisterClass);
10177     case 'y':   // MMX_REGS if MMX allowed.
10178       if (!Subtarget->hasMMX()) break;
10179       return std::make_pair(0U, X86::VR64RegisterClass);
10180     case 'Y':   // SSE_REGS if SSE2 allowed
10181       if (!Subtarget->hasSSE2()) break;
10182       // FALL THROUGH.
10183     case 'x':   // SSE_REGS if SSE1 allowed
10184       if (!Subtarget->hasSSE1()) break;
10185
10186       switch (VT.getSimpleVT().SimpleTy) {
10187       default: break;
10188       // Scalar SSE types.
10189       case MVT::f32:
10190       case MVT::i32:
10191         return std::make_pair(0U, X86::FR32RegisterClass);
10192       case MVT::f64:
10193       case MVT::i64:
10194         return std::make_pair(0U, X86::FR64RegisterClass);
10195       // Vector types.
10196       case MVT::v16i8:
10197       case MVT::v8i16:
10198       case MVT::v4i32:
10199       case MVT::v2i64:
10200       case MVT::v4f32:
10201       case MVT::v2f64:
10202         return std::make_pair(0U, X86::VR128RegisterClass);
10203       }
10204       break;
10205     }
10206   }
10207
10208   // Use the default implementation in TargetLowering to convert the register
10209   // constraint into a member of a register class.
10210   std::pair<unsigned, const TargetRegisterClass*> Res;
10211   Res = TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
10212
10213   // Not found as a standard register?
10214   if (Res.second == 0) {
10215     // Map st(0) -> st(7) -> ST0
10216     if (Constraint.size() == 7 && Constraint[0] == '{' &&
10217         tolower(Constraint[1]) == 's' &&
10218         tolower(Constraint[2]) == 't' &&
10219         Constraint[3] == '(' &&
10220         (Constraint[4] >= '0' && Constraint[4] <= '7') &&
10221         Constraint[5] == ')' &&
10222         Constraint[6] == '}') {
10223
10224       Res.first = X86::ST0+Constraint[4]-'0';
10225       Res.second = X86::RFP80RegisterClass;
10226       return Res;
10227     }
10228
10229     // GCC allows "st(0)" to be called just plain "st".
10230     if (StringRef("{st}").equals_lower(Constraint)) {
10231       Res.first = X86::ST0;
10232       Res.second = X86::RFP80RegisterClass;
10233       return Res;
10234     }
10235
10236     // flags -> EFLAGS
10237     if (StringRef("{flags}").equals_lower(Constraint)) {
10238       Res.first = X86::EFLAGS;
10239       Res.second = X86::CCRRegisterClass;
10240       return Res;
10241     }
10242
10243     // 'A' means EAX + EDX.
10244     if (Constraint == "A") {
10245       Res.first = X86::EAX;
10246       Res.second = X86::GR32_ADRegisterClass;
10247       return Res;
10248     }
10249     return Res;
10250   }
10251
10252   // Otherwise, check to see if this is a register class of the wrong value
10253   // type.  For example, we want to map "{ax},i32" -> {eax}, we don't want it to
10254   // turn into {ax},{dx}.
10255   if (Res.second->hasType(VT))
10256     return Res;   // Correct type already, nothing to do.
10257
10258   // All of the single-register GCC register classes map their values onto
10259   // 16-bit register pieces "ax","dx","cx","bx","si","di","bp","sp".  If we
10260   // really want an 8-bit or 32-bit register, map to the appropriate register
10261   // class and return the appropriate register.
10262   if (Res.second == X86::GR16RegisterClass) {
10263     if (VT == MVT::i8) {
10264       unsigned DestReg = 0;
10265       switch (Res.first) {
10266       default: break;
10267       case X86::AX: DestReg = X86::AL; break;
10268       case X86::DX: DestReg = X86::DL; break;
10269       case X86::CX: DestReg = X86::CL; break;
10270       case X86::BX: DestReg = X86::BL; break;
10271       }
10272       if (DestReg) {
10273         Res.first = DestReg;
10274         Res.second = X86::GR8RegisterClass;
10275       }
10276     } else if (VT == MVT::i32) {
10277       unsigned DestReg = 0;
10278       switch (Res.first) {
10279       default: break;
10280       case X86::AX: DestReg = X86::EAX; break;
10281       case X86::DX: DestReg = X86::EDX; break;
10282       case X86::CX: DestReg = X86::ECX; break;
10283       case X86::BX: DestReg = X86::EBX; break;
10284       case X86::SI: DestReg = X86::ESI; break;
10285       case X86::DI: DestReg = X86::EDI; break;
10286       case X86::BP: DestReg = X86::EBP; break;
10287       case X86::SP: DestReg = X86::ESP; break;
10288       }
10289       if (DestReg) {
10290         Res.first = DestReg;
10291         Res.second = X86::GR32RegisterClass;
10292       }
10293     } else if (VT == MVT::i64) {
10294       unsigned DestReg = 0;
10295       switch (Res.first) {
10296       default: break;
10297       case X86::AX: DestReg = X86::RAX; break;
10298       case X86::DX: DestReg = X86::RDX; break;
10299       case X86::CX: DestReg = X86::RCX; break;
10300       case X86::BX: DestReg = X86::RBX; break;
10301       case X86::SI: DestReg = X86::RSI; break;
10302       case X86::DI: DestReg = X86::RDI; break;
10303       case X86::BP: DestReg = X86::RBP; break;
10304       case X86::SP: DestReg = X86::RSP; break;
10305       }
10306       if (DestReg) {
10307         Res.first = DestReg;
10308         Res.second = X86::GR64RegisterClass;
10309       }
10310     }
10311   } else if (Res.second == X86::FR32RegisterClass ||
10312              Res.second == X86::FR64RegisterClass ||
10313              Res.second == X86::VR128RegisterClass) {
10314     // Handle references to XMM physical registers that got mapped into the
10315     // wrong class.  This can happen with constraints like {xmm0} where the
10316     // target independent register mapper will just pick the first match it can
10317     // find, ignoring the required type.
10318     if (VT == MVT::f32)
10319       Res.second = X86::FR32RegisterClass;
10320     else if (VT == MVT::f64)
10321       Res.second = X86::FR64RegisterClass;
10322     else if (X86::VR128RegisterClass->hasType(VT))
10323       Res.second = X86::VR128RegisterClass;
10324   }
10325
10326   return Res;
10327 }