Promoting 16-bit cmp / test aren't free. Don't do it.
[oota-llvm.git] / lib / Target / X86 / X86ISelLowering.cpp
1 //===-- X86ISelLowering.cpp - X86 DAG Lowering Implementation -------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file defines the interfaces that X86 uses to lower LLVM code into a
11 // selection DAG.
12 //
13 //===----------------------------------------------------------------------===//
14
15 #define DEBUG_TYPE "x86-isel"
16 #include "X86.h"
17 #include "X86InstrBuilder.h"
18 #include "X86ISelLowering.h"
19 #include "X86TargetMachine.h"
20 #include "X86TargetObjectFile.h"
21 #include "llvm/CallingConv.h"
22 #include "llvm/Constants.h"
23 #include "llvm/DerivedTypes.h"
24 #include "llvm/GlobalAlias.h"
25 #include "llvm/GlobalVariable.h"
26 #include "llvm/Function.h"
27 #include "llvm/Instructions.h"
28 #include "llvm/Intrinsics.h"
29 #include "llvm/LLVMContext.h"
30 #include "llvm/CodeGen/MachineFrameInfo.h"
31 #include "llvm/CodeGen/MachineFunction.h"
32 #include "llvm/CodeGen/MachineInstrBuilder.h"
33 #include "llvm/CodeGen/MachineJumpTableInfo.h"
34 #include "llvm/CodeGen/MachineModuleInfo.h"
35 #include "llvm/CodeGen/MachineRegisterInfo.h"
36 #include "llvm/CodeGen/PseudoSourceValue.h"
37 #include "llvm/MC/MCAsmInfo.h"
38 #include "llvm/MC/MCContext.h"
39 #include "llvm/MC/MCExpr.h"
40 #include "llvm/MC/MCSymbol.h"
41 #include "llvm/ADT/BitVector.h"
42 #include "llvm/ADT/SmallSet.h"
43 #include "llvm/ADT/Statistic.h"
44 #include "llvm/ADT/StringExtras.h"
45 #include "llvm/ADT/VectorExtras.h"
46 #include "llvm/Support/CommandLine.h"
47 #include "llvm/Support/Debug.h"
48 #include "llvm/Support/Dwarf.h"
49 #include "llvm/Support/ErrorHandling.h"
50 #include "llvm/Support/MathExtras.h"
51 #include "llvm/Support/raw_ostream.h"
52 using namespace llvm;
53 using namespace dwarf;
54
55 STATISTIC(NumTailCalls, "Number of tail calls");
56
57 static cl::opt<bool>
58 DisableMMX("disable-mmx", cl::Hidden, cl::desc("Disable use of MMX"));
59
60 // Disable16Bit - 16-bit operations typically have a larger encoding than
61 // corresponding 32-bit instructions, and 16-bit code is slow on some
62 // processors. This is an experimental flag to disable 16-bit operations
63 // (which forces them to be Legalized to 32-bit operations).
64 static cl::opt<bool>
65 Disable16Bit("disable-16bit", cl::Hidden,
66              cl::desc("Disable use of 16-bit instructions"));
67
68 // Forward declarations.
69 static SDValue getMOVL(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
70                        SDValue V2);
71
72 static TargetLoweringObjectFile *createTLOF(X86TargetMachine &TM) {
73   switch (TM.getSubtarget<X86Subtarget>().TargetType) {
74   default: llvm_unreachable("unknown subtarget type");
75   case X86Subtarget::isDarwin:
76     if (TM.getSubtarget<X86Subtarget>().is64Bit())
77       return new X8664_MachoTargetObjectFile();
78     return new TargetLoweringObjectFileMachO();
79   case X86Subtarget::isELF:
80    if (TM.getSubtarget<X86Subtarget>().is64Bit())
81      return new X8664_ELFTargetObjectFile(TM);
82     return new X8632_ELFTargetObjectFile(TM);
83   case X86Subtarget::isMingw:
84   case X86Subtarget::isCygwin:
85   case X86Subtarget::isWindows:
86     return new TargetLoweringObjectFileCOFF();
87   }
88 }
89
90 X86TargetLowering::X86TargetLowering(X86TargetMachine &TM)
91   : TargetLowering(TM, createTLOF(TM)) {
92   Subtarget = &TM.getSubtarget<X86Subtarget>();
93   X86ScalarSSEf64 = Subtarget->hasSSE2();
94   X86ScalarSSEf32 = Subtarget->hasSSE1();
95   X86StackPtr = Subtarget->is64Bit() ? X86::RSP : X86::ESP;
96
97   RegInfo = TM.getRegisterInfo();
98   TD = getTargetData();
99
100   // Set up the TargetLowering object.
101
102   // X86 is weird, it always uses i8 for shift amounts and setcc results.
103   setShiftAmountType(MVT::i8);
104   setBooleanContents(ZeroOrOneBooleanContent);
105   setSchedulingPreference(SchedulingForRegPressure);
106   setStackPointerRegisterToSaveRestore(X86StackPtr);
107
108   if (Subtarget->isTargetDarwin()) {
109     // Darwin should use _setjmp/_longjmp instead of setjmp/longjmp.
110     setUseUnderscoreSetJmp(false);
111     setUseUnderscoreLongJmp(false);
112   } else if (Subtarget->isTargetMingw()) {
113     // MS runtime is weird: it exports _setjmp, but longjmp!
114     setUseUnderscoreSetJmp(true);
115     setUseUnderscoreLongJmp(false);
116   } else {
117     setUseUnderscoreSetJmp(true);
118     setUseUnderscoreLongJmp(true);
119   }
120
121   // Set up the register classes.
122   addRegisterClass(MVT::i8, X86::GR8RegisterClass);
123   if (!Disable16Bit)
124     addRegisterClass(MVT::i16, X86::GR16RegisterClass);
125   addRegisterClass(MVT::i32, X86::GR32RegisterClass);
126   if (Subtarget->is64Bit())
127     addRegisterClass(MVT::i64, X86::GR64RegisterClass);
128
129   setLoadExtAction(ISD::SEXTLOAD, MVT::i1, Promote);
130
131   // We don't accept any truncstore of integer registers.
132   setTruncStoreAction(MVT::i64, MVT::i32, Expand);
133   if (!Disable16Bit)
134     setTruncStoreAction(MVT::i64, MVT::i16, Expand);
135   setTruncStoreAction(MVT::i64, MVT::i8 , Expand);
136   if (!Disable16Bit)
137     setTruncStoreAction(MVT::i32, MVT::i16, Expand);
138   setTruncStoreAction(MVT::i32, MVT::i8 , Expand);
139   setTruncStoreAction(MVT::i16, MVT::i8,  Expand);
140
141   // SETOEQ and SETUNE require checking two conditions.
142   setCondCodeAction(ISD::SETOEQ, MVT::f32, Expand);
143   setCondCodeAction(ISD::SETOEQ, MVT::f64, Expand);
144   setCondCodeAction(ISD::SETOEQ, MVT::f80, Expand);
145   setCondCodeAction(ISD::SETUNE, MVT::f32, Expand);
146   setCondCodeAction(ISD::SETUNE, MVT::f64, Expand);
147   setCondCodeAction(ISD::SETUNE, MVT::f80, Expand);
148
149   // Promote all UINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have this
150   // operation.
151   setOperationAction(ISD::UINT_TO_FP       , MVT::i1   , Promote);
152   setOperationAction(ISD::UINT_TO_FP       , MVT::i8   , Promote);
153   setOperationAction(ISD::UINT_TO_FP       , MVT::i16  , Promote);
154
155   if (Subtarget->is64Bit()) {
156     setOperationAction(ISD::UINT_TO_FP     , MVT::i32  , Promote);
157     setOperationAction(ISD::UINT_TO_FP     , MVT::i64  , Expand);
158   } else if (!UseSoftFloat) {
159     if (X86ScalarSSEf64) {
160       // We have an impenetrably clever algorithm for ui64->double only.
161       setOperationAction(ISD::UINT_TO_FP   , MVT::i64  , Custom);
162     }
163     // We have an algorithm for SSE2, and we turn this into a 64-bit
164     // FILD for other targets.
165     setOperationAction(ISD::UINT_TO_FP   , MVT::i32  , Custom);
166   }
167
168   // Promote i1/i8 SINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have
169   // this operation.
170   setOperationAction(ISD::SINT_TO_FP       , MVT::i1   , Promote);
171   setOperationAction(ISD::SINT_TO_FP       , MVT::i8   , Promote);
172
173   if (!UseSoftFloat) {
174     // SSE has no i16 to fp conversion, only i32
175     if (X86ScalarSSEf32) {
176       setOperationAction(ISD::SINT_TO_FP     , MVT::i16  , Promote);
177       // f32 and f64 cases are Legal, f80 case is not
178       setOperationAction(ISD::SINT_TO_FP     , MVT::i32  , Custom);
179     } else {
180       setOperationAction(ISD::SINT_TO_FP     , MVT::i16  , Custom);
181       setOperationAction(ISD::SINT_TO_FP     , MVT::i32  , Custom);
182     }
183   } else {
184     setOperationAction(ISD::SINT_TO_FP     , MVT::i16  , Promote);
185     setOperationAction(ISD::SINT_TO_FP     , MVT::i32  , Promote);
186   }
187
188   // In 32-bit mode these are custom lowered.  In 64-bit mode F32 and F64
189   // are Legal, f80 is custom lowered.
190   setOperationAction(ISD::FP_TO_SINT     , MVT::i64  , Custom);
191   setOperationAction(ISD::SINT_TO_FP     , MVT::i64  , Custom);
192
193   // Promote i1/i8 FP_TO_SINT to larger FP_TO_SINTS's, as X86 doesn't have
194   // this operation.
195   setOperationAction(ISD::FP_TO_SINT       , MVT::i1   , Promote);
196   setOperationAction(ISD::FP_TO_SINT       , MVT::i8   , Promote);
197
198   if (X86ScalarSSEf32) {
199     setOperationAction(ISD::FP_TO_SINT     , MVT::i16  , Promote);
200     // f32 and f64 cases are Legal, f80 case is not
201     setOperationAction(ISD::FP_TO_SINT     , MVT::i32  , Custom);
202   } else {
203     setOperationAction(ISD::FP_TO_SINT     , MVT::i16  , Custom);
204     setOperationAction(ISD::FP_TO_SINT     , MVT::i32  , Custom);
205   }
206
207   // Handle FP_TO_UINT by promoting the destination to a larger signed
208   // conversion.
209   setOperationAction(ISD::FP_TO_UINT       , MVT::i1   , Promote);
210   setOperationAction(ISD::FP_TO_UINT       , MVT::i8   , Promote);
211   setOperationAction(ISD::FP_TO_UINT       , MVT::i16  , Promote);
212
213   if (Subtarget->is64Bit()) {
214     setOperationAction(ISD::FP_TO_UINT     , MVT::i64  , Expand);
215     setOperationAction(ISD::FP_TO_UINT     , MVT::i32  , Promote);
216   } else if (!UseSoftFloat) {
217     if (X86ScalarSSEf32 && !Subtarget->hasSSE3())
218       // Expand FP_TO_UINT into a select.
219       // FIXME: We would like to use a Custom expander here eventually to do
220       // the optimal thing for SSE vs. the default expansion in the legalizer.
221       setOperationAction(ISD::FP_TO_UINT   , MVT::i32  , Expand);
222     else
223       // With SSE3 we can use fisttpll to convert to a signed i64; without
224       // SSE, we're stuck with a fistpll.
225       setOperationAction(ISD::FP_TO_UINT   , MVT::i32  , Custom);
226   }
227
228   // TODO: when we have SSE, these could be more efficient, by using movd/movq.
229   if (!X86ScalarSSEf64) {
230     setOperationAction(ISD::BIT_CONVERT      , MVT::f32  , Expand);
231     setOperationAction(ISD::BIT_CONVERT      , MVT::i32  , Expand);
232   }
233
234   // Scalar integer divide and remainder are lowered to use operations that
235   // produce two results, to match the available instructions. This exposes
236   // the two-result form to trivial CSE, which is able to combine x/y and x%y
237   // into a single instruction.
238   //
239   // Scalar integer multiply-high is also lowered to use two-result
240   // operations, to match the available instructions. However, plain multiply
241   // (low) operations are left as Legal, as there are single-result
242   // instructions for this in x86. Using the two-result multiply instructions
243   // when both high and low results are needed must be arranged by dagcombine.
244   setOperationAction(ISD::MULHS           , MVT::i8    , Expand);
245   setOperationAction(ISD::MULHU           , MVT::i8    , Expand);
246   setOperationAction(ISD::SDIV            , MVT::i8    , Expand);
247   setOperationAction(ISD::UDIV            , MVT::i8    , Expand);
248   setOperationAction(ISD::SREM            , MVT::i8    , Expand);
249   setOperationAction(ISD::UREM            , MVT::i8    , Expand);
250   setOperationAction(ISD::MULHS           , MVT::i16   , Expand);
251   setOperationAction(ISD::MULHU           , MVT::i16   , Expand);
252   setOperationAction(ISD::SDIV            , MVT::i16   , Expand);
253   setOperationAction(ISD::UDIV            , MVT::i16   , Expand);
254   setOperationAction(ISD::SREM            , MVT::i16   , Expand);
255   setOperationAction(ISD::UREM            , MVT::i16   , Expand);
256   setOperationAction(ISD::MULHS           , MVT::i32   , Expand);
257   setOperationAction(ISD::MULHU           , MVT::i32   , Expand);
258   setOperationAction(ISD::SDIV            , MVT::i32   , Expand);
259   setOperationAction(ISD::UDIV            , MVT::i32   , Expand);
260   setOperationAction(ISD::SREM            , MVT::i32   , Expand);
261   setOperationAction(ISD::UREM            , MVT::i32   , Expand);
262   setOperationAction(ISD::MULHS           , MVT::i64   , Expand);
263   setOperationAction(ISD::MULHU           , MVT::i64   , Expand);
264   setOperationAction(ISD::SDIV            , MVT::i64   , Expand);
265   setOperationAction(ISD::UDIV            , MVT::i64   , Expand);
266   setOperationAction(ISD::SREM            , MVT::i64   , Expand);
267   setOperationAction(ISD::UREM            , MVT::i64   , Expand);
268
269   setOperationAction(ISD::BR_JT            , MVT::Other, Expand);
270   setOperationAction(ISD::BRCOND           , MVT::Other, Custom);
271   setOperationAction(ISD::BR_CC            , MVT::Other, Expand);
272   setOperationAction(ISD::SELECT_CC        , MVT::Other, Expand);
273   if (Subtarget->is64Bit())
274     setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i32, Legal);
275   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16  , Legal);
276   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8   , Legal);
277   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1   , Expand);
278   setOperationAction(ISD::FP_ROUND_INREG   , MVT::f32  , Expand);
279   setOperationAction(ISD::FREM             , MVT::f32  , Expand);
280   setOperationAction(ISD::FREM             , MVT::f64  , Expand);
281   setOperationAction(ISD::FREM             , MVT::f80  , Expand);
282   setOperationAction(ISD::FLT_ROUNDS_      , MVT::i32  , Custom);
283
284   setOperationAction(ISD::CTPOP            , MVT::i8   , Expand);
285   setOperationAction(ISD::CTTZ             , MVT::i8   , Custom);
286   setOperationAction(ISD::CTLZ             , MVT::i8   , Custom);
287   setOperationAction(ISD::CTPOP            , MVT::i16  , Expand);
288   if (Disable16Bit) {
289     setOperationAction(ISD::CTTZ           , MVT::i16  , Expand);
290     setOperationAction(ISD::CTLZ           , MVT::i16  , Expand);
291   } else {
292     setOperationAction(ISD::CTTZ           , MVT::i16  , Custom);
293     setOperationAction(ISD::CTLZ           , MVT::i16  , Custom);
294   }
295   setOperationAction(ISD::CTPOP            , MVT::i32  , Expand);
296   setOperationAction(ISD::CTTZ             , MVT::i32  , Custom);
297   setOperationAction(ISD::CTLZ             , MVT::i32  , Custom);
298   if (Subtarget->is64Bit()) {
299     setOperationAction(ISD::CTPOP          , MVT::i64  , Expand);
300     setOperationAction(ISD::CTTZ           , MVT::i64  , Custom);
301     setOperationAction(ISD::CTLZ           , MVT::i64  , Custom);
302   }
303
304   setOperationAction(ISD::READCYCLECOUNTER , MVT::i64  , Custom);
305   setOperationAction(ISD::BSWAP            , MVT::i16  , Expand);
306
307   // These should be promoted to a larger select which is supported.
308   setOperationAction(ISD::SELECT          , MVT::i1   , Promote);
309   // X86 wants to expand cmov itself.
310   setOperationAction(ISD::SELECT          , MVT::i8   , Custom);
311   if (Disable16Bit)
312     setOperationAction(ISD::SELECT        , MVT::i16  , Expand);
313   else
314     setOperationAction(ISD::SELECT        , MVT::i16  , Custom);
315   setOperationAction(ISD::SELECT          , MVT::i32  , Custom);
316   setOperationAction(ISD::SELECT          , MVT::f32  , Custom);
317   setOperationAction(ISD::SELECT          , MVT::f64  , Custom);
318   setOperationAction(ISD::SELECT          , MVT::f80  , Custom);
319   setOperationAction(ISD::SETCC           , MVT::i8   , Custom);
320   if (Disable16Bit)
321     setOperationAction(ISD::SETCC         , MVT::i16  , Expand);
322   else
323     setOperationAction(ISD::SETCC         , MVT::i16  , Custom);
324   setOperationAction(ISD::SETCC           , MVT::i32  , Custom);
325   setOperationAction(ISD::SETCC           , MVT::f32  , Custom);
326   setOperationAction(ISD::SETCC           , MVT::f64  , Custom);
327   setOperationAction(ISD::SETCC           , MVT::f80  , Custom);
328   if (Subtarget->is64Bit()) {
329     setOperationAction(ISD::SELECT        , MVT::i64  , Custom);
330     setOperationAction(ISD::SETCC         , MVT::i64  , Custom);
331   }
332   setOperationAction(ISD::EH_RETURN       , MVT::Other, Custom);
333
334   // Darwin ABI issue.
335   setOperationAction(ISD::ConstantPool    , MVT::i32  , Custom);
336   setOperationAction(ISD::JumpTable       , MVT::i32  , Custom);
337   setOperationAction(ISD::GlobalAddress   , MVT::i32  , Custom);
338   setOperationAction(ISD::GlobalTLSAddress, MVT::i32  , Custom);
339   if (Subtarget->is64Bit())
340     setOperationAction(ISD::GlobalTLSAddress, MVT::i64, Custom);
341   setOperationAction(ISD::ExternalSymbol  , MVT::i32  , Custom);
342   setOperationAction(ISD::BlockAddress    , MVT::i32  , Custom);
343   if (Subtarget->is64Bit()) {
344     setOperationAction(ISD::ConstantPool  , MVT::i64  , Custom);
345     setOperationAction(ISD::JumpTable     , MVT::i64  , Custom);
346     setOperationAction(ISD::GlobalAddress , MVT::i64  , Custom);
347     setOperationAction(ISD::ExternalSymbol, MVT::i64  , Custom);
348     setOperationAction(ISD::BlockAddress  , MVT::i64  , Custom);
349   }
350   // 64-bit addm sub, shl, sra, srl (iff 32-bit x86)
351   setOperationAction(ISD::SHL_PARTS       , MVT::i32  , Custom);
352   setOperationAction(ISD::SRA_PARTS       , MVT::i32  , Custom);
353   setOperationAction(ISD::SRL_PARTS       , MVT::i32  , Custom);
354   if (Subtarget->is64Bit()) {
355     setOperationAction(ISD::SHL_PARTS     , MVT::i64  , Custom);
356     setOperationAction(ISD::SRA_PARTS     , MVT::i64  , Custom);
357     setOperationAction(ISD::SRL_PARTS     , MVT::i64  , Custom);
358   }
359
360   if (Subtarget->hasSSE1())
361     setOperationAction(ISD::PREFETCH      , MVT::Other, Legal);
362
363   if (!Subtarget->hasSSE2())
364     setOperationAction(ISD::MEMBARRIER    , MVT::Other, Expand);
365
366   // Expand certain atomics
367   setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i8, Custom);
368   setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i16, Custom);
369   setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i32, Custom);
370   setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i64, Custom);
371
372   setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i8, Custom);
373   setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i16, Custom);
374   setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i32, Custom);
375   setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i64, Custom);
376
377   if (!Subtarget->is64Bit()) {
378     setOperationAction(ISD::ATOMIC_LOAD_ADD, MVT::i64, Custom);
379     setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i64, Custom);
380     setOperationAction(ISD::ATOMIC_LOAD_AND, MVT::i64, Custom);
381     setOperationAction(ISD::ATOMIC_LOAD_OR, MVT::i64, Custom);
382     setOperationAction(ISD::ATOMIC_LOAD_XOR, MVT::i64, Custom);
383     setOperationAction(ISD::ATOMIC_LOAD_NAND, MVT::i64, Custom);
384     setOperationAction(ISD::ATOMIC_SWAP, MVT::i64, Custom);
385   }
386
387   // FIXME - use subtarget debug flags
388   if (!Subtarget->isTargetDarwin() &&
389       !Subtarget->isTargetELF() &&
390       !Subtarget->isTargetCygMing()) {
391     setOperationAction(ISD::EH_LABEL, MVT::Other, Expand);
392   }
393
394   setOperationAction(ISD::EXCEPTIONADDR, MVT::i64, Expand);
395   setOperationAction(ISD::EHSELECTION,   MVT::i64, Expand);
396   setOperationAction(ISD::EXCEPTIONADDR, MVT::i32, Expand);
397   setOperationAction(ISD::EHSELECTION,   MVT::i32, Expand);
398   if (Subtarget->is64Bit()) {
399     setExceptionPointerRegister(X86::RAX);
400     setExceptionSelectorRegister(X86::RDX);
401   } else {
402     setExceptionPointerRegister(X86::EAX);
403     setExceptionSelectorRegister(X86::EDX);
404   }
405   setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i32, Custom);
406   setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i64, Custom);
407
408   setOperationAction(ISD::TRAMPOLINE, MVT::Other, Custom);
409
410   setOperationAction(ISD::TRAP, MVT::Other, Legal);
411
412   // VASTART needs to be custom lowered to use the VarArgsFrameIndex
413   setOperationAction(ISD::VASTART           , MVT::Other, Custom);
414   setOperationAction(ISD::VAEND             , MVT::Other, Expand);
415   if (Subtarget->is64Bit()) {
416     setOperationAction(ISD::VAARG           , MVT::Other, Custom);
417     setOperationAction(ISD::VACOPY          , MVT::Other, Custom);
418   } else {
419     setOperationAction(ISD::VAARG           , MVT::Other, Expand);
420     setOperationAction(ISD::VACOPY          , MVT::Other, Expand);
421   }
422
423   setOperationAction(ISD::STACKSAVE,          MVT::Other, Expand);
424   setOperationAction(ISD::STACKRESTORE,       MVT::Other, Expand);
425   if (Subtarget->is64Bit())
426     setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i64, Expand);
427   if (Subtarget->isTargetCygMing())
428     setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Custom);
429   else
430     setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Expand);
431
432   if (!UseSoftFloat && X86ScalarSSEf64) {
433     // f32 and f64 use SSE.
434     // Set up the FP register classes.
435     addRegisterClass(MVT::f32, X86::FR32RegisterClass);
436     addRegisterClass(MVT::f64, X86::FR64RegisterClass);
437
438     // Use ANDPD to simulate FABS.
439     setOperationAction(ISD::FABS , MVT::f64, Custom);
440     setOperationAction(ISD::FABS , MVT::f32, Custom);
441
442     // Use XORP to simulate FNEG.
443     setOperationAction(ISD::FNEG , MVT::f64, Custom);
444     setOperationAction(ISD::FNEG , MVT::f32, Custom);
445
446     // Use ANDPD and ORPD to simulate FCOPYSIGN.
447     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
448     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
449
450     // We don't support sin/cos/fmod
451     setOperationAction(ISD::FSIN , MVT::f64, Expand);
452     setOperationAction(ISD::FCOS , MVT::f64, Expand);
453     setOperationAction(ISD::FSIN , MVT::f32, Expand);
454     setOperationAction(ISD::FCOS , MVT::f32, Expand);
455
456     // Expand FP immediates into loads from the stack, except for the special
457     // cases we handle.
458     addLegalFPImmediate(APFloat(+0.0)); // xorpd
459     addLegalFPImmediate(APFloat(+0.0f)); // xorps
460   } else if (!UseSoftFloat && X86ScalarSSEf32) {
461     // Use SSE for f32, x87 for f64.
462     // Set up the FP register classes.
463     addRegisterClass(MVT::f32, X86::FR32RegisterClass);
464     addRegisterClass(MVT::f64, X86::RFP64RegisterClass);
465
466     // Use ANDPS to simulate FABS.
467     setOperationAction(ISD::FABS , MVT::f32, Custom);
468
469     // Use XORP to simulate FNEG.
470     setOperationAction(ISD::FNEG , MVT::f32, Custom);
471
472     setOperationAction(ISD::UNDEF,     MVT::f64, Expand);
473
474     // Use ANDPS and ORPS to simulate FCOPYSIGN.
475     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
476     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
477
478     // We don't support sin/cos/fmod
479     setOperationAction(ISD::FSIN , MVT::f32, Expand);
480     setOperationAction(ISD::FCOS , MVT::f32, Expand);
481
482     // Special cases we handle for FP constants.
483     addLegalFPImmediate(APFloat(+0.0f)); // xorps
484     addLegalFPImmediate(APFloat(+0.0)); // FLD0
485     addLegalFPImmediate(APFloat(+1.0)); // FLD1
486     addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
487     addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
488
489     if (!UnsafeFPMath) {
490       setOperationAction(ISD::FSIN           , MVT::f64  , Expand);
491       setOperationAction(ISD::FCOS           , MVT::f64  , Expand);
492     }
493   } else if (!UseSoftFloat) {
494     // f32 and f64 in x87.
495     // Set up the FP register classes.
496     addRegisterClass(MVT::f64, X86::RFP64RegisterClass);
497     addRegisterClass(MVT::f32, X86::RFP32RegisterClass);
498
499     setOperationAction(ISD::UNDEF,     MVT::f64, Expand);
500     setOperationAction(ISD::UNDEF,     MVT::f32, Expand);
501     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
502     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand);
503
504     if (!UnsafeFPMath) {
505       setOperationAction(ISD::FSIN           , MVT::f64  , Expand);
506       setOperationAction(ISD::FCOS           , MVT::f64  , Expand);
507     }
508     addLegalFPImmediate(APFloat(+0.0)); // FLD0
509     addLegalFPImmediate(APFloat(+1.0)); // FLD1
510     addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
511     addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
512     addLegalFPImmediate(APFloat(+0.0f)); // FLD0
513     addLegalFPImmediate(APFloat(+1.0f)); // FLD1
514     addLegalFPImmediate(APFloat(-0.0f)); // FLD0/FCHS
515     addLegalFPImmediate(APFloat(-1.0f)); // FLD1/FCHS
516   }
517
518   // Long double always uses X87.
519   if (!UseSoftFloat) {
520     addRegisterClass(MVT::f80, X86::RFP80RegisterClass);
521     setOperationAction(ISD::UNDEF,     MVT::f80, Expand);
522     setOperationAction(ISD::FCOPYSIGN, MVT::f80, Expand);
523     {
524       bool ignored;
525       APFloat TmpFlt(+0.0);
526       TmpFlt.convert(APFloat::x87DoubleExtended, APFloat::rmNearestTiesToEven,
527                      &ignored);
528       addLegalFPImmediate(TmpFlt);  // FLD0
529       TmpFlt.changeSign();
530       addLegalFPImmediate(TmpFlt);  // FLD0/FCHS
531       APFloat TmpFlt2(+1.0);
532       TmpFlt2.convert(APFloat::x87DoubleExtended, APFloat::rmNearestTiesToEven,
533                       &ignored);
534       addLegalFPImmediate(TmpFlt2);  // FLD1
535       TmpFlt2.changeSign();
536       addLegalFPImmediate(TmpFlt2);  // FLD1/FCHS
537     }
538
539     if (!UnsafeFPMath) {
540       setOperationAction(ISD::FSIN           , MVT::f80  , Expand);
541       setOperationAction(ISD::FCOS           , MVT::f80  , Expand);
542     }
543   }
544
545   // Always use a library call for pow.
546   setOperationAction(ISD::FPOW             , MVT::f32  , Expand);
547   setOperationAction(ISD::FPOW             , MVT::f64  , Expand);
548   setOperationAction(ISD::FPOW             , MVT::f80  , Expand);
549
550   setOperationAction(ISD::FLOG, MVT::f80, Expand);
551   setOperationAction(ISD::FLOG2, MVT::f80, Expand);
552   setOperationAction(ISD::FLOG10, MVT::f80, Expand);
553   setOperationAction(ISD::FEXP, MVT::f80, Expand);
554   setOperationAction(ISD::FEXP2, MVT::f80, Expand);
555
556   // First set operation action for all vector types to either promote
557   // (for widening) or expand (for scalarization). Then we will selectively
558   // turn on ones that can be effectively codegen'd.
559   for (unsigned VT = (unsigned)MVT::FIRST_VECTOR_VALUETYPE;
560        VT <= (unsigned)MVT::LAST_VECTOR_VALUETYPE; ++VT) {
561     setOperationAction(ISD::ADD , (MVT::SimpleValueType)VT, Expand);
562     setOperationAction(ISD::SUB , (MVT::SimpleValueType)VT, Expand);
563     setOperationAction(ISD::FADD, (MVT::SimpleValueType)VT, Expand);
564     setOperationAction(ISD::FNEG, (MVT::SimpleValueType)VT, Expand);
565     setOperationAction(ISD::FSUB, (MVT::SimpleValueType)VT, Expand);
566     setOperationAction(ISD::MUL , (MVT::SimpleValueType)VT, Expand);
567     setOperationAction(ISD::FMUL, (MVT::SimpleValueType)VT, Expand);
568     setOperationAction(ISD::SDIV, (MVT::SimpleValueType)VT, Expand);
569     setOperationAction(ISD::UDIV, (MVT::SimpleValueType)VT, Expand);
570     setOperationAction(ISD::FDIV, (MVT::SimpleValueType)VT, Expand);
571     setOperationAction(ISD::SREM, (MVT::SimpleValueType)VT, Expand);
572     setOperationAction(ISD::UREM, (MVT::SimpleValueType)VT, Expand);
573     setOperationAction(ISD::LOAD, (MVT::SimpleValueType)VT, Expand);
574     setOperationAction(ISD::VECTOR_SHUFFLE, (MVT::SimpleValueType)VT, Expand);
575     setOperationAction(ISD::EXTRACT_VECTOR_ELT,(MVT::SimpleValueType)VT,Expand);
576     setOperationAction(ISD::EXTRACT_SUBVECTOR,(MVT::SimpleValueType)VT,Expand);
577     setOperationAction(ISD::INSERT_VECTOR_ELT,(MVT::SimpleValueType)VT, Expand);
578     setOperationAction(ISD::FABS, (MVT::SimpleValueType)VT, Expand);
579     setOperationAction(ISD::FSIN, (MVT::SimpleValueType)VT, Expand);
580     setOperationAction(ISD::FCOS, (MVT::SimpleValueType)VT, Expand);
581     setOperationAction(ISD::FREM, (MVT::SimpleValueType)VT, Expand);
582     setOperationAction(ISD::FPOWI, (MVT::SimpleValueType)VT, Expand);
583     setOperationAction(ISD::FSQRT, (MVT::SimpleValueType)VT, Expand);
584     setOperationAction(ISD::FCOPYSIGN, (MVT::SimpleValueType)VT, Expand);
585     setOperationAction(ISD::SMUL_LOHI, (MVT::SimpleValueType)VT, Expand);
586     setOperationAction(ISD::UMUL_LOHI, (MVT::SimpleValueType)VT, Expand);
587     setOperationAction(ISD::SDIVREM, (MVT::SimpleValueType)VT, Expand);
588     setOperationAction(ISD::UDIVREM, (MVT::SimpleValueType)VT, Expand);
589     setOperationAction(ISD::FPOW, (MVT::SimpleValueType)VT, Expand);
590     setOperationAction(ISD::CTPOP, (MVT::SimpleValueType)VT, Expand);
591     setOperationAction(ISD::CTTZ, (MVT::SimpleValueType)VT, Expand);
592     setOperationAction(ISD::CTLZ, (MVT::SimpleValueType)VT, Expand);
593     setOperationAction(ISD::SHL, (MVT::SimpleValueType)VT, Expand);
594     setOperationAction(ISD::SRA, (MVT::SimpleValueType)VT, Expand);
595     setOperationAction(ISD::SRL, (MVT::SimpleValueType)VT, Expand);
596     setOperationAction(ISD::ROTL, (MVT::SimpleValueType)VT, Expand);
597     setOperationAction(ISD::ROTR, (MVT::SimpleValueType)VT, Expand);
598     setOperationAction(ISD::BSWAP, (MVT::SimpleValueType)VT, Expand);
599     setOperationAction(ISD::VSETCC, (MVT::SimpleValueType)VT, Expand);
600     setOperationAction(ISD::FLOG, (MVT::SimpleValueType)VT, Expand);
601     setOperationAction(ISD::FLOG2, (MVT::SimpleValueType)VT, Expand);
602     setOperationAction(ISD::FLOG10, (MVT::SimpleValueType)VT, Expand);
603     setOperationAction(ISD::FEXP, (MVT::SimpleValueType)VT, Expand);
604     setOperationAction(ISD::FEXP2, (MVT::SimpleValueType)VT, Expand);
605     setOperationAction(ISD::FP_TO_UINT, (MVT::SimpleValueType)VT, Expand);
606     setOperationAction(ISD::FP_TO_SINT, (MVT::SimpleValueType)VT, Expand);
607     setOperationAction(ISD::UINT_TO_FP, (MVT::SimpleValueType)VT, Expand);
608     setOperationAction(ISD::SINT_TO_FP, (MVT::SimpleValueType)VT, Expand);
609     setOperationAction(ISD::SIGN_EXTEND_INREG, (MVT::SimpleValueType)VT,Expand);
610     setOperationAction(ISD::TRUNCATE,  (MVT::SimpleValueType)VT, Expand);
611     setOperationAction(ISD::SIGN_EXTEND,  (MVT::SimpleValueType)VT, Expand);
612     setOperationAction(ISD::ZERO_EXTEND,  (MVT::SimpleValueType)VT, Expand);
613     setOperationAction(ISD::ANY_EXTEND,  (MVT::SimpleValueType)VT, Expand);
614     for (unsigned InnerVT = (unsigned)MVT::FIRST_VECTOR_VALUETYPE;
615          InnerVT <= (unsigned)MVT::LAST_VECTOR_VALUETYPE; ++InnerVT)
616       setTruncStoreAction((MVT::SimpleValueType)VT,
617                           (MVT::SimpleValueType)InnerVT, Expand);
618     setLoadExtAction(ISD::SEXTLOAD, (MVT::SimpleValueType)VT, Expand);
619     setLoadExtAction(ISD::ZEXTLOAD, (MVT::SimpleValueType)VT, Expand);
620     setLoadExtAction(ISD::EXTLOAD, (MVT::SimpleValueType)VT, Expand);
621   }
622
623   // FIXME: In order to prevent SSE instructions being expanded to MMX ones
624   // with -msoft-float, disable use of MMX as well.
625   if (!UseSoftFloat && !DisableMMX && Subtarget->hasMMX()) {
626     addRegisterClass(MVT::v8i8,  X86::VR64RegisterClass, false);
627     addRegisterClass(MVT::v4i16, X86::VR64RegisterClass, false);
628     addRegisterClass(MVT::v2i32, X86::VR64RegisterClass, false);
629     addRegisterClass(MVT::v2f32, X86::VR64RegisterClass, false);
630     addRegisterClass(MVT::v1i64, X86::VR64RegisterClass, false);
631
632     setOperationAction(ISD::ADD,                MVT::v8i8,  Legal);
633     setOperationAction(ISD::ADD,                MVT::v4i16, Legal);
634     setOperationAction(ISD::ADD,                MVT::v2i32, Legal);
635     setOperationAction(ISD::ADD,                MVT::v1i64, Legal);
636
637     setOperationAction(ISD::SUB,                MVT::v8i8,  Legal);
638     setOperationAction(ISD::SUB,                MVT::v4i16, Legal);
639     setOperationAction(ISD::SUB,                MVT::v2i32, Legal);
640     setOperationAction(ISD::SUB,                MVT::v1i64, Legal);
641
642     setOperationAction(ISD::MULHS,              MVT::v4i16, Legal);
643     setOperationAction(ISD::MUL,                MVT::v4i16, Legal);
644
645     setOperationAction(ISD::AND,                MVT::v8i8,  Promote);
646     AddPromotedToType (ISD::AND,                MVT::v8i8,  MVT::v1i64);
647     setOperationAction(ISD::AND,                MVT::v4i16, Promote);
648     AddPromotedToType (ISD::AND,                MVT::v4i16, MVT::v1i64);
649     setOperationAction(ISD::AND,                MVT::v2i32, Promote);
650     AddPromotedToType (ISD::AND,                MVT::v2i32, MVT::v1i64);
651     setOperationAction(ISD::AND,                MVT::v1i64, Legal);
652
653     setOperationAction(ISD::OR,                 MVT::v8i8,  Promote);
654     AddPromotedToType (ISD::OR,                 MVT::v8i8,  MVT::v1i64);
655     setOperationAction(ISD::OR,                 MVT::v4i16, Promote);
656     AddPromotedToType (ISD::OR,                 MVT::v4i16, MVT::v1i64);
657     setOperationAction(ISD::OR,                 MVT::v2i32, Promote);
658     AddPromotedToType (ISD::OR,                 MVT::v2i32, MVT::v1i64);
659     setOperationAction(ISD::OR,                 MVT::v1i64, Legal);
660
661     setOperationAction(ISD::XOR,                MVT::v8i8,  Promote);
662     AddPromotedToType (ISD::XOR,                MVT::v8i8,  MVT::v1i64);
663     setOperationAction(ISD::XOR,                MVT::v4i16, Promote);
664     AddPromotedToType (ISD::XOR,                MVT::v4i16, MVT::v1i64);
665     setOperationAction(ISD::XOR,                MVT::v2i32, Promote);
666     AddPromotedToType (ISD::XOR,                MVT::v2i32, MVT::v1i64);
667     setOperationAction(ISD::XOR,                MVT::v1i64, Legal);
668
669     setOperationAction(ISD::LOAD,               MVT::v8i8,  Promote);
670     AddPromotedToType (ISD::LOAD,               MVT::v8i8,  MVT::v1i64);
671     setOperationAction(ISD::LOAD,               MVT::v4i16, Promote);
672     AddPromotedToType (ISD::LOAD,               MVT::v4i16, MVT::v1i64);
673     setOperationAction(ISD::LOAD,               MVT::v2i32, Promote);
674     AddPromotedToType (ISD::LOAD,               MVT::v2i32, MVT::v1i64);
675     setOperationAction(ISD::LOAD,               MVT::v2f32, Promote);
676     AddPromotedToType (ISD::LOAD,               MVT::v2f32, MVT::v1i64);
677     setOperationAction(ISD::LOAD,               MVT::v1i64, Legal);
678
679     setOperationAction(ISD::BUILD_VECTOR,       MVT::v8i8,  Custom);
680     setOperationAction(ISD::BUILD_VECTOR,       MVT::v4i16, Custom);
681     setOperationAction(ISD::BUILD_VECTOR,       MVT::v2i32, Custom);
682     setOperationAction(ISD::BUILD_VECTOR,       MVT::v2f32, Custom);
683     setOperationAction(ISD::BUILD_VECTOR,       MVT::v1i64, Custom);
684
685     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v8i8,  Custom);
686     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v4i16, Custom);
687     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v2i32, Custom);
688     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v1i64, Custom);
689
690     setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v2f32, Custom);
691     setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v8i8,  Custom);
692     setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v4i16, Custom);
693     setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v1i64, Custom);
694
695     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4i16, Custom);
696
697     setOperationAction(ISD::SELECT,             MVT::v8i8, Promote);
698     setOperationAction(ISD::SELECT,             MVT::v4i16, Promote);
699     setOperationAction(ISD::SELECT,             MVT::v2i32, Promote);
700     setOperationAction(ISD::SELECT,             MVT::v1i64, Custom);
701     setOperationAction(ISD::VSETCC,             MVT::v8i8, Custom);
702     setOperationAction(ISD::VSETCC,             MVT::v4i16, Custom);
703     setOperationAction(ISD::VSETCC,             MVT::v2i32, Custom);
704   }
705
706   if (!UseSoftFloat && Subtarget->hasSSE1()) {
707     addRegisterClass(MVT::v4f32, X86::VR128RegisterClass);
708
709     setOperationAction(ISD::FADD,               MVT::v4f32, Legal);
710     setOperationAction(ISD::FSUB,               MVT::v4f32, Legal);
711     setOperationAction(ISD::FMUL,               MVT::v4f32, Legal);
712     setOperationAction(ISD::FDIV,               MVT::v4f32, Legal);
713     setOperationAction(ISD::FSQRT,              MVT::v4f32, Legal);
714     setOperationAction(ISD::FNEG,               MVT::v4f32, Custom);
715     setOperationAction(ISD::LOAD,               MVT::v4f32, Legal);
716     setOperationAction(ISD::BUILD_VECTOR,       MVT::v4f32, Custom);
717     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v4f32, Custom);
718     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
719     setOperationAction(ISD::SELECT,             MVT::v4f32, Custom);
720     setOperationAction(ISD::VSETCC,             MVT::v4f32, Custom);
721   }
722
723   if (!UseSoftFloat && Subtarget->hasSSE2()) {
724     addRegisterClass(MVT::v2f64, X86::VR128RegisterClass);
725
726     // FIXME: Unfortunately -soft-float and -no-implicit-float means XMM
727     // registers cannot be used even for integer operations.
728     addRegisterClass(MVT::v16i8, X86::VR128RegisterClass);
729     addRegisterClass(MVT::v8i16, X86::VR128RegisterClass);
730     addRegisterClass(MVT::v4i32, X86::VR128RegisterClass);
731     addRegisterClass(MVT::v2i64, X86::VR128RegisterClass);
732
733     setOperationAction(ISD::ADD,                MVT::v16i8, Legal);
734     setOperationAction(ISD::ADD,                MVT::v8i16, Legal);
735     setOperationAction(ISD::ADD,                MVT::v4i32, Legal);
736     setOperationAction(ISD::ADD,                MVT::v2i64, Legal);
737     setOperationAction(ISD::MUL,                MVT::v2i64, Custom);
738     setOperationAction(ISD::SUB,                MVT::v16i8, Legal);
739     setOperationAction(ISD::SUB,                MVT::v8i16, Legal);
740     setOperationAction(ISD::SUB,                MVT::v4i32, Legal);
741     setOperationAction(ISD::SUB,                MVT::v2i64, Legal);
742     setOperationAction(ISD::MUL,                MVT::v8i16, Legal);
743     setOperationAction(ISD::FADD,               MVT::v2f64, Legal);
744     setOperationAction(ISD::FSUB,               MVT::v2f64, Legal);
745     setOperationAction(ISD::FMUL,               MVT::v2f64, Legal);
746     setOperationAction(ISD::FDIV,               MVT::v2f64, Legal);
747     setOperationAction(ISD::FSQRT,              MVT::v2f64, Legal);
748     setOperationAction(ISD::FNEG,               MVT::v2f64, Custom);
749
750     setOperationAction(ISD::VSETCC,             MVT::v2f64, Custom);
751     setOperationAction(ISD::VSETCC,             MVT::v16i8, Custom);
752     setOperationAction(ISD::VSETCC,             MVT::v8i16, Custom);
753     setOperationAction(ISD::VSETCC,             MVT::v4i32, Custom);
754
755     setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v16i8, Custom);
756     setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v8i16, Custom);
757     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v8i16, Custom);
758     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4i32, Custom);
759     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4f32, Custom);
760
761     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v2f64, Custom);
762     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v2i64, Custom);
763     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v16i8, Custom);
764     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v8i16, Custom);
765     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v4i32, Custom);
766
767     // Custom lower build_vector, vector_shuffle, and extract_vector_elt.
768     for (unsigned i = (unsigned)MVT::v16i8; i != (unsigned)MVT::v2i64; ++i) {
769       EVT VT = (MVT::SimpleValueType)i;
770       // Do not attempt to custom lower non-power-of-2 vectors
771       if (!isPowerOf2_32(VT.getVectorNumElements()))
772         continue;
773       // Do not attempt to custom lower non-128-bit vectors
774       if (!VT.is128BitVector())
775         continue;
776       setOperationAction(ISD::BUILD_VECTOR,
777                          VT.getSimpleVT().SimpleTy, Custom);
778       setOperationAction(ISD::VECTOR_SHUFFLE,
779                          VT.getSimpleVT().SimpleTy, Custom);
780       setOperationAction(ISD::EXTRACT_VECTOR_ELT,
781                          VT.getSimpleVT().SimpleTy, Custom);
782     }
783
784     setOperationAction(ISD::BUILD_VECTOR,       MVT::v2f64, Custom);
785     setOperationAction(ISD::BUILD_VECTOR,       MVT::v2i64, Custom);
786     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v2f64, Custom);
787     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v2i64, Custom);
788     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2f64, Custom);
789     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Custom);
790
791     if (Subtarget->is64Bit()) {
792       setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2i64, Custom);
793       setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
794     }
795
796     // Promote v16i8, v8i16, v4i32 load, select, and, or, xor to v2i64.
797     for (unsigned i = (unsigned)MVT::v16i8; i != (unsigned)MVT::v2i64; i++) {
798       MVT::SimpleValueType SVT = (MVT::SimpleValueType)i;
799       EVT VT = SVT;
800
801       // Do not attempt to promote non-128-bit vectors
802       if (!VT.is128BitVector()) {
803         continue;
804       }
805       
806       setOperationAction(ISD::AND,    SVT, Promote);
807       AddPromotedToType (ISD::AND,    SVT, MVT::v2i64);
808       setOperationAction(ISD::OR,     SVT, Promote);
809       AddPromotedToType (ISD::OR,     SVT, MVT::v2i64);
810       setOperationAction(ISD::XOR,    SVT, Promote);
811       AddPromotedToType (ISD::XOR,    SVT, MVT::v2i64);
812       setOperationAction(ISD::LOAD,   SVT, Promote);
813       AddPromotedToType (ISD::LOAD,   SVT, MVT::v2i64);
814       setOperationAction(ISD::SELECT, SVT, Promote);
815       AddPromotedToType (ISD::SELECT, SVT, MVT::v2i64);
816     }
817
818     setTruncStoreAction(MVT::f64, MVT::f32, Expand);
819
820     // Custom lower v2i64 and v2f64 selects.
821     setOperationAction(ISD::LOAD,               MVT::v2f64, Legal);
822     setOperationAction(ISD::LOAD,               MVT::v2i64, Legal);
823     setOperationAction(ISD::SELECT,             MVT::v2f64, Custom);
824     setOperationAction(ISD::SELECT,             MVT::v2i64, Custom);
825
826     setOperationAction(ISD::FP_TO_SINT,         MVT::v4i32, Legal);
827     setOperationAction(ISD::SINT_TO_FP,         MVT::v4i32, Legal);
828     if (!DisableMMX && Subtarget->hasMMX()) {
829       setOperationAction(ISD::FP_TO_SINT,         MVT::v2i32, Custom);
830       setOperationAction(ISD::SINT_TO_FP,         MVT::v2i32, Custom);
831     }
832   }
833
834   if (Subtarget->hasSSE41()) {
835     // FIXME: Do we need to handle scalar-to-vector here?
836     setOperationAction(ISD::MUL,                MVT::v4i32, Legal);
837
838     // i8 and i16 vectors are custom , because the source register and source
839     // source memory operand types are not the same width.  f32 vectors are
840     // custom since the immediate controlling the insert encodes additional
841     // information.
842     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v16i8, Custom);
843     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v8i16, Custom);
844     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4i32, Custom);
845     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4f32, Custom);
846
847     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i8, Custom);
848     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i16, Custom);
849     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i32, Custom);
850     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
851
852     if (Subtarget->is64Bit()) {
853       setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2i64, Legal);
854       setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Legal);
855     }
856   }
857
858   if (Subtarget->hasSSE42()) {
859     setOperationAction(ISD::VSETCC,             MVT::v2i64, Custom);
860   }
861
862   if (!UseSoftFloat && Subtarget->hasAVX()) {
863     addRegisterClass(MVT::v8f32, X86::VR256RegisterClass);
864     addRegisterClass(MVT::v4f64, X86::VR256RegisterClass);
865     addRegisterClass(MVT::v8i32, X86::VR256RegisterClass);
866     addRegisterClass(MVT::v4i64, X86::VR256RegisterClass);
867
868     setOperationAction(ISD::LOAD,               MVT::v8f32, Legal);
869     setOperationAction(ISD::LOAD,               MVT::v8i32, Legal);
870     setOperationAction(ISD::LOAD,               MVT::v4f64, Legal);
871     setOperationAction(ISD::LOAD,               MVT::v4i64, Legal);
872     setOperationAction(ISD::FADD,               MVT::v8f32, Legal);
873     setOperationAction(ISD::FSUB,               MVT::v8f32, Legal);
874     setOperationAction(ISD::FMUL,               MVT::v8f32, Legal);
875     setOperationAction(ISD::FDIV,               MVT::v8f32, Legal);
876     setOperationAction(ISD::FSQRT,              MVT::v8f32, Legal);
877     setOperationAction(ISD::FNEG,               MVT::v8f32, Custom);
878     //setOperationAction(ISD::BUILD_VECTOR,       MVT::v8f32, Custom);
879     //setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v8f32, Custom);
880     //setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8f32, Custom);
881     //setOperationAction(ISD::SELECT,             MVT::v8f32, Custom);
882     //setOperationAction(ISD::VSETCC,             MVT::v8f32, Custom);
883
884     // Operations to consider commented out -v16i16 v32i8
885     //setOperationAction(ISD::ADD,                MVT::v16i16, Legal);
886     setOperationAction(ISD::ADD,                MVT::v8i32, Custom);
887     setOperationAction(ISD::ADD,                MVT::v4i64, Custom);
888     //setOperationAction(ISD::SUB,                MVT::v32i8, Legal);
889     //setOperationAction(ISD::SUB,                MVT::v16i16, Legal);
890     setOperationAction(ISD::SUB,                MVT::v8i32, Custom);
891     setOperationAction(ISD::SUB,                MVT::v4i64, Custom);
892     //setOperationAction(ISD::MUL,                MVT::v16i16, Legal);
893     setOperationAction(ISD::FADD,               MVT::v4f64, Legal);
894     setOperationAction(ISD::FSUB,               MVT::v4f64, Legal);
895     setOperationAction(ISD::FMUL,               MVT::v4f64, Legal);
896     setOperationAction(ISD::FDIV,               MVT::v4f64, Legal);
897     setOperationAction(ISD::FSQRT,              MVT::v4f64, Legal);
898     setOperationAction(ISD::FNEG,               MVT::v4f64, Custom);
899
900     setOperationAction(ISD::VSETCC,             MVT::v4f64, Custom);
901     // setOperationAction(ISD::VSETCC,             MVT::v32i8, Custom);
902     // setOperationAction(ISD::VSETCC,             MVT::v16i16, Custom);
903     setOperationAction(ISD::VSETCC,             MVT::v8i32, Custom);
904
905     // setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v32i8, Custom);
906     // setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v16i16, Custom);
907     // setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v16i16, Custom);
908     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v8i32, Custom);
909     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v8f32, Custom);
910
911     setOperationAction(ISD::BUILD_VECTOR,       MVT::v4f64, Custom);
912     setOperationAction(ISD::BUILD_VECTOR,       MVT::v4i64, Custom);
913     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v4f64, Custom);
914     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v4i64, Custom);
915     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4f64, Custom);
916     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f64, Custom);
917
918 #if 0
919     // Not sure we want to do this since there are no 256-bit integer
920     // operations in AVX
921
922     // Custom lower build_vector, vector_shuffle, and extract_vector_elt.
923     // This includes 256-bit vectors
924     for (unsigned i = (unsigned)MVT::v16i8; i != (unsigned)MVT::v4i64; ++i) {
925       EVT VT = (MVT::SimpleValueType)i;
926
927       // Do not attempt to custom lower non-power-of-2 vectors
928       if (!isPowerOf2_32(VT.getVectorNumElements()))
929         continue;
930
931       setOperationAction(ISD::BUILD_VECTOR,       VT, Custom);
932       setOperationAction(ISD::VECTOR_SHUFFLE,     VT, Custom);
933       setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
934     }
935
936     if (Subtarget->is64Bit()) {
937       setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4i64, Custom);
938       setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i64, Custom);
939     }
940 #endif
941
942 #if 0
943     // Not sure we want to do this since there are no 256-bit integer
944     // operations in AVX
945
946     // Promote v32i8, v16i16, v8i32 load, select, and, or, xor to v4i64.
947     // Including 256-bit vectors
948     for (unsigned i = (unsigned)MVT::v16i8; i != (unsigned)MVT::v4i64; i++) {
949       EVT VT = (MVT::SimpleValueType)i;
950
951       if (!VT.is256BitVector()) {
952         continue;
953       }
954       setOperationAction(ISD::AND,    VT, Promote);
955       AddPromotedToType (ISD::AND,    VT, MVT::v4i64);
956       setOperationAction(ISD::OR,     VT, Promote);
957       AddPromotedToType (ISD::OR,     VT, MVT::v4i64);
958       setOperationAction(ISD::XOR,    VT, Promote);
959       AddPromotedToType (ISD::XOR,    VT, MVT::v4i64);
960       setOperationAction(ISD::LOAD,   VT, Promote);
961       AddPromotedToType (ISD::LOAD,   VT, MVT::v4i64);
962       setOperationAction(ISD::SELECT, VT, Promote);
963       AddPromotedToType (ISD::SELECT, VT, MVT::v4i64);
964     }
965
966     setTruncStoreAction(MVT::f64, MVT::f32, Expand);
967 #endif
968   }
969
970   // We want to custom lower some of our intrinsics.
971   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
972
973   // Add/Sub/Mul with overflow operations are custom lowered.
974   setOperationAction(ISD::SADDO, MVT::i32, Custom);
975   setOperationAction(ISD::SADDO, MVT::i64, Custom);
976   setOperationAction(ISD::UADDO, MVT::i32, Custom);
977   setOperationAction(ISD::UADDO, MVT::i64, Custom);
978   setOperationAction(ISD::SSUBO, MVT::i32, Custom);
979   setOperationAction(ISD::SSUBO, MVT::i64, Custom);
980   setOperationAction(ISD::USUBO, MVT::i32, Custom);
981   setOperationAction(ISD::USUBO, MVT::i64, Custom);
982   setOperationAction(ISD::SMULO, MVT::i32, Custom);
983   setOperationAction(ISD::SMULO, MVT::i64, Custom);
984
985   if (!Subtarget->is64Bit()) {
986     // These libcalls are not available in 32-bit.
987     setLibcallName(RTLIB::SHL_I128, 0);
988     setLibcallName(RTLIB::SRL_I128, 0);
989     setLibcallName(RTLIB::SRA_I128, 0);
990   }
991
992   // We have target-specific dag combine patterns for the following nodes:
993   setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
994   setTargetDAGCombine(ISD::EXTRACT_VECTOR_ELT);
995   setTargetDAGCombine(ISD::BUILD_VECTOR);
996   setTargetDAGCombine(ISD::SELECT);
997   setTargetDAGCombine(ISD::SHL);
998   setTargetDAGCombine(ISD::SRA);
999   setTargetDAGCombine(ISD::SRL);
1000   setTargetDAGCombine(ISD::OR);
1001   setTargetDAGCombine(ISD::STORE);
1002   setTargetDAGCombine(ISD::MEMBARRIER);
1003   setTargetDAGCombine(ISD::ZERO_EXTEND);
1004   if (Subtarget->is64Bit())
1005     setTargetDAGCombine(ISD::MUL);
1006
1007   computeRegisterProperties();
1008
1009   // FIXME: These should be based on subtarget info. Plus, the values should
1010   // be smaller when we are in optimizing for size mode.
1011   maxStoresPerMemset = 16; // For @llvm.memset -> sequence of stores
1012   maxStoresPerMemcpy = 8; // For @llvm.memcpy -> sequence of stores
1013   maxStoresPerMemmove = 3; // For @llvm.memmove -> sequence of stores
1014   setPrefLoopAlignment(16);
1015   benefitFromCodePlacementOpt = true;
1016 }
1017
1018
1019 MVT::SimpleValueType X86TargetLowering::getSetCCResultType(EVT VT) const {
1020   return MVT::i8;
1021 }
1022
1023
1024 /// getMaxByValAlign - Helper for getByValTypeAlignment to determine
1025 /// the desired ByVal argument alignment.
1026 static void getMaxByValAlign(const Type *Ty, unsigned &MaxAlign) {
1027   if (MaxAlign == 16)
1028     return;
1029   if (const VectorType *VTy = dyn_cast<VectorType>(Ty)) {
1030     if (VTy->getBitWidth() == 128)
1031       MaxAlign = 16;
1032   } else if (const ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
1033     unsigned EltAlign = 0;
1034     getMaxByValAlign(ATy->getElementType(), EltAlign);
1035     if (EltAlign > MaxAlign)
1036       MaxAlign = EltAlign;
1037   } else if (const StructType *STy = dyn_cast<StructType>(Ty)) {
1038     for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
1039       unsigned EltAlign = 0;
1040       getMaxByValAlign(STy->getElementType(i), EltAlign);
1041       if (EltAlign > MaxAlign)
1042         MaxAlign = EltAlign;
1043       if (MaxAlign == 16)
1044         break;
1045     }
1046   }
1047   return;
1048 }
1049
1050 /// getByValTypeAlignment - Return the desired alignment for ByVal aggregate
1051 /// function arguments in the caller parameter area. For X86, aggregates
1052 /// that contain SSE vectors are placed at 16-byte boundaries while the rest
1053 /// are at 4-byte boundaries.
1054 unsigned X86TargetLowering::getByValTypeAlignment(const Type *Ty) const {
1055   if (Subtarget->is64Bit()) {
1056     // Max of 8 and alignment of type.
1057     unsigned TyAlign = TD->getABITypeAlignment(Ty);
1058     if (TyAlign > 8)
1059       return TyAlign;
1060     return 8;
1061   }
1062
1063   unsigned Align = 4;
1064   if (Subtarget->hasSSE1())
1065     getMaxByValAlign(Ty, Align);
1066   return Align;
1067 }
1068
1069 /// getOptimalMemOpType - Returns the target specific optimal type for load
1070 /// and store operations as a result of memset, memcpy, and memmove
1071 /// lowering. If DstAlign is zero that means it's safe to destination
1072 /// alignment can satisfy any constraint. Similarly if SrcAlign is zero it
1073 /// means there isn't a need to check it against alignment requirement,
1074 /// probably because the source does not need to be loaded. If
1075 /// 'NonScalarIntSafe' is true, that means it's safe to return a
1076 /// non-scalar-integer type, e.g. empty string source, constant, or loaded
1077 /// from memory. 'MemcpyStrSrc' indicates whether the memcpy source is
1078 /// constant so it does not need to be loaded.
1079 /// It returns EVT::Other if the type should be determined using generic
1080 /// target-independent logic.
1081 EVT
1082 X86TargetLowering::getOptimalMemOpType(uint64_t Size,
1083                                        unsigned DstAlign, unsigned SrcAlign,
1084                                        bool NonScalarIntSafe,
1085                                        bool MemcpyStrSrc,
1086                                        MachineFunction &MF) const {
1087   // FIXME: This turns off use of xmm stores for memset/memcpy on targets like
1088   // linux.  This is because the stack realignment code can't handle certain
1089   // cases like PR2962.  This should be removed when PR2962 is fixed.
1090   const Function *F = MF.getFunction();
1091   if (NonScalarIntSafe &&
1092       !F->hasFnAttr(Attribute::NoImplicitFloat)) {
1093     if (Size >= 16 &&
1094         (Subtarget->isUnalignedMemAccessFast() ||
1095          ((DstAlign == 0 || DstAlign >= 16) &&
1096           (SrcAlign == 0 || SrcAlign >= 16))) &&
1097         Subtarget->getStackAlignment() >= 16) {
1098       if (Subtarget->hasSSE2())
1099         return MVT::v4i32;
1100       if (Subtarget->hasSSE1())
1101         return MVT::v4f32;
1102     } else if (!MemcpyStrSrc && Size >= 8 &&
1103                !Subtarget->is64Bit() &&
1104                Subtarget->getStackAlignment() >= 8 &&
1105                Subtarget->hasSSE2()) {
1106       // Do not use f64 to lower memcpy if source is string constant. It's
1107       // better to use i32 to avoid the loads.
1108       return MVT::f64;
1109     }
1110   }
1111   if (Subtarget->is64Bit() && Size >= 8)
1112     return MVT::i64;
1113   return MVT::i32;
1114 }
1115
1116 /// getJumpTableEncoding - Return the entry encoding for a jump table in the
1117 /// current function.  The returned value is a member of the
1118 /// MachineJumpTableInfo::JTEntryKind enum.
1119 unsigned X86TargetLowering::getJumpTableEncoding() const {
1120   // In GOT pic mode, each entry in the jump table is emitted as a @GOTOFF
1121   // symbol.
1122   if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1123       Subtarget->isPICStyleGOT())
1124     return MachineJumpTableInfo::EK_Custom32;
1125   
1126   // Otherwise, use the normal jump table encoding heuristics.
1127   return TargetLowering::getJumpTableEncoding();
1128 }
1129
1130 /// getPICBaseSymbol - Return the X86-32 PIC base.
1131 MCSymbol *
1132 X86TargetLowering::getPICBaseSymbol(const MachineFunction *MF,
1133                                     MCContext &Ctx) const {
1134   const MCAsmInfo &MAI = *getTargetMachine().getMCAsmInfo();
1135   return Ctx.GetOrCreateSymbol(Twine(MAI.getPrivateGlobalPrefix())+
1136                                Twine(MF->getFunctionNumber())+"$pb");
1137 }
1138
1139
1140 const MCExpr *
1141 X86TargetLowering::LowerCustomJumpTableEntry(const MachineJumpTableInfo *MJTI,
1142                                              const MachineBasicBlock *MBB,
1143                                              unsigned uid,MCContext &Ctx) const{
1144   assert(getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1145          Subtarget->isPICStyleGOT());
1146   // In 32-bit ELF systems, our jump table entries are formed with @GOTOFF
1147   // entries.
1148   return MCSymbolRefExpr::Create(MBB->getSymbol(),
1149                                  MCSymbolRefExpr::VK_GOTOFF, Ctx);
1150 }
1151
1152 /// getPICJumpTableRelocaBase - Returns relocation base for the given PIC
1153 /// jumptable.
1154 SDValue X86TargetLowering::getPICJumpTableRelocBase(SDValue Table,
1155                                                     SelectionDAG &DAG) const {
1156   if (!Subtarget->is64Bit())
1157     // This doesn't have DebugLoc associated with it, but is not really the
1158     // same as a Register.
1159     return DAG.getNode(X86ISD::GlobalBaseReg, DebugLoc(), getPointerTy());
1160   return Table;
1161 }
1162
1163 /// getPICJumpTableRelocBaseExpr - This returns the relocation base for the
1164 /// given PIC jumptable, the same as getPICJumpTableRelocBase, but as an
1165 /// MCExpr.
1166 const MCExpr *X86TargetLowering::
1167 getPICJumpTableRelocBaseExpr(const MachineFunction *MF, unsigned JTI,
1168                              MCContext &Ctx) const {
1169   // X86-64 uses RIP relative addressing based on the jump table label.
1170   if (Subtarget->isPICStyleRIPRel())
1171     return TargetLowering::getPICJumpTableRelocBaseExpr(MF, JTI, Ctx);
1172
1173   // Otherwise, the reference is relative to the PIC base.
1174   return MCSymbolRefExpr::Create(getPICBaseSymbol(MF, Ctx), Ctx);
1175 }
1176
1177 /// getFunctionAlignment - Return the Log2 alignment of this function.
1178 unsigned X86TargetLowering::getFunctionAlignment(const Function *F) const {
1179   return F->hasFnAttr(Attribute::OptimizeForSize) ? 0 : 4;
1180 }
1181
1182 //===----------------------------------------------------------------------===//
1183 //               Return Value Calling Convention Implementation
1184 //===----------------------------------------------------------------------===//
1185
1186 #include "X86GenCallingConv.inc"
1187
1188 bool 
1189 X86TargetLowering::CanLowerReturn(CallingConv::ID CallConv, bool isVarArg,
1190                         const SmallVectorImpl<EVT> &OutTys,
1191                         const SmallVectorImpl<ISD::ArgFlagsTy> &ArgsFlags,
1192                         SelectionDAG &DAG) const {
1193   SmallVector<CCValAssign, 16> RVLocs;
1194   CCState CCInfo(CallConv, isVarArg, getTargetMachine(),
1195                  RVLocs, *DAG.getContext());
1196   return CCInfo.CheckReturn(OutTys, ArgsFlags, RetCC_X86);
1197 }
1198
1199 SDValue
1200 X86TargetLowering::LowerReturn(SDValue Chain,
1201                                CallingConv::ID CallConv, bool isVarArg,
1202                                const SmallVectorImpl<ISD::OutputArg> &Outs,
1203                                DebugLoc dl, SelectionDAG &DAG) const {
1204   MachineFunction &MF = DAG.getMachineFunction();
1205   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1206
1207   SmallVector<CCValAssign, 16> RVLocs;
1208   CCState CCInfo(CallConv, isVarArg, getTargetMachine(),
1209                  RVLocs, *DAG.getContext());
1210   CCInfo.AnalyzeReturn(Outs, RetCC_X86);
1211
1212   // Add the regs to the liveout set for the function.
1213   MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo();
1214   for (unsigned i = 0; i != RVLocs.size(); ++i)
1215     if (RVLocs[i].isRegLoc() && !MRI.isLiveOut(RVLocs[i].getLocReg()))
1216       MRI.addLiveOut(RVLocs[i].getLocReg());
1217
1218   SDValue Flag;
1219
1220   SmallVector<SDValue, 6> RetOps;
1221   RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
1222   // Operand #1 = Bytes To Pop
1223   RetOps.push_back(DAG.getTargetConstant(FuncInfo->getBytesToPopOnReturn(),
1224                    MVT::i16));
1225
1226   // Copy the result values into the output registers.
1227   for (unsigned i = 0; i != RVLocs.size(); ++i) {
1228     CCValAssign &VA = RVLocs[i];
1229     assert(VA.isRegLoc() && "Can only return in registers!");
1230     SDValue ValToCopy = Outs[i].Val;
1231
1232     // Returns in ST0/ST1 are handled specially: these are pushed as operands to
1233     // the RET instruction and handled by the FP Stackifier.
1234     if (VA.getLocReg() == X86::ST0 ||
1235         VA.getLocReg() == X86::ST1) {
1236       // If this is a copy from an xmm register to ST(0), use an FPExtend to
1237       // change the value to the FP stack register class.
1238       if (isScalarFPTypeInSSEReg(VA.getValVT()))
1239         ValToCopy = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f80, ValToCopy);
1240       RetOps.push_back(ValToCopy);
1241       // Don't emit a copytoreg.
1242       continue;
1243     }
1244
1245     // 64-bit vector (MMX) values are returned in XMM0 / XMM1 except for v1i64
1246     // which is returned in RAX / RDX.
1247     if (Subtarget->is64Bit()) {
1248       EVT ValVT = ValToCopy.getValueType();
1249       if (ValVT.isVector() && ValVT.getSizeInBits() == 64) {
1250         ValToCopy = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::i64, ValToCopy);
1251         if (VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1)
1252           ValToCopy = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64, ValToCopy);
1253       }
1254     }
1255
1256     Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), ValToCopy, Flag);
1257     Flag = Chain.getValue(1);
1258   }
1259
1260   // The x86-64 ABI for returning structs by value requires that we copy
1261   // the sret argument into %rax for the return. We saved the argument into
1262   // a virtual register in the entry block, so now we copy the value out
1263   // and into %rax.
1264   if (Subtarget->is64Bit() &&
1265       DAG.getMachineFunction().getFunction()->hasStructRetAttr()) {
1266     MachineFunction &MF = DAG.getMachineFunction();
1267     X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1268     unsigned Reg = FuncInfo->getSRetReturnReg();
1269     if (!Reg) {
1270       Reg = MRI.createVirtualRegister(getRegClassFor(MVT::i64));
1271       FuncInfo->setSRetReturnReg(Reg);
1272     }
1273     SDValue Val = DAG.getCopyFromReg(Chain, dl, Reg, getPointerTy());
1274
1275     Chain = DAG.getCopyToReg(Chain, dl, X86::RAX, Val, Flag);
1276     Flag = Chain.getValue(1);
1277
1278     // RAX now acts like a return value.
1279     MRI.addLiveOut(X86::RAX);
1280   }
1281
1282   RetOps[0] = Chain;  // Update chain.
1283
1284   // Add the flag if we have it.
1285   if (Flag.getNode())
1286     RetOps.push_back(Flag);
1287
1288   return DAG.getNode(X86ISD::RET_FLAG, dl,
1289                      MVT::Other, &RetOps[0], RetOps.size());
1290 }
1291
1292 /// LowerCallResult - Lower the result values of a call into the
1293 /// appropriate copies out of appropriate physical registers.
1294 ///
1295 SDValue
1296 X86TargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
1297                                    CallingConv::ID CallConv, bool isVarArg,
1298                                    const SmallVectorImpl<ISD::InputArg> &Ins,
1299                                    DebugLoc dl, SelectionDAG &DAG,
1300                                    SmallVectorImpl<SDValue> &InVals) const {
1301
1302   // Assign locations to each value returned by this call.
1303   SmallVector<CCValAssign, 16> RVLocs;
1304   bool Is64Bit = Subtarget->is64Bit();
1305   CCState CCInfo(CallConv, isVarArg, getTargetMachine(),
1306                  RVLocs, *DAG.getContext());
1307   CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
1308
1309   // Copy all of the result registers out of their specified physreg.
1310   for (unsigned i = 0; i != RVLocs.size(); ++i) {
1311     CCValAssign &VA = RVLocs[i];
1312     EVT CopyVT = VA.getValVT();
1313
1314     // If this is x86-64, and we disabled SSE, we can't return FP values
1315     if ((CopyVT == MVT::f32 || CopyVT == MVT::f64) &&
1316         ((Is64Bit || Ins[i].Flags.isInReg()) && !Subtarget->hasSSE1())) {
1317       report_fatal_error("SSE register return with SSE disabled");
1318     }
1319
1320     // If this is a call to a function that returns an fp value on the floating
1321     // point stack, but where we prefer to use the value in xmm registers, copy
1322     // it out as F80 and use a truncate to move it from fp stack reg to xmm reg.
1323     if ((VA.getLocReg() == X86::ST0 ||
1324          VA.getLocReg() == X86::ST1) &&
1325         isScalarFPTypeInSSEReg(VA.getValVT())) {
1326       CopyVT = MVT::f80;
1327     }
1328
1329     SDValue Val;
1330     if (Is64Bit && CopyVT.isVector() && CopyVT.getSizeInBits() == 64) {
1331       // For x86-64, MMX values are returned in XMM0 / XMM1 except for v1i64.
1332       if (VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) {
1333         Chain = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(),
1334                                    MVT::v2i64, InFlag).getValue(1);
1335         Val = Chain.getValue(0);
1336         Val = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i64,
1337                           Val, DAG.getConstant(0, MVT::i64));
1338       } else {
1339         Chain = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(),
1340                                    MVT::i64, InFlag).getValue(1);
1341         Val = Chain.getValue(0);
1342       }
1343       Val = DAG.getNode(ISD::BIT_CONVERT, dl, CopyVT, Val);
1344     } else {
1345       Chain = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(),
1346                                  CopyVT, InFlag).getValue(1);
1347       Val = Chain.getValue(0);
1348     }
1349     InFlag = Chain.getValue(2);
1350
1351     if (CopyVT != VA.getValVT()) {
1352       // Round the F80 the right size, which also moves to the appropriate xmm
1353       // register.
1354       Val = DAG.getNode(ISD::FP_ROUND, dl, VA.getValVT(), Val,
1355                         // This truncation won't change the value.
1356                         DAG.getIntPtrConstant(1));
1357     }
1358
1359     InVals.push_back(Val);
1360   }
1361
1362   return Chain;
1363 }
1364
1365
1366 //===----------------------------------------------------------------------===//
1367 //                C & StdCall & Fast Calling Convention implementation
1368 //===----------------------------------------------------------------------===//
1369 //  StdCall calling convention seems to be standard for many Windows' API
1370 //  routines and around. It differs from C calling convention just a little:
1371 //  callee should clean up the stack, not caller. Symbols should be also
1372 //  decorated in some fancy way :) It doesn't support any vector arguments.
1373 //  For info on fast calling convention see Fast Calling Convention (tail call)
1374 //  implementation LowerX86_32FastCCCallTo.
1375
1376 /// CallIsStructReturn - Determines whether a call uses struct return
1377 /// semantics.
1378 static bool CallIsStructReturn(const SmallVectorImpl<ISD::OutputArg> &Outs) {
1379   if (Outs.empty())
1380     return false;
1381
1382   return Outs[0].Flags.isSRet();
1383 }
1384
1385 /// ArgsAreStructReturn - Determines whether a function uses struct
1386 /// return semantics.
1387 static bool
1388 ArgsAreStructReturn(const SmallVectorImpl<ISD::InputArg> &Ins) {
1389   if (Ins.empty())
1390     return false;
1391
1392   return Ins[0].Flags.isSRet();
1393 }
1394
1395 /// IsCalleePop - Determines whether the callee is required to pop its
1396 /// own arguments. Callee pop is necessary to support tail calls.
1397 bool X86TargetLowering::IsCalleePop(bool IsVarArg,
1398                                     CallingConv::ID CallingConv) const {
1399   if (IsVarArg)
1400     return false;
1401
1402   switch (CallingConv) {
1403   default:
1404     return false;
1405   case CallingConv::X86_StdCall:
1406     return !Subtarget->is64Bit();
1407   case CallingConv::X86_FastCall:
1408     return !Subtarget->is64Bit();
1409   case CallingConv::Fast:
1410     return GuaranteedTailCallOpt;
1411   case CallingConv::GHC:
1412     return GuaranteedTailCallOpt;
1413   }
1414 }
1415
1416 /// CCAssignFnForNode - Selects the correct CCAssignFn for a the
1417 /// given CallingConvention value.
1418 CCAssignFn *X86TargetLowering::CCAssignFnForNode(CallingConv::ID CC) const {
1419   if (Subtarget->is64Bit()) {
1420     if (CC == CallingConv::GHC)
1421       return CC_X86_64_GHC;
1422     else if (Subtarget->isTargetWin64())
1423       return CC_X86_Win64_C;
1424     else
1425       return CC_X86_64_C;
1426   }
1427
1428   if (CC == CallingConv::X86_FastCall)
1429     return CC_X86_32_FastCall;
1430   else if (CC == CallingConv::Fast)
1431     return CC_X86_32_FastCC;
1432   else if (CC == CallingConv::GHC)
1433     return CC_X86_32_GHC;
1434   else
1435     return CC_X86_32_C;
1436 }
1437
1438 /// CreateCopyOfByValArgument - Make a copy of an aggregate at address specified
1439 /// by "Src" to address "Dst" with size and alignment information specified by
1440 /// the specific parameter attribute. The copy will be passed as a byval
1441 /// function parameter.
1442 static SDValue
1443 CreateCopyOfByValArgument(SDValue Src, SDValue Dst, SDValue Chain,
1444                           ISD::ArgFlagsTy Flags, SelectionDAG &DAG,
1445                           DebugLoc dl) {
1446   SDValue SizeNode     = DAG.getConstant(Flags.getByValSize(), MVT::i32);
1447   return DAG.getMemcpy(Chain, dl, Dst, Src, SizeNode, Flags.getByValAlign(),
1448                        /*isVolatile*/false, /*AlwaysInline=*/true,
1449                        NULL, 0, NULL, 0);
1450 }
1451
1452 /// IsTailCallConvention - Return true if the calling convention is one that
1453 /// supports tail call optimization.
1454 static bool IsTailCallConvention(CallingConv::ID CC) {
1455   return (CC == CallingConv::Fast || CC == CallingConv::GHC);
1456 }
1457
1458 /// FuncIsMadeTailCallSafe - Return true if the function is being made into
1459 /// a tailcall target by changing its ABI.
1460 static bool FuncIsMadeTailCallSafe(CallingConv::ID CC) {
1461   return GuaranteedTailCallOpt && IsTailCallConvention(CC);
1462 }
1463
1464 SDValue
1465 X86TargetLowering::LowerMemArgument(SDValue Chain,
1466                                     CallingConv::ID CallConv,
1467                                     const SmallVectorImpl<ISD::InputArg> &Ins,
1468                                     DebugLoc dl, SelectionDAG &DAG,
1469                                     const CCValAssign &VA,
1470                                     MachineFrameInfo *MFI,
1471                                     unsigned i) const {
1472   // Create the nodes corresponding to a load from this parameter slot.
1473   ISD::ArgFlagsTy Flags = Ins[i].Flags;
1474   bool AlwaysUseMutable = FuncIsMadeTailCallSafe(CallConv);
1475   bool isImmutable = !AlwaysUseMutable && !Flags.isByVal();
1476   EVT ValVT;
1477
1478   // If value is passed by pointer we have address passed instead of the value
1479   // itself.
1480   if (VA.getLocInfo() == CCValAssign::Indirect)
1481     ValVT = VA.getLocVT();
1482   else
1483     ValVT = VA.getValVT();
1484
1485   // FIXME: For now, all byval parameter objects are marked mutable. This can be
1486   // changed with more analysis.
1487   // In case of tail call optimization mark all arguments mutable. Since they
1488   // could be overwritten by lowering of arguments in case of a tail call.
1489   if (Flags.isByVal()) {
1490     int FI = MFI->CreateFixedObject(Flags.getByValSize(),
1491                                     VA.getLocMemOffset(), isImmutable, false);
1492     return DAG.getFrameIndex(FI, getPointerTy());
1493   } else {
1494     int FI = MFI->CreateFixedObject(ValVT.getSizeInBits()/8,
1495                                     VA.getLocMemOffset(), isImmutable, false);
1496     SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
1497     return DAG.getLoad(ValVT, dl, Chain, FIN,
1498                        PseudoSourceValue::getFixedStack(FI), 0,
1499                        false, false, 0);
1500   }
1501 }
1502
1503 SDValue
1504 X86TargetLowering::LowerFormalArguments(SDValue Chain,
1505                                         CallingConv::ID CallConv,
1506                                         bool isVarArg,
1507                                       const SmallVectorImpl<ISD::InputArg> &Ins,
1508                                         DebugLoc dl,
1509                                         SelectionDAG &DAG,
1510                                         SmallVectorImpl<SDValue> &InVals)
1511                                           const {
1512   MachineFunction &MF = DAG.getMachineFunction();
1513   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1514
1515   const Function* Fn = MF.getFunction();
1516   if (Fn->hasExternalLinkage() &&
1517       Subtarget->isTargetCygMing() &&
1518       Fn->getName() == "main")
1519     FuncInfo->setForceFramePointer(true);
1520
1521   MachineFrameInfo *MFI = MF.getFrameInfo();
1522   bool Is64Bit = Subtarget->is64Bit();
1523   bool IsWin64 = Subtarget->isTargetWin64();
1524
1525   assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
1526          "Var args not supported with calling convention fastcc or ghc");
1527
1528   // Assign locations to all of the incoming arguments.
1529   SmallVector<CCValAssign, 16> ArgLocs;
1530   CCState CCInfo(CallConv, isVarArg, getTargetMachine(),
1531                  ArgLocs, *DAG.getContext());
1532   CCInfo.AnalyzeFormalArguments(Ins, CCAssignFnForNode(CallConv));
1533
1534   unsigned LastVal = ~0U;
1535   SDValue ArgValue;
1536   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
1537     CCValAssign &VA = ArgLocs[i];
1538     // TODO: If an arg is passed in two places (e.g. reg and stack), skip later
1539     // places.
1540     assert(VA.getValNo() != LastVal &&
1541            "Don't support value assigned to multiple locs yet");
1542     LastVal = VA.getValNo();
1543
1544     if (VA.isRegLoc()) {
1545       EVT RegVT = VA.getLocVT();
1546       TargetRegisterClass *RC = NULL;
1547       if (RegVT == MVT::i32)
1548         RC = X86::GR32RegisterClass;
1549       else if (Is64Bit && RegVT == MVT::i64)
1550         RC = X86::GR64RegisterClass;
1551       else if (RegVT == MVT::f32)
1552         RC = X86::FR32RegisterClass;
1553       else if (RegVT == MVT::f64)
1554         RC = X86::FR64RegisterClass;
1555       else if (RegVT.isVector() && RegVT.getSizeInBits() == 128)
1556         RC = X86::VR128RegisterClass;
1557       else if (RegVT.isVector() && RegVT.getSizeInBits() == 64)
1558         RC = X86::VR64RegisterClass;
1559       else
1560         llvm_unreachable("Unknown argument type!");
1561
1562       unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
1563       ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
1564
1565       // If this is an 8 or 16-bit value, it is really passed promoted to 32
1566       // bits.  Insert an assert[sz]ext to capture this, then truncate to the
1567       // right size.
1568       if (VA.getLocInfo() == CCValAssign::SExt)
1569         ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
1570                                DAG.getValueType(VA.getValVT()));
1571       else if (VA.getLocInfo() == CCValAssign::ZExt)
1572         ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
1573                                DAG.getValueType(VA.getValVT()));
1574       else if (VA.getLocInfo() == CCValAssign::BCvt)
1575         ArgValue = DAG.getNode(ISD::BIT_CONVERT, dl, VA.getValVT(), ArgValue);
1576
1577       if (VA.isExtInLoc()) {
1578         // Handle MMX values passed in XMM regs.
1579         if (RegVT.isVector()) {
1580           ArgValue = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i64,
1581                                  ArgValue, DAG.getConstant(0, MVT::i64));
1582           ArgValue = DAG.getNode(ISD::BIT_CONVERT, dl, VA.getValVT(), ArgValue);
1583         } else
1584           ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
1585       }
1586     } else {
1587       assert(VA.isMemLoc());
1588       ArgValue = LowerMemArgument(Chain, CallConv, Ins, dl, DAG, VA, MFI, i);
1589     }
1590
1591     // If value is passed via pointer - do a load.
1592     if (VA.getLocInfo() == CCValAssign::Indirect)
1593       ArgValue = DAG.getLoad(VA.getValVT(), dl, Chain, ArgValue, NULL, 0,
1594                              false, false, 0);
1595
1596     InVals.push_back(ArgValue);
1597   }
1598
1599   // The x86-64 ABI for returning structs by value requires that we copy
1600   // the sret argument into %rax for the return. Save the argument into
1601   // a virtual register so that we can access it from the return points.
1602   if (Is64Bit && MF.getFunction()->hasStructRetAttr()) {
1603     X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1604     unsigned Reg = FuncInfo->getSRetReturnReg();
1605     if (!Reg) {
1606       Reg = MF.getRegInfo().createVirtualRegister(getRegClassFor(MVT::i64));
1607       FuncInfo->setSRetReturnReg(Reg);
1608     }
1609     SDValue Copy = DAG.getCopyToReg(DAG.getEntryNode(), dl, Reg, InVals[0]);
1610     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Copy, Chain);
1611   }
1612
1613   unsigned StackSize = CCInfo.getNextStackOffset();
1614   // Align stack specially for tail calls.
1615   if (FuncIsMadeTailCallSafe(CallConv))
1616     StackSize = GetAlignedArgumentStackSize(StackSize, DAG);
1617
1618   // If the function takes variable number of arguments, make a frame index for
1619   // the start of the first vararg value... for expansion of llvm.va_start.
1620   if (isVarArg) {
1621     if (Is64Bit || CallConv != CallingConv::X86_FastCall) {
1622       FuncInfo->setVarArgsFrameIndex(MFI->CreateFixedObject(1, StackSize,
1623                                                             true, false));
1624     }
1625     if (Is64Bit) {
1626       unsigned TotalNumIntRegs = 0, TotalNumXMMRegs = 0;
1627
1628       // FIXME: We should really autogenerate these arrays
1629       static const unsigned GPR64ArgRegsWin64[] = {
1630         X86::RCX, X86::RDX, X86::R8,  X86::R9
1631       };
1632       static const unsigned XMMArgRegsWin64[] = {
1633         X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3
1634       };
1635       static const unsigned GPR64ArgRegs64Bit[] = {
1636         X86::RDI, X86::RSI, X86::RDX, X86::RCX, X86::R8, X86::R9
1637       };
1638       static const unsigned XMMArgRegs64Bit[] = {
1639         X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
1640         X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
1641       };
1642       const unsigned *GPR64ArgRegs, *XMMArgRegs;
1643
1644       if (IsWin64) {
1645         TotalNumIntRegs = 4; TotalNumXMMRegs = 4;
1646         GPR64ArgRegs = GPR64ArgRegsWin64;
1647         XMMArgRegs = XMMArgRegsWin64;
1648       } else {
1649         TotalNumIntRegs = 6; TotalNumXMMRegs = 8;
1650         GPR64ArgRegs = GPR64ArgRegs64Bit;
1651         XMMArgRegs = XMMArgRegs64Bit;
1652       }
1653       unsigned NumIntRegs = CCInfo.getFirstUnallocated(GPR64ArgRegs,
1654                                                        TotalNumIntRegs);
1655       unsigned NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs,
1656                                                        TotalNumXMMRegs);
1657
1658       bool NoImplicitFloatOps = Fn->hasFnAttr(Attribute::NoImplicitFloat);
1659       assert(!(NumXMMRegs && !Subtarget->hasSSE1()) &&
1660              "SSE register cannot be used when SSE is disabled!");
1661       assert(!(NumXMMRegs && UseSoftFloat && NoImplicitFloatOps) &&
1662              "SSE register cannot be used when SSE is disabled!");
1663       if (UseSoftFloat || NoImplicitFloatOps || !Subtarget->hasSSE1())
1664         // Kernel mode asks for SSE to be disabled, so don't push them
1665         // on the stack.
1666         TotalNumXMMRegs = 0;
1667
1668       // For X86-64, if there are vararg parameters that are passed via
1669       // registers, then we must store them to their spots on the stack so they
1670       // may be loaded by deferencing the result of va_next.
1671       FuncInfo->setVarArgsGPOffset(NumIntRegs * 8);
1672       FuncInfo->setVarArgsFPOffset(TotalNumIntRegs * 8 + NumXMMRegs * 16);
1673       FuncInfo->setRegSaveFrameIndex(
1674         MFI->CreateStackObject(TotalNumIntRegs * 8 + TotalNumXMMRegs * 16, 16,
1675                                false));
1676
1677       // Store the integer parameter registers.
1678       SmallVector<SDValue, 8> MemOps;
1679       SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
1680                                         getPointerTy());
1681       unsigned Offset = FuncInfo->getVarArgsGPOffset();
1682       for (; NumIntRegs != TotalNumIntRegs; ++NumIntRegs) {
1683         SDValue FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(), RSFIN,
1684                                   DAG.getIntPtrConstant(Offset));
1685         unsigned VReg = MF.addLiveIn(GPR64ArgRegs[NumIntRegs],
1686                                      X86::GR64RegisterClass);
1687         SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
1688         SDValue Store =
1689           DAG.getStore(Val.getValue(1), dl, Val, FIN,
1690                        PseudoSourceValue::getFixedStack(
1691                          FuncInfo->getRegSaveFrameIndex()),
1692                        Offset, false, false, 0);
1693         MemOps.push_back(Store);
1694         Offset += 8;
1695       }
1696
1697       if (TotalNumXMMRegs != 0 && NumXMMRegs != TotalNumXMMRegs) {
1698         // Now store the XMM (fp + vector) parameter registers.
1699         SmallVector<SDValue, 11> SaveXMMOps;
1700         SaveXMMOps.push_back(Chain);
1701
1702         unsigned AL = MF.addLiveIn(X86::AL, X86::GR8RegisterClass);
1703         SDValue ALVal = DAG.getCopyFromReg(DAG.getEntryNode(), dl, AL, MVT::i8);
1704         SaveXMMOps.push_back(ALVal);
1705
1706         SaveXMMOps.push_back(DAG.getIntPtrConstant(
1707                                FuncInfo->getRegSaveFrameIndex()));
1708         SaveXMMOps.push_back(DAG.getIntPtrConstant(
1709                                FuncInfo->getVarArgsFPOffset()));
1710
1711         for (; NumXMMRegs != TotalNumXMMRegs; ++NumXMMRegs) {
1712           unsigned VReg = MF.addLiveIn(XMMArgRegs[NumXMMRegs],
1713                                        X86::VR128RegisterClass);
1714           SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::v4f32);
1715           SaveXMMOps.push_back(Val);
1716         }
1717         MemOps.push_back(DAG.getNode(X86ISD::VASTART_SAVE_XMM_REGS, dl,
1718                                      MVT::Other,
1719                                      &SaveXMMOps[0], SaveXMMOps.size()));
1720       }
1721
1722       if (!MemOps.empty())
1723         Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
1724                             &MemOps[0], MemOps.size());
1725     }
1726   }
1727
1728   // Some CCs need callee pop.
1729   if (IsCalleePop(isVarArg, CallConv)) {
1730     FuncInfo->setBytesToPopOnReturn(StackSize); // Callee pops everything.
1731   } else {
1732     FuncInfo->setBytesToPopOnReturn(0); // Callee pops nothing.
1733     // If this is an sret function, the return should pop the hidden pointer.
1734     if (!Is64Bit && !IsTailCallConvention(CallConv) && ArgsAreStructReturn(Ins))
1735       FuncInfo->setBytesToPopOnReturn(4);
1736   }
1737
1738   if (!Is64Bit) {
1739     // RegSaveFrameIndex is X86-64 only.
1740     FuncInfo->setRegSaveFrameIndex(0xAAAAAAA);
1741     if (CallConv == CallingConv::X86_FastCall)
1742       // fastcc functions can't have varargs.
1743       FuncInfo->setVarArgsFrameIndex(0xAAAAAAA);
1744   }
1745
1746   return Chain;
1747 }
1748
1749 SDValue
1750 X86TargetLowering::LowerMemOpCallTo(SDValue Chain,
1751                                     SDValue StackPtr, SDValue Arg,
1752                                     DebugLoc dl, SelectionDAG &DAG,
1753                                     const CCValAssign &VA,
1754                                     ISD::ArgFlagsTy Flags) const {
1755   const unsigned FirstStackArgOffset = (Subtarget->isTargetWin64() ? 32 : 0);
1756   unsigned LocMemOffset = FirstStackArgOffset + VA.getLocMemOffset();
1757   SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset);
1758   PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, PtrOff);
1759   if (Flags.isByVal()) {
1760     return CreateCopyOfByValArgument(Arg, PtrOff, Chain, Flags, DAG, dl);
1761   }
1762   return DAG.getStore(Chain, dl, Arg, PtrOff,
1763                       PseudoSourceValue::getStack(), LocMemOffset,
1764                       false, false, 0);
1765 }
1766
1767 /// EmitTailCallLoadRetAddr - Emit a load of return address if tail call
1768 /// optimization is performed and it is required.
1769 SDValue
1770 X86TargetLowering::EmitTailCallLoadRetAddr(SelectionDAG &DAG,
1771                                            SDValue &OutRetAddr, SDValue Chain,
1772                                            bool IsTailCall, bool Is64Bit,
1773                                            int FPDiff, DebugLoc dl) const {
1774   // Adjust the Return address stack slot.
1775   EVT VT = getPointerTy();
1776   OutRetAddr = getReturnAddressFrameIndex(DAG);
1777
1778   // Load the "old" Return address.
1779   OutRetAddr = DAG.getLoad(VT, dl, Chain, OutRetAddr, NULL, 0, false, false, 0);
1780   return SDValue(OutRetAddr.getNode(), 1);
1781 }
1782
1783 /// EmitTailCallStoreRetAddr - Emit a store of the return adress if tail call
1784 /// optimization is performed and it is required (FPDiff!=0).
1785 static SDValue
1786 EmitTailCallStoreRetAddr(SelectionDAG & DAG, MachineFunction &MF,
1787                          SDValue Chain, SDValue RetAddrFrIdx,
1788                          bool Is64Bit, int FPDiff, DebugLoc dl) {
1789   // Store the return address to the appropriate stack slot.
1790   if (!FPDiff) return Chain;
1791   // Calculate the new stack slot for the return address.
1792   int SlotSize = Is64Bit ? 8 : 4;
1793   int NewReturnAddrFI =
1794     MF.getFrameInfo()->CreateFixedObject(SlotSize, FPDiff-SlotSize, false, false);
1795   EVT VT = Is64Bit ? MVT::i64 : MVT::i32;
1796   SDValue NewRetAddrFrIdx = DAG.getFrameIndex(NewReturnAddrFI, VT);
1797   Chain = DAG.getStore(Chain, dl, RetAddrFrIdx, NewRetAddrFrIdx,
1798                        PseudoSourceValue::getFixedStack(NewReturnAddrFI), 0,
1799                        false, false, 0);
1800   return Chain;
1801 }
1802
1803 SDValue
1804 X86TargetLowering::LowerCall(SDValue Chain, SDValue Callee,
1805                              CallingConv::ID CallConv, bool isVarArg,
1806                              bool &isTailCall,
1807                              const SmallVectorImpl<ISD::OutputArg> &Outs,
1808                              const SmallVectorImpl<ISD::InputArg> &Ins,
1809                              DebugLoc dl, SelectionDAG &DAG,
1810                              SmallVectorImpl<SDValue> &InVals) const {
1811   MachineFunction &MF = DAG.getMachineFunction();
1812   bool Is64Bit        = Subtarget->is64Bit();
1813   bool IsStructRet    = CallIsStructReturn(Outs);
1814   bool IsSibcall      = false;
1815
1816   if (isTailCall) {
1817     // Check if it's really possible to do a tail call.
1818     isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv,
1819                     isVarArg, IsStructRet, MF.getFunction()->hasStructRetAttr(),
1820                                                    Outs, Ins, DAG);
1821
1822     // Sibcalls are automatically detected tailcalls which do not require
1823     // ABI changes.
1824     if (!GuaranteedTailCallOpt && isTailCall)
1825       IsSibcall = true;
1826
1827     if (isTailCall)
1828       ++NumTailCalls;
1829   }
1830
1831   assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
1832          "Var args not supported with calling convention fastcc or ghc");
1833
1834   // Analyze operands of the call, assigning locations to each operand.
1835   SmallVector<CCValAssign, 16> ArgLocs;
1836   CCState CCInfo(CallConv, isVarArg, getTargetMachine(),
1837                  ArgLocs, *DAG.getContext());
1838   CCInfo.AnalyzeCallOperands(Outs, CCAssignFnForNode(CallConv));
1839
1840   // Get a count of how many bytes are to be pushed on the stack.
1841   unsigned NumBytes = CCInfo.getNextStackOffset();
1842   if (IsSibcall)
1843     // This is a sibcall. The memory operands are available in caller's
1844     // own caller's stack.
1845     NumBytes = 0;
1846   else if (GuaranteedTailCallOpt && IsTailCallConvention(CallConv))
1847     NumBytes = GetAlignedArgumentStackSize(NumBytes, DAG);
1848
1849   int FPDiff = 0;
1850   if (isTailCall && !IsSibcall) {
1851     // Lower arguments at fp - stackoffset + fpdiff.
1852     unsigned NumBytesCallerPushed =
1853       MF.getInfo<X86MachineFunctionInfo>()->getBytesToPopOnReturn();
1854     FPDiff = NumBytesCallerPushed - NumBytes;
1855
1856     // Set the delta of movement of the returnaddr stackslot.
1857     // But only set if delta is greater than previous delta.
1858     if (FPDiff < (MF.getInfo<X86MachineFunctionInfo>()->getTCReturnAddrDelta()))
1859       MF.getInfo<X86MachineFunctionInfo>()->setTCReturnAddrDelta(FPDiff);
1860   }
1861
1862   if (!IsSibcall)
1863     Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes, true));
1864
1865   SDValue RetAddrFrIdx;
1866   // Load return adress for tail calls.
1867   if (isTailCall && FPDiff)
1868     Chain = EmitTailCallLoadRetAddr(DAG, RetAddrFrIdx, Chain, isTailCall,
1869                                     Is64Bit, FPDiff, dl);
1870
1871   SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
1872   SmallVector<SDValue, 8> MemOpChains;
1873   SDValue StackPtr;
1874
1875   // Walk the register/memloc assignments, inserting copies/loads.  In the case
1876   // of tail call optimization arguments are handle later.
1877   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
1878     CCValAssign &VA = ArgLocs[i];
1879     EVT RegVT = VA.getLocVT();
1880     SDValue Arg = Outs[i].Val;
1881     ISD::ArgFlagsTy Flags = Outs[i].Flags;
1882     bool isByVal = Flags.isByVal();
1883
1884     // Promote the value if needed.
1885     switch (VA.getLocInfo()) {
1886     default: llvm_unreachable("Unknown loc info!");
1887     case CCValAssign::Full: break;
1888     case CCValAssign::SExt:
1889       Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, RegVT, Arg);
1890       break;
1891     case CCValAssign::ZExt:
1892       Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, RegVT, Arg);
1893       break;
1894     case CCValAssign::AExt:
1895       if (RegVT.isVector() && RegVT.getSizeInBits() == 128) {
1896         // Special case: passing MMX values in XMM registers.
1897         Arg = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::i64, Arg);
1898         Arg = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64, Arg);
1899         Arg = getMOVL(DAG, dl, MVT::v2i64, DAG.getUNDEF(MVT::v2i64), Arg);
1900       } else
1901         Arg = DAG.getNode(ISD::ANY_EXTEND, dl, RegVT, Arg);
1902       break;
1903     case CCValAssign::BCvt:
1904       Arg = DAG.getNode(ISD::BIT_CONVERT, dl, RegVT, Arg);
1905       break;
1906     case CCValAssign::Indirect: {
1907       // Store the argument.
1908       SDValue SpillSlot = DAG.CreateStackTemporary(VA.getValVT());
1909       int FI = cast<FrameIndexSDNode>(SpillSlot)->getIndex();
1910       Chain = DAG.getStore(Chain, dl, Arg, SpillSlot,
1911                            PseudoSourceValue::getFixedStack(FI), 0,
1912                            false, false, 0);
1913       Arg = SpillSlot;
1914       break;
1915     }
1916     }
1917
1918     if (VA.isRegLoc()) {
1919       RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
1920     } else if (!IsSibcall && (!isTailCall || isByVal)) {
1921       assert(VA.isMemLoc());
1922       if (StackPtr.getNode() == 0)
1923         StackPtr = DAG.getCopyFromReg(Chain, dl, X86StackPtr, getPointerTy());
1924       MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg,
1925                                              dl, DAG, VA, Flags));
1926     }
1927   }
1928
1929   if (!MemOpChains.empty())
1930     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
1931                         &MemOpChains[0], MemOpChains.size());
1932
1933   // Build a sequence of copy-to-reg nodes chained together with token chain
1934   // and flag operands which copy the outgoing args into registers.
1935   SDValue InFlag;
1936   // Tail call byval lowering might overwrite argument registers so in case of
1937   // tail call optimization the copies to registers are lowered later.
1938   if (!isTailCall)
1939     for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
1940       Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
1941                                RegsToPass[i].second, InFlag);
1942       InFlag = Chain.getValue(1);
1943     }
1944
1945   if (Subtarget->isPICStyleGOT()) {
1946     // ELF / PIC requires GOT in the EBX register before function calls via PLT
1947     // GOT pointer.
1948     if (!isTailCall) {
1949       Chain = DAG.getCopyToReg(Chain, dl, X86::EBX,
1950                                DAG.getNode(X86ISD::GlobalBaseReg,
1951                                            DebugLoc(), getPointerTy()),
1952                                InFlag);
1953       InFlag = Chain.getValue(1);
1954     } else {
1955       // If we are tail calling and generating PIC/GOT style code load the
1956       // address of the callee into ECX. The value in ecx is used as target of
1957       // the tail jump. This is done to circumvent the ebx/callee-saved problem
1958       // for tail calls on PIC/GOT architectures. Normally we would just put the
1959       // address of GOT into ebx and then call target@PLT. But for tail calls
1960       // ebx would be restored (since ebx is callee saved) before jumping to the
1961       // target@PLT.
1962
1963       // Note: The actual moving to ECX is done further down.
1964       GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee);
1965       if (G && !G->getGlobal()->hasHiddenVisibility() &&
1966           !G->getGlobal()->hasProtectedVisibility())
1967         Callee = LowerGlobalAddress(Callee, DAG);
1968       else if (isa<ExternalSymbolSDNode>(Callee))
1969         Callee = LowerExternalSymbol(Callee, DAG);
1970     }
1971   }
1972
1973   if (Is64Bit && isVarArg) {
1974     // From AMD64 ABI document:
1975     // For calls that may call functions that use varargs or stdargs
1976     // (prototype-less calls or calls to functions containing ellipsis (...) in
1977     // the declaration) %al is used as hidden argument to specify the number
1978     // of SSE registers used. The contents of %al do not need to match exactly
1979     // the number of registers, but must be an ubound on the number of SSE
1980     // registers used and is in the range 0 - 8 inclusive.
1981
1982     // FIXME: Verify this on Win64
1983     // Count the number of XMM registers allocated.
1984     static const unsigned XMMArgRegs[] = {
1985       X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
1986       X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
1987     };
1988     unsigned NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs, 8);
1989     assert((Subtarget->hasSSE1() || !NumXMMRegs)
1990            && "SSE registers cannot be used when SSE is disabled");
1991
1992     Chain = DAG.getCopyToReg(Chain, dl, X86::AL,
1993                              DAG.getConstant(NumXMMRegs, MVT::i8), InFlag);
1994     InFlag = Chain.getValue(1);
1995   }
1996
1997
1998   // For tail calls lower the arguments to the 'real' stack slot.
1999   if (isTailCall) {
2000     // Force all the incoming stack arguments to be loaded from the stack
2001     // before any new outgoing arguments are stored to the stack, because the
2002     // outgoing stack slots may alias the incoming argument stack slots, and
2003     // the alias isn't otherwise explicit. This is slightly more conservative
2004     // than necessary, because it means that each store effectively depends
2005     // on every argument instead of just those arguments it would clobber.
2006     SDValue ArgChain = DAG.getStackArgumentTokenFactor(Chain);
2007
2008     SmallVector<SDValue, 8> MemOpChains2;
2009     SDValue FIN;
2010     int FI = 0;
2011     // Do not flag preceeding copytoreg stuff together with the following stuff.
2012     InFlag = SDValue();
2013     if (GuaranteedTailCallOpt) {
2014       for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2015         CCValAssign &VA = ArgLocs[i];
2016         if (VA.isRegLoc())
2017           continue;
2018         assert(VA.isMemLoc());
2019         SDValue Arg = Outs[i].Val;
2020         ISD::ArgFlagsTy Flags = Outs[i].Flags;
2021         // Create frame index.
2022         int32_t Offset = VA.getLocMemOffset()+FPDiff;
2023         uint32_t OpSize = (VA.getLocVT().getSizeInBits()+7)/8;
2024         FI = MF.getFrameInfo()->CreateFixedObject(OpSize, Offset, true, false);
2025         FIN = DAG.getFrameIndex(FI, getPointerTy());
2026
2027         if (Flags.isByVal()) {
2028           // Copy relative to framepointer.
2029           SDValue Source = DAG.getIntPtrConstant(VA.getLocMemOffset());
2030           if (StackPtr.getNode() == 0)
2031             StackPtr = DAG.getCopyFromReg(Chain, dl, X86StackPtr,
2032                                           getPointerTy());
2033           Source = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, Source);
2034
2035           MemOpChains2.push_back(CreateCopyOfByValArgument(Source, FIN,
2036                                                            ArgChain,
2037                                                            Flags, DAG, dl));
2038         } else {
2039           // Store relative to framepointer.
2040           MemOpChains2.push_back(
2041             DAG.getStore(ArgChain, dl, Arg, FIN,
2042                          PseudoSourceValue::getFixedStack(FI), 0,
2043                          false, false, 0));
2044         }
2045       }
2046     }
2047
2048     if (!MemOpChains2.empty())
2049       Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
2050                           &MemOpChains2[0], MemOpChains2.size());
2051
2052     // Copy arguments to their registers.
2053     for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
2054       Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
2055                                RegsToPass[i].second, InFlag);
2056       InFlag = Chain.getValue(1);
2057     }
2058     InFlag =SDValue();
2059
2060     // Store the return address to the appropriate stack slot.
2061     Chain = EmitTailCallStoreRetAddr(DAG, MF, Chain, RetAddrFrIdx, Is64Bit,
2062                                      FPDiff, dl);
2063   }
2064
2065   bool WasGlobalOrExternal = false;
2066   if (getTargetMachine().getCodeModel() == CodeModel::Large) {
2067     assert(Is64Bit && "Large code model is only legal in 64-bit mode.");
2068     // In the 64-bit large code model, we have to make all calls
2069     // through a register, since the call instruction's 32-bit
2070     // pc-relative offset may not be large enough to hold the whole
2071     // address.
2072   } else if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
2073     WasGlobalOrExternal = true;
2074     // If the callee is a GlobalAddress node (quite common, every direct call
2075     // is) turn it into a TargetGlobalAddress node so that legalize doesn't hack
2076     // it.
2077
2078     // We should use extra load for direct calls to dllimported functions in
2079     // non-JIT mode.
2080     const GlobalValue *GV = G->getGlobal();
2081     if (!GV->hasDLLImportLinkage()) {
2082       unsigned char OpFlags = 0;
2083
2084       // On ELF targets, in both X86-64 and X86-32 mode, direct calls to
2085       // external symbols most go through the PLT in PIC mode.  If the symbol
2086       // has hidden or protected visibility, or if it is static or local, then
2087       // we don't need to use the PLT - we can directly call it.
2088       if (Subtarget->isTargetELF() &&
2089           getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
2090           GV->hasDefaultVisibility() && !GV->hasLocalLinkage()) {
2091         OpFlags = X86II::MO_PLT;
2092       } else if (Subtarget->isPICStyleStubAny() &&
2093                (GV->isDeclaration() || GV->isWeakForLinker()) &&
2094                Subtarget->getDarwinVers() < 9) {
2095         // PC-relative references to external symbols should go through $stub,
2096         // unless we're building with the leopard linker or later, which
2097         // automatically synthesizes these stubs.
2098         OpFlags = X86II::MO_DARWIN_STUB;
2099       }
2100
2101       Callee = DAG.getTargetGlobalAddress(GV, getPointerTy(),
2102                                           G->getOffset(), OpFlags);
2103     }
2104   } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
2105     WasGlobalOrExternal = true;
2106     unsigned char OpFlags = 0;
2107
2108     // On ELF targets, in either X86-64 or X86-32 mode, direct calls to external
2109     // symbols should go through the PLT.
2110     if (Subtarget->isTargetELF() &&
2111         getTargetMachine().getRelocationModel() == Reloc::PIC_) {
2112       OpFlags = X86II::MO_PLT;
2113     } else if (Subtarget->isPICStyleStubAny() &&
2114              Subtarget->getDarwinVers() < 9) {
2115       // PC-relative references to external symbols should go through $stub,
2116       // unless we're building with the leopard linker or later, which
2117       // automatically synthesizes these stubs.
2118       OpFlags = X86II::MO_DARWIN_STUB;
2119     }
2120
2121     Callee = DAG.getTargetExternalSymbol(S->getSymbol(), getPointerTy(),
2122                                          OpFlags);
2123   }
2124
2125   // Returns a chain & a flag for retval copy to use.
2126   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Flag);
2127   SmallVector<SDValue, 8> Ops;
2128
2129   if (!IsSibcall && isTailCall) {
2130     Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, true),
2131                            DAG.getIntPtrConstant(0, true), InFlag);
2132     InFlag = Chain.getValue(1);
2133   }
2134
2135   Ops.push_back(Chain);
2136   Ops.push_back(Callee);
2137
2138   if (isTailCall)
2139     Ops.push_back(DAG.getConstant(FPDiff, MVT::i32));
2140
2141   // Add argument registers to the end of the list so that they are known live
2142   // into the call.
2143   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
2144     Ops.push_back(DAG.getRegister(RegsToPass[i].first,
2145                                   RegsToPass[i].second.getValueType()));
2146
2147   // Add an implicit use GOT pointer in EBX.
2148   if (!isTailCall && Subtarget->isPICStyleGOT())
2149     Ops.push_back(DAG.getRegister(X86::EBX, getPointerTy()));
2150
2151   // Add an implicit use of AL for x86 vararg functions.
2152   if (Is64Bit && isVarArg)
2153     Ops.push_back(DAG.getRegister(X86::AL, MVT::i8));
2154
2155   if (InFlag.getNode())
2156     Ops.push_back(InFlag);
2157
2158   if (isTailCall) {
2159     // If this is the first return lowered for this function, add the regs
2160     // to the liveout set for the function.
2161     if (MF.getRegInfo().liveout_empty()) {
2162       SmallVector<CCValAssign, 16> RVLocs;
2163       CCState CCInfo(CallConv, isVarArg, getTargetMachine(), RVLocs,
2164                      *DAG.getContext());
2165       CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
2166       for (unsigned i = 0; i != RVLocs.size(); ++i)
2167         if (RVLocs[i].isRegLoc())
2168           MF.getRegInfo().addLiveOut(RVLocs[i].getLocReg());
2169     }
2170     return DAG.getNode(X86ISD::TC_RETURN, dl,
2171                        NodeTys, &Ops[0], Ops.size());
2172   }
2173
2174   Chain = DAG.getNode(X86ISD::CALL, dl, NodeTys, &Ops[0], Ops.size());
2175   InFlag = Chain.getValue(1);
2176
2177   // Create the CALLSEQ_END node.
2178   unsigned NumBytesForCalleeToPush;
2179   if (IsCalleePop(isVarArg, CallConv))
2180     NumBytesForCalleeToPush = NumBytes;    // Callee pops everything
2181   else if (!Is64Bit && !IsTailCallConvention(CallConv) && IsStructRet)
2182     // If this is a call to a struct-return function, the callee
2183     // pops the hidden struct pointer, so we have to push it back.
2184     // This is common for Darwin/X86, Linux & Mingw32 targets.
2185     NumBytesForCalleeToPush = 4;
2186   else
2187     NumBytesForCalleeToPush = 0;  // Callee pops nothing.
2188
2189   // Returns a flag for retval copy to use.
2190   if (!IsSibcall) {
2191     Chain = DAG.getCALLSEQ_END(Chain,
2192                                DAG.getIntPtrConstant(NumBytes, true),
2193                                DAG.getIntPtrConstant(NumBytesForCalleeToPush,
2194                                                      true),
2195                                InFlag);
2196     InFlag = Chain.getValue(1);
2197   }
2198
2199   // Handle result values, copying them out of physregs into vregs that we
2200   // return.
2201   return LowerCallResult(Chain, InFlag, CallConv, isVarArg,
2202                          Ins, dl, DAG, InVals);
2203 }
2204
2205
2206 //===----------------------------------------------------------------------===//
2207 //                Fast Calling Convention (tail call) implementation
2208 //===----------------------------------------------------------------------===//
2209
2210 //  Like std call, callee cleans arguments, convention except that ECX is
2211 //  reserved for storing the tail called function address. Only 2 registers are
2212 //  free for argument passing (inreg). Tail call optimization is performed
2213 //  provided:
2214 //                * tailcallopt is enabled
2215 //                * caller/callee are fastcc
2216 //  On X86_64 architecture with GOT-style position independent code only local
2217 //  (within module) calls are supported at the moment.
2218 //  To keep the stack aligned according to platform abi the function
2219 //  GetAlignedArgumentStackSize ensures that argument delta is always multiples
2220 //  of stack alignment. (Dynamic linkers need this - darwin's dyld for example)
2221 //  If a tail called function callee has more arguments than the caller the
2222 //  caller needs to make sure that there is room to move the RETADDR to. This is
2223 //  achieved by reserving an area the size of the argument delta right after the
2224 //  original REtADDR, but before the saved framepointer or the spilled registers
2225 //  e.g. caller(arg1, arg2) calls callee(arg1, arg2,arg3,arg4)
2226 //  stack layout:
2227 //    arg1
2228 //    arg2
2229 //    RETADDR
2230 //    [ new RETADDR
2231 //      move area ]
2232 //    (possible EBP)
2233 //    ESI
2234 //    EDI
2235 //    local1 ..
2236
2237 /// GetAlignedArgumentStackSize - Make the stack size align e.g 16n + 12 aligned
2238 /// for a 16 byte align requirement.
2239 unsigned
2240 X86TargetLowering::GetAlignedArgumentStackSize(unsigned StackSize,
2241                                                SelectionDAG& DAG) const {
2242   MachineFunction &MF = DAG.getMachineFunction();
2243   const TargetMachine &TM = MF.getTarget();
2244   const TargetFrameInfo &TFI = *TM.getFrameInfo();
2245   unsigned StackAlignment = TFI.getStackAlignment();
2246   uint64_t AlignMask = StackAlignment - 1;
2247   int64_t Offset = StackSize;
2248   uint64_t SlotSize = TD->getPointerSize();
2249   if ( (Offset & AlignMask) <= (StackAlignment - SlotSize) ) {
2250     // Number smaller than 12 so just add the difference.
2251     Offset += ((StackAlignment - SlotSize) - (Offset & AlignMask));
2252   } else {
2253     // Mask out lower bits, add stackalignment once plus the 12 bytes.
2254     Offset = ((~AlignMask) & Offset) + StackAlignment +
2255       (StackAlignment-SlotSize);
2256   }
2257   return Offset;
2258 }
2259
2260 /// MatchingStackOffset - Return true if the given stack call argument is
2261 /// already available in the same position (relatively) of the caller's
2262 /// incoming argument stack.
2263 static
2264 bool MatchingStackOffset(SDValue Arg, unsigned Offset, ISD::ArgFlagsTy Flags,
2265                          MachineFrameInfo *MFI, const MachineRegisterInfo *MRI,
2266                          const X86InstrInfo *TII) {
2267   unsigned Bytes = Arg.getValueType().getSizeInBits() / 8;
2268   int FI = INT_MAX;
2269   if (Arg.getOpcode() == ISD::CopyFromReg) {
2270     unsigned VR = cast<RegisterSDNode>(Arg.getOperand(1))->getReg();
2271     if (!VR || TargetRegisterInfo::isPhysicalRegister(VR))
2272       return false;
2273     MachineInstr *Def = MRI->getVRegDef(VR);
2274     if (!Def)
2275       return false;
2276     if (!Flags.isByVal()) {
2277       if (!TII->isLoadFromStackSlot(Def, FI))
2278         return false;
2279     } else {
2280       unsigned Opcode = Def->getOpcode();
2281       if ((Opcode == X86::LEA32r || Opcode == X86::LEA64r) &&
2282           Def->getOperand(1).isFI()) {
2283         FI = Def->getOperand(1).getIndex();
2284         Bytes = Flags.getByValSize();
2285       } else
2286         return false;
2287     }
2288   } else if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Arg)) {
2289     if (Flags.isByVal())
2290       // ByVal argument is passed in as a pointer but it's now being
2291       // dereferenced. e.g.
2292       // define @foo(%struct.X* %A) {
2293       //   tail call @bar(%struct.X* byval %A)
2294       // }
2295       return false;
2296     SDValue Ptr = Ld->getBasePtr();
2297     FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr);
2298     if (!FINode)
2299       return false;
2300     FI = FINode->getIndex();
2301   } else
2302     return false;
2303
2304   assert(FI != INT_MAX);
2305   if (!MFI->isFixedObjectIndex(FI))
2306     return false;
2307   return Offset == MFI->getObjectOffset(FI) && Bytes == MFI->getObjectSize(FI);
2308 }
2309
2310 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
2311 /// for tail call optimization. Targets which want to do tail call
2312 /// optimization should implement this function.
2313 bool
2314 X86TargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
2315                                                      CallingConv::ID CalleeCC,
2316                                                      bool isVarArg,
2317                                                      bool isCalleeStructRet,
2318                                                      bool isCallerStructRet,
2319                                     const SmallVectorImpl<ISD::OutputArg> &Outs,
2320                                     const SmallVectorImpl<ISD::InputArg> &Ins,
2321                                                      SelectionDAG& DAG) const {
2322   if (!IsTailCallConvention(CalleeCC) &&
2323       CalleeCC != CallingConv::C)
2324     return false;
2325
2326   // If -tailcallopt is specified, make fastcc functions tail-callable.
2327   const MachineFunction &MF = DAG.getMachineFunction();
2328   const Function *CallerF = DAG.getMachineFunction().getFunction();
2329   if (GuaranteedTailCallOpt) {
2330     if (IsTailCallConvention(CalleeCC) &&
2331         CallerF->getCallingConv() == CalleeCC)
2332       return true;
2333     return false;
2334   }
2335
2336   // Look for obvious safe cases to perform tail call optimization that does not
2337   // requite ABI changes. This is what gcc calls sibcall.
2338
2339   // Can't do sibcall if stack needs to be dynamically re-aligned. PEI needs to
2340   // emit a special epilogue.
2341   if (RegInfo->needsStackRealignment(MF))
2342     return false;
2343
2344   // Do not sibcall optimize vararg calls unless the call site is not passing any
2345   // arguments.
2346   if (isVarArg && !Outs.empty())
2347     return false;
2348
2349   // Also avoid sibcall optimization if either caller or callee uses struct
2350   // return semantics.
2351   if (isCalleeStructRet || isCallerStructRet)
2352     return false;
2353
2354   // If the call result is in ST0 / ST1, it needs to be popped off the x87 stack.
2355   // Therefore if it's not used by the call it is not safe to optimize this into
2356   // a sibcall.
2357   bool Unused = false;
2358   for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
2359     if (!Ins[i].Used) {
2360       Unused = true;
2361       break;
2362     }
2363   }
2364   if (Unused) {
2365     SmallVector<CCValAssign, 16> RVLocs;
2366     CCState CCInfo(CalleeCC, false, getTargetMachine(),
2367                    RVLocs, *DAG.getContext());
2368     CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
2369     for (unsigned i = 0; i != RVLocs.size(); ++i) {
2370       CCValAssign &VA = RVLocs[i];
2371       if (VA.getLocReg() == X86::ST0 || VA.getLocReg() == X86::ST1)
2372         return false;
2373     }
2374   }
2375
2376   // If the callee takes no arguments then go on to check the results of the
2377   // call.
2378   if (!Outs.empty()) {
2379     // Check if stack adjustment is needed. For now, do not do this if any
2380     // argument is passed on the stack.
2381     SmallVector<CCValAssign, 16> ArgLocs;
2382     CCState CCInfo(CalleeCC, isVarArg, getTargetMachine(),
2383                    ArgLocs, *DAG.getContext());
2384     CCInfo.AnalyzeCallOperands(Outs, CCAssignFnForNode(CalleeCC));
2385     if (CCInfo.getNextStackOffset()) {
2386       MachineFunction &MF = DAG.getMachineFunction();
2387       if (MF.getInfo<X86MachineFunctionInfo>()->getBytesToPopOnReturn())
2388         return false;
2389       if (Subtarget->isTargetWin64())
2390         // Win64 ABI has additional complications.
2391         return false;
2392
2393       // Check if the arguments are already laid out in the right way as
2394       // the caller's fixed stack objects.
2395       MachineFrameInfo *MFI = MF.getFrameInfo();
2396       const MachineRegisterInfo *MRI = &MF.getRegInfo();
2397       const X86InstrInfo *TII =
2398         ((X86TargetMachine&)getTargetMachine()).getInstrInfo();
2399       for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2400         CCValAssign &VA = ArgLocs[i];
2401         EVT RegVT = VA.getLocVT();
2402         SDValue Arg = Outs[i].Val;
2403         ISD::ArgFlagsTy Flags = Outs[i].Flags;
2404         if (VA.getLocInfo() == CCValAssign::Indirect)
2405           return false;
2406         if (!VA.isRegLoc()) {
2407           if (!MatchingStackOffset(Arg, VA.getLocMemOffset(), Flags,
2408                                    MFI, MRI, TII))
2409             return false;
2410         }
2411       }
2412     }
2413   }
2414
2415   return true;
2416 }
2417
2418 FastISel *
2419 X86TargetLowering::createFastISel(MachineFunction &mf,
2420                             DenseMap<const Value *, unsigned> &vm,
2421                             DenseMap<const BasicBlock*, MachineBasicBlock*> &bm,
2422                             DenseMap<const AllocaInst *, int> &am,
2423                             std::vector<std::pair<MachineInstr*, unsigned> > &pn
2424 #ifndef NDEBUG
2425                           , SmallSet<const Instruction *, 8> &cil
2426 #endif
2427                                   ) const {
2428   return X86::createFastISel(mf, vm, bm, am, pn
2429 #ifndef NDEBUG
2430                              , cil
2431 #endif
2432                              );
2433 }
2434
2435
2436 //===----------------------------------------------------------------------===//
2437 //                           Other Lowering Hooks
2438 //===----------------------------------------------------------------------===//
2439
2440
2441 SDValue X86TargetLowering::getReturnAddressFrameIndex(SelectionDAG &DAG) const {
2442   MachineFunction &MF = DAG.getMachineFunction();
2443   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
2444   int ReturnAddrIndex = FuncInfo->getRAIndex();
2445
2446   if (ReturnAddrIndex == 0) {
2447     // Set up a frame object for the return address.
2448     uint64_t SlotSize = TD->getPointerSize();
2449     ReturnAddrIndex = MF.getFrameInfo()->CreateFixedObject(SlotSize, -SlotSize,
2450                                                            false, false);
2451     FuncInfo->setRAIndex(ReturnAddrIndex);
2452   }
2453
2454   return DAG.getFrameIndex(ReturnAddrIndex, getPointerTy());
2455 }
2456
2457
2458 bool X86::isOffsetSuitableForCodeModel(int64_t Offset, CodeModel::Model M,
2459                                        bool hasSymbolicDisplacement) {
2460   // Offset should fit into 32 bit immediate field.
2461   if (!isInt<32>(Offset))
2462     return false;
2463
2464   // If we don't have a symbolic displacement - we don't have any extra
2465   // restrictions.
2466   if (!hasSymbolicDisplacement)
2467     return true;
2468
2469   // FIXME: Some tweaks might be needed for medium code model.
2470   if (M != CodeModel::Small && M != CodeModel::Kernel)
2471     return false;
2472
2473   // For small code model we assume that latest object is 16MB before end of 31
2474   // bits boundary. We may also accept pretty large negative constants knowing
2475   // that all objects are in the positive half of address space.
2476   if (M == CodeModel::Small && Offset < 16*1024*1024)
2477     return true;
2478
2479   // For kernel code model we know that all object resist in the negative half
2480   // of 32bits address space. We may not accept negative offsets, since they may
2481   // be just off and we may accept pretty large positive ones.
2482   if (M == CodeModel::Kernel && Offset > 0)
2483     return true;
2484
2485   return false;
2486 }
2487
2488 /// TranslateX86CC - do a one to one translation of a ISD::CondCode to the X86
2489 /// specific condition code, returning the condition code and the LHS/RHS of the
2490 /// comparison to make.
2491 static unsigned TranslateX86CC(ISD::CondCode SetCCOpcode, bool isFP,
2492                                SDValue &LHS, SDValue &RHS, SelectionDAG &DAG) {
2493   if (!isFP) {
2494     if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) {
2495       if (SetCCOpcode == ISD::SETGT && RHSC->isAllOnesValue()) {
2496         // X > -1   -> X == 0, jump !sign.
2497         RHS = DAG.getConstant(0, RHS.getValueType());
2498         return X86::COND_NS;
2499       } else if (SetCCOpcode == ISD::SETLT && RHSC->isNullValue()) {
2500         // X < 0   -> X == 0, jump on sign.
2501         return X86::COND_S;
2502       } else if (SetCCOpcode == ISD::SETLT && RHSC->getZExtValue() == 1) {
2503         // X < 1   -> X <= 0
2504         RHS = DAG.getConstant(0, RHS.getValueType());
2505         return X86::COND_LE;
2506       }
2507     }
2508
2509     switch (SetCCOpcode) {
2510     default: llvm_unreachable("Invalid integer condition!");
2511     case ISD::SETEQ:  return X86::COND_E;
2512     case ISD::SETGT:  return X86::COND_G;
2513     case ISD::SETGE:  return X86::COND_GE;
2514     case ISD::SETLT:  return X86::COND_L;
2515     case ISD::SETLE:  return X86::COND_LE;
2516     case ISD::SETNE:  return X86::COND_NE;
2517     case ISD::SETULT: return X86::COND_B;
2518     case ISD::SETUGT: return X86::COND_A;
2519     case ISD::SETULE: return X86::COND_BE;
2520     case ISD::SETUGE: return X86::COND_AE;
2521     }
2522   }
2523
2524   // First determine if it is required or is profitable to flip the operands.
2525
2526   // If LHS is a foldable load, but RHS is not, flip the condition.
2527   if ((ISD::isNON_EXTLoad(LHS.getNode()) && LHS.hasOneUse()) &&
2528       !(ISD::isNON_EXTLoad(RHS.getNode()) && RHS.hasOneUse())) {
2529     SetCCOpcode = getSetCCSwappedOperands(SetCCOpcode);
2530     std::swap(LHS, RHS);
2531   }
2532
2533   switch (SetCCOpcode) {
2534   default: break;
2535   case ISD::SETOLT:
2536   case ISD::SETOLE:
2537   case ISD::SETUGT:
2538   case ISD::SETUGE:
2539     std::swap(LHS, RHS);
2540     break;
2541   }
2542
2543   // On a floating point condition, the flags are set as follows:
2544   // ZF  PF  CF   op
2545   //  0 | 0 | 0 | X > Y
2546   //  0 | 0 | 1 | X < Y
2547   //  1 | 0 | 0 | X == Y
2548   //  1 | 1 | 1 | unordered
2549   switch (SetCCOpcode) {
2550   default: llvm_unreachable("Condcode should be pre-legalized away");
2551   case ISD::SETUEQ:
2552   case ISD::SETEQ:   return X86::COND_E;
2553   case ISD::SETOLT:              // flipped
2554   case ISD::SETOGT:
2555   case ISD::SETGT:   return X86::COND_A;
2556   case ISD::SETOLE:              // flipped
2557   case ISD::SETOGE:
2558   case ISD::SETGE:   return X86::COND_AE;
2559   case ISD::SETUGT:              // flipped
2560   case ISD::SETULT:
2561   case ISD::SETLT:   return X86::COND_B;
2562   case ISD::SETUGE:              // flipped
2563   case ISD::SETULE:
2564   case ISD::SETLE:   return X86::COND_BE;
2565   case ISD::SETONE:
2566   case ISD::SETNE:   return X86::COND_NE;
2567   case ISD::SETUO:   return X86::COND_P;
2568   case ISD::SETO:    return X86::COND_NP;
2569   case ISD::SETOEQ:
2570   case ISD::SETUNE:  return X86::COND_INVALID;
2571   }
2572 }
2573
2574 /// hasFPCMov - is there a floating point cmov for the specific X86 condition
2575 /// code. Current x86 isa includes the following FP cmov instructions:
2576 /// fcmovb, fcomvbe, fcomve, fcmovu, fcmovae, fcmova, fcmovne, fcmovnu.
2577 static bool hasFPCMov(unsigned X86CC) {
2578   switch (X86CC) {
2579   default:
2580     return false;
2581   case X86::COND_B:
2582   case X86::COND_BE:
2583   case X86::COND_E:
2584   case X86::COND_P:
2585   case X86::COND_A:
2586   case X86::COND_AE:
2587   case X86::COND_NE:
2588   case X86::COND_NP:
2589     return true;
2590   }
2591 }
2592
2593 /// isFPImmLegal - Returns true if the target can instruction select the
2594 /// specified FP immediate natively. If false, the legalizer will
2595 /// materialize the FP immediate as a load from a constant pool.
2596 bool X86TargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
2597   for (unsigned i = 0, e = LegalFPImmediates.size(); i != e; ++i) {
2598     if (Imm.bitwiseIsEqual(LegalFPImmediates[i]))
2599       return true;
2600   }
2601   return false;
2602 }
2603
2604 /// isUndefOrInRange - Return true if Val is undef or if its value falls within
2605 /// the specified range (L, H].
2606 static bool isUndefOrInRange(int Val, int Low, int Hi) {
2607   return (Val < 0) || (Val >= Low && Val < Hi);
2608 }
2609
2610 /// isUndefOrEqual - Val is either less than zero (undef) or equal to the
2611 /// specified value.
2612 static bool isUndefOrEqual(int Val, int CmpVal) {
2613   if (Val < 0 || Val == CmpVal)
2614     return true;
2615   return false;
2616 }
2617
2618 /// isPSHUFDMask - Return true if the node specifies a shuffle of elements that
2619 /// is suitable for input to PSHUFD or PSHUFW.  That is, it doesn't reference
2620 /// the second operand.
2621 static bool isPSHUFDMask(const SmallVectorImpl<int> &Mask, EVT VT) {
2622   if (VT == MVT::v4f32 || VT == MVT::v4i32 || VT == MVT::v4i16)
2623     return (Mask[0] < 4 && Mask[1] < 4 && Mask[2] < 4 && Mask[3] < 4);
2624   if (VT == MVT::v2f64 || VT == MVT::v2i64)
2625     return (Mask[0] < 2 && Mask[1] < 2);
2626   return false;
2627 }
2628
2629 bool X86::isPSHUFDMask(ShuffleVectorSDNode *N) {
2630   SmallVector<int, 8> M;
2631   N->getMask(M);
2632   return ::isPSHUFDMask(M, N->getValueType(0));
2633 }
2634
2635 /// isPSHUFHWMask - Return true if the node specifies a shuffle of elements that
2636 /// is suitable for input to PSHUFHW.
2637 static bool isPSHUFHWMask(const SmallVectorImpl<int> &Mask, EVT VT) {
2638   if (VT != MVT::v8i16)
2639     return false;
2640
2641   // Lower quadword copied in order or undef.
2642   for (int i = 0; i != 4; ++i)
2643     if (Mask[i] >= 0 && Mask[i] != i)
2644       return false;
2645
2646   // Upper quadword shuffled.
2647   for (int i = 4; i != 8; ++i)
2648     if (Mask[i] >= 0 && (Mask[i] < 4 || Mask[i] > 7))
2649       return false;
2650
2651   return true;
2652 }
2653
2654 bool X86::isPSHUFHWMask(ShuffleVectorSDNode *N) {
2655   SmallVector<int, 8> M;
2656   N->getMask(M);
2657   return ::isPSHUFHWMask(M, N->getValueType(0));
2658 }
2659
2660 /// isPSHUFLWMask - Return true if the node specifies a shuffle of elements that
2661 /// is suitable for input to PSHUFLW.
2662 static bool isPSHUFLWMask(const SmallVectorImpl<int> &Mask, EVT VT) {
2663   if (VT != MVT::v8i16)
2664     return false;
2665
2666   // Upper quadword copied in order.
2667   for (int i = 4; i != 8; ++i)
2668     if (Mask[i] >= 0 && Mask[i] != i)
2669       return false;
2670
2671   // Lower quadword shuffled.
2672   for (int i = 0; i != 4; ++i)
2673     if (Mask[i] >= 4)
2674       return false;
2675
2676   return true;
2677 }
2678
2679 bool X86::isPSHUFLWMask(ShuffleVectorSDNode *N) {
2680   SmallVector<int, 8> M;
2681   N->getMask(M);
2682   return ::isPSHUFLWMask(M, N->getValueType(0));
2683 }
2684
2685 /// isPALIGNRMask - Return true if the node specifies a shuffle of elements that
2686 /// is suitable for input to PALIGNR.
2687 static bool isPALIGNRMask(const SmallVectorImpl<int> &Mask, EVT VT,
2688                           bool hasSSSE3) {
2689   int i, e = VT.getVectorNumElements();
2690   
2691   // Do not handle v2i64 / v2f64 shuffles with palignr.
2692   if (e < 4 || !hasSSSE3)
2693     return false;
2694   
2695   for (i = 0; i != e; ++i)
2696     if (Mask[i] >= 0)
2697       break;
2698   
2699   // All undef, not a palignr.
2700   if (i == e)
2701     return false;
2702
2703   // Determine if it's ok to perform a palignr with only the LHS, since we
2704   // don't have access to the actual shuffle elements to see if RHS is undef.
2705   bool Unary = Mask[i] < (int)e;
2706   bool NeedsUnary = false;
2707
2708   int s = Mask[i] - i;
2709   
2710   // Check the rest of the elements to see if they are consecutive.
2711   for (++i; i != e; ++i) {
2712     int m = Mask[i];
2713     if (m < 0) 
2714       continue;
2715     
2716     Unary = Unary && (m < (int)e);
2717     NeedsUnary = NeedsUnary || (m < s);
2718
2719     if (NeedsUnary && !Unary)
2720       return false;
2721     if (Unary && m != ((s+i) & (e-1)))
2722       return false;
2723     if (!Unary && m != (s+i))
2724       return false;
2725   }
2726   return true;
2727 }
2728
2729 bool X86::isPALIGNRMask(ShuffleVectorSDNode *N) {
2730   SmallVector<int, 8> M;
2731   N->getMask(M);
2732   return ::isPALIGNRMask(M, N->getValueType(0), true);
2733 }
2734
2735 /// isSHUFPMask - Return true if the specified VECTOR_SHUFFLE operand
2736 /// specifies a shuffle of elements that is suitable for input to SHUFP*.
2737 static bool isSHUFPMask(const SmallVectorImpl<int> &Mask, EVT VT) {
2738   int NumElems = VT.getVectorNumElements();
2739   if (NumElems != 2 && NumElems != 4)
2740     return false;
2741
2742   int Half = NumElems / 2;
2743   for (int i = 0; i < Half; ++i)
2744     if (!isUndefOrInRange(Mask[i], 0, NumElems))
2745       return false;
2746   for (int i = Half; i < NumElems; ++i)
2747     if (!isUndefOrInRange(Mask[i], NumElems, NumElems*2))
2748       return false;
2749
2750   return true;
2751 }
2752
2753 bool X86::isSHUFPMask(ShuffleVectorSDNode *N) {
2754   SmallVector<int, 8> M;
2755   N->getMask(M);
2756   return ::isSHUFPMask(M, N->getValueType(0));
2757 }
2758
2759 /// isCommutedSHUFP - Returns true if the shuffle mask is exactly
2760 /// the reverse of what x86 shuffles want. x86 shuffles requires the lower
2761 /// half elements to come from vector 1 (which would equal the dest.) and
2762 /// the upper half to come from vector 2.
2763 static bool isCommutedSHUFPMask(const SmallVectorImpl<int> &Mask, EVT VT) {
2764   int NumElems = VT.getVectorNumElements();
2765
2766   if (NumElems != 2 && NumElems != 4)
2767     return false;
2768
2769   int Half = NumElems / 2;
2770   for (int i = 0; i < Half; ++i)
2771     if (!isUndefOrInRange(Mask[i], NumElems, NumElems*2))
2772       return false;
2773   for (int i = Half; i < NumElems; ++i)
2774     if (!isUndefOrInRange(Mask[i], 0, NumElems))
2775       return false;
2776   return true;
2777 }
2778
2779 static bool isCommutedSHUFP(ShuffleVectorSDNode *N) {
2780   SmallVector<int, 8> M;
2781   N->getMask(M);
2782   return isCommutedSHUFPMask(M, N->getValueType(0));
2783 }
2784
2785 /// isMOVHLPSMask - Return true if the specified VECTOR_SHUFFLE operand
2786 /// specifies a shuffle of elements that is suitable for input to MOVHLPS.
2787 bool X86::isMOVHLPSMask(ShuffleVectorSDNode *N) {
2788   if (N->getValueType(0).getVectorNumElements() != 4)
2789     return false;
2790
2791   // Expect bit0 == 6, bit1 == 7, bit2 == 2, bit3 == 3
2792   return isUndefOrEqual(N->getMaskElt(0), 6) &&
2793          isUndefOrEqual(N->getMaskElt(1), 7) &&
2794          isUndefOrEqual(N->getMaskElt(2), 2) &&
2795          isUndefOrEqual(N->getMaskElt(3), 3);
2796 }
2797
2798 /// isMOVHLPS_v_undef_Mask - Special case of isMOVHLPSMask for canonical form
2799 /// of vector_shuffle v, v, <2, 3, 2, 3>, i.e. vector_shuffle v, undef,
2800 /// <2, 3, 2, 3>
2801 bool X86::isMOVHLPS_v_undef_Mask(ShuffleVectorSDNode *N) {
2802   unsigned NumElems = N->getValueType(0).getVectorNumElements();
2803   
2804   if (NumElems != 4)
2805     return false;
2806   
2807   return isUndefOrEqual(N->getMaskElt(0), 2) &&
2808   isUndefOrEqual(N->getMaskElt(1), 3) &&
2809   isUndefOrEqual(N->getMaskElt(2), 2) &&
2810   isUndefOrEqual(N->getMaskElt(3), 3);
2811 }
2812
2813 /// isMOVLPMask - Return true if the specified VECTOR_SHUFFLE operand
2814 /// specifies a shuffle of elements that is suitable for input to MOVLP{S|D}.
2815 bool X86::isMOVLPMask(ShuffleVectorSDNode *N) {
2816   unsigned NumElems = N->getValueType(0).getVectorNumElements();
2817
2818   if (NumElems != 2 && NumElems != 4)
2819     return false;
2820
2821   for (unsigned i = 0; i < NumElems/2; ++i)
2822     if (!isUndefOrEqual(N->getMaskElt(i), i + NumElems))
2823       return false;
2824
2825   for (unsigned i = NumElems/2; i < NumElems; ++i)
2826     if (!isUndefOrEqual(N->getMaskElt(i), i))
2827       return false;
2828
2829   return true;
2830 }
2831
2832 /// isMOVLHPSMask - Return true if the specified VECTOR_SHUFFLE operand
2833 /// specifies a shuffle of elements that is suitable for input to MOVLHPS.
2834 bool X86::isMOVLHPSMask(ShuffleVectorSDNode *N) {
2835   unsigned NumElems = N->getValueType(0).getVectorNumElements();
2836
2837   if (NumElems != 2 && NumElems != 4)
2838     return false;
2839
2840   for (unsigned i = 0; i < NumElems/2; ++i)
2841     if (!isUndefOrEqual(N->getMaskElt(i), i))
2842       return false;
2843
2844   for (unsigned i = 0; i < NumElems/2; ++i)
2845     if (!isUndefOrEqual(N->getMaskElt(i + NumElems/2), i + NumElems))
2846       return false;
2847
2848   return true;
2849 }
2850
2851 /// isUNPCKLMask - Return true if the specified VECTOR_SHUFFLE operand
2852 /// specifies a shuffle of elements that is suitable for input to UNPCKL.
2853 static bool isUNPCKLMask(const SmallVectorImpl<int> &Mask, EVT VT,
2854                          bool V2IsSplat = false) {
2855   int NumElts = VT.getVectorNumElements();
2856   if (NumElts != 2 && NumElts != 4 && NumElts != 8 && NumElts != 16)
2857     return false;
2858
2859   for (int i = 0, j = 0; i != NumElts; i += 2, ++j) {
2860     int BitI  = Mask[i];
2861     int BitI1 = Mask[i+1];
2862     if (!isUndefOrEqual(BitI, j))
2863       return false;
2864     if (V2IsSplat) {
2865       if (!isUndefOrEqual(BitI1, NumElts))
2866         return false;
2867     } else {
2868       if (!isUndefOrEqual(BitI1, j + NumElts))
2869         return false;
2870     }
2871   }
2872   return true;
2873 }
2874
2875 bool X86::isUNPCKLMask(ShuffleVectorSDNode *N, bool V2IsSplat) {
2876   SmallVector<int, 8> M;
2877   N->getMask(M);
2878   return ::isUNPCKLMask(M, N->getValueType(0), V2IsSplat);
2879 }
2880
2881 /// isUNPCKHMask - Return true if the specified VECTOR_SHUFFLE operand
2882 /// specifies a shuffle of elements that is suitable for input to UNPCKH.
2883 static bool isUNPCKHMask(const SmallVectorImpl<int> &Mask, EVT VT,
2884                          bool V2IsSplat = false) {
2885   int NumElts = VT.getVectorNumElements();
2886   if (NumElts != 2 && NumElts != 4 && NumElts != 8 && NumElts != 16)
2887     return false;
2888
2889   for (int i = 0, j = 0; i != NumElts; i += 2, ++j) {
2890     int BitI  = Mask[i];
2891     int BitI1 = Mask[i+1];
2892     if (!isUndefOrEqual(BitI, j + NumElts/2))
2893       return false;
2894     if (V2IsSplat) {
2895       if (isUndefOrEqual(BitI1, NumElts))
2896         return false;
2897     } else {
2898       if (!isUndefOrEqual(BitI1, j + NumElts/2 + NumElts))
2899         return false;
2900     }
2901   }
2902   return true;
2903 }
2904
2905 bool X86::isUNPCKHMask(ShuffleVectorSDNode *N, bool V2IsSplat) {
2906   SmallVector<int, 8> M;
2907   N->getMask(M);
2908   return ::isUNPCKHMask(M, N->getValueType(0), V2IsSplat);
2909 }
2910
2911 /// isUNPCKL_v_undef_Mask - Special case of isUNPCKLMask for canonical form
2912 /// of vector_shuffle v, v, <0, 4, 1, 5>, i.e. vector_shuffle v, undef,
2913 /// <0, 0, 1, 1>
2914 static bool isUNPCKL_v_undef_Mask(const SmallVectorImpl<int> &Mask, EVT VT) {
2915   int NumElems = VT.getVectorNumElements();
2916   if (NumElems != 2 && NumElems != 4 && NumElems != 8 && NumElems != 16)
2917     return false;
2918
2919   for (int i = 0, j = 0; i != NumElems; i += 2, ++j) {
2920     int BitI  = Mask[i];
2921     int BitI1 = Mask[i+1];
2922     if (!isUndefOrEqual(BitI, j))
2923       return false;
2924     if (!isUndefOrEqual(BitI1, j))
2925       return false;
2926   }
2927   return true;
2928 }
2929
2930 bool X86::isUNPCKL_v_undef_Mask(ShuffleVectorSDNode *N) {
2931   SmallVector<int, 8> M;
2932   N->getMask(M);
2933   return ::isUNPCKL_v_undef_Mask(M, N->getValueType(0));
2934 }
2935
2936 /// isUNPCKH_v_undef_Mask - Special case of isUNPCKHMask for canonical form
2937 /// of vector_shuffle v, v, <2, 6, 3, 7>, i.e. vector_shuffle v, undef,
2938 /// <2, 2, 3, 3>
2939 static bool isUNPCKH_v_undef_Mask(const SmallVectorImpl<int> &Mask, EVT VT) {
2940   int NumElems = VT.getVectorNumElements();
2941   if (NumElems != 2 && NumElems != 4 && NumElems != 8 && NumElems != 16)
2942     return false;
2943
2944   for (int i = 0, j = NumElems / 2; i != NumElems; i += 2, ++j) {
2945     int BitI  = Mask[i];
2946     int BitI1 = Mask[i+1];
2947     if (!isUndefOrEqual(BitI, j))
2948       return false;
2949     if (!isUndefOrEqual(BitI1, j))
2950       return false;
2951   }
2952   return true;
2953 }
2954
2955 bool X86::isUNPCKH_v_undef_Mask(ShuffleVectorSDNode *N) {
2956   SmallVector<int, 8> M;
2957   N->getMask(M);
2958   return ::isUNPCKH_v_undef_Mask(M, N->getValueType(0));
2959 }
2960
2961 /// isMOVLMask - Return true if the specified VECTOR_SHUFFLE operand
2962 /// specifies a shuffle of elements that is suitable for input to MOVSS,
2963 /// MOVSD, and MOVD, i.e. setting the lowest element.
2964 static bool isMOVLMask(const SmallVectorImpl<int> &Mask, EVT VT) {
2965   if (VT.getVectorElementType().getSizeInBits() < 32)
2966     return false;
2967
2968   int NumElts = VT.getVectorNumElements();
2969
2970   if (!isUndefOrEqual(Mask[0], NumElts))
2971     return false;
2972
2973   for (int i = 1; i < NumElts; ++i)
2974     if (!isUndefOrEqual(Mask[i], i))
2975       return false;
2976
2977   return true;
2978 }
2979
2980 bool X86::isMOVLMask(ShuffleVectorSDNode *N) {
2981   SmallVector<int, 8> M;
2982   N->getMask(M);
2983   return ::isMOVLMask(M, N->getValueType(0));
2984 }
2985
2986 /// isCommutedMOVL - Returns true if the shuffle mask is except the reverse
2987 /// of what x86 movss want. X86 movs requires the lowest  element to be lowest
2988 /// element of vector 2 and the other elements to come from vector 1 in order.
2989 static bool isCommutedMOVLMask(const SmallVectorImpl<int> &Mask, EVT VT,
2990                                bool V2IsSplat = false, bool V2IsUndef = false) {
2991   int NumOps = VT.getVectorNumElements();
2992   if (NumOps != 2 && NumOps != 4 && NumOps != 8 && NumOps != 16)
2993     return false;
2994
2995   if (!isUndefOrEqual(Mask[0], 0))
2996     return false;
2997
2998   for (int i = 1; i < NumOps; ++i)
2999     if (!(isUndefOrEqual(Mask[i], i+NumOps) ||
3000           (V2IsUndef && isUndefOrInRange(Mask[i], NumOps, NumOps*2)) ||
3001           (V2IsSplat && isUndefOrEqual(Mask[i], NumOps))))
3002       return false;
3003
3004   return true;
3005 }
3006
3007 static bool isCommutedMOVL(ShuffleVectorSDNode *N, bool V2IsSplat = false,
3008                            bool V2IsUndef = false) {
3009   SmallVector<int, 8> M;
3010   N->getMask(M);
3011   return isCommutedMOVLMask(M, N->getValueType(0), V2IsSplat, V2IsUndef);
3012 }
3013
3014 /// isMOVSHDUPMask - Return true if the specified VECTOR_SHUFFLE operand
3015 /// specifies a shuffle of elements that is suitable for input to MOVSHDUP.
3016 bool X86::isMOVSHDUPMask(ShuffleVectorSDNode *N) {
3017   if (N->getValueType(0).getVectorNumElements() != 4)
3018     return false;
3019
3020   // Expect 1, 1, 3, 3
3021   for (unsigned i = 0; i < 2; ++i) {
3022     int Elt = N->getMaskElt(i);
3023     if (Elt >= 0 && Elt != 1)
3024       return false;
3025   }
3026
3027   bool HasHi = false;
3028   for (unsigned i = 2; i < 4; ++i) {
3029     int Elt = N->getMaskElt(i);
3030     if (Elt >= 0 && Elt != 3)
3031       return false;
3032     if (Elt == 3)
3033       HasHi = true;
3034   }
3035   // Don't use movshdup if it can be done with a shufps.
3036   // FIXME: verify that matching u, u, 3, 3 is what we want.
3037   return HasHi;
3038 }
3039
3040 /// isMOVSLDUPMask - Return true if the specified VECTOR_SHUFFLE operand
3041 /// specifies a shuffle of elements that is suitable for input to MOVSLDUP.
3042 bool X86::isMOVSLDUPMask(ShuffleVectorSDNode *N) {
3043   if (N->getValueType(0).getVectorNumElements() != 4)
3044     return false;
3045
3046   // Expect 0, 0, 2, 2
3047   for (unsigned i = 0; i < 2; ++i)
3048     if (N->getMaskElt(i) > 0)
3049       return false;
3050
3051   bool HasHi = false;
3052   for (unsigned i = 2; i < 4; ++i) {
3053     int Elt = N->getMaskElt(i);
3054     if (Elt >= 0 && Elt != 2)
3055       return false;
3056     if (Elt == 2)
3057       HasHi = true;
3058   }
3059   // Don't use movsldup if it can be done with a shufps.
3060   return HasHi;
3061 }
3062
3063 /// isMOVDDUPMask - Return true if the specified VECTOR_SHUFFLE operand
3064 /// specifies a shuffle of elements that is suitable for input to MOVDDUP.
3065 bool X86::isMOVDDUPMask(ShuffleVectorSDNode *N) {
3066   int e = N->getValueType(0).getVectorNumElements() / 2;
3067
3068   for (int i = 0; i < e; ++i)
3069     if (!isUndefOrEqual(N->getMaskElt(i), i))
3070       return false;
3071   for (int i = 0; i < e; ++i)
3072     if (!isUndefOrEqual(N->getMaskElt(e+i), i))
3073       return false;
3074   return true;
3075 }
3076
3077 /// getShuffleSHUFImmediate - Return the appropriate immediate to shuffle
3078 /// the specified VECTOR_SHUFFLE mask with PSHUF* and SHUFP* instructions.
3079 unsigned X86::getShuffleSHUFImmediate(SDNode *N) {
3080   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
3081   int NumOperands = SVOp->getValueType(0).getVectorNumElements();
3082
3083   unsigned Shift = (NumOperands == 4) ? 2 : 1;
3084   unsigned Mask = 0;
3085   for (int i = 0; i < NumOperands; ++i) {
3086     int Val = SVOp->getMaskElt(NumOperands-i-1);
3087     if (Val < 0) Val = 0;
3088     if (Val >= NumOperands) Val -= NumOperands;
3089     Mask |= Val;
3090     if (i != NumOperands - 1)
3091       Mask <<= Shift;
3092   }
3093   return Mask;
3094 }
3095
3096 /// getShufflePSHUFHWImmediate - Return the appropriate immediate to shuffle
3097 /// the specified VECTOR_SHUFFLE mask with the PSHUFHW instruction.
3098 unsigned X86::getShufflePSHUFHWImmediate(SDNode *N) {
3099   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
3100   unsigned Mask = 0;
3101   // 8 nodes, but we only care about the last 4.
3102   for (unsigned i = 7; i >= 4; --i) {
3103     int Val = SVOp->getMaskElt(i);
3104     if (Val >= 0)
3105       Mask |= (Val - 4);
3106     if (i != 4)
3107       Mask <<= 2;
3108   }
3109   return Mask;
3110 }
3111
3112 /// getShufflePSHUFLWImmediate - Return the appropriate immediate to shuffle
3113 /// the specified VECTOR_SHUFFLE mask with the PSHUFLW instruction.
3114 unsigned X86::getShufflePSHUFLWImmediate(SDNode *N) {
3115   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
3116   unsigned Mask = 0;
3117   // 8 nodes, but we only care about the first 4.
3118   for (int i = 3; i >= 0; --i) {
3119     int Val = SVOp->getMaskElt(i);
3120     if (Val >= 0)
3121       Mask |= Val;
3122     if (i != 0)
3123       Mask <<= 2;
3124   }
3125   return Mask;
3126 }
3127
3128 /// getShufflePALIGNRImmediate - Return the appropriate immediate to shuffle
3129 /// the specified VECTOR_SHUFFLE mask with the PALIGNR instruction.
3130 unsigned X86::getShufflePALIGNRImmediate(SDNode *N) {
3131   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
3132   EVT VVT = N->getValueType(0);
3133   unsigned EltSize = VVT.getVectorElementType().getSizeInBits() >> 3;
3134   int Val = 0;
3135
3136   unsigned i, e;
3137   for (i = 0, e = VVT.getVectorNumElements(); i != e; ++i) {
3138     Val = SVOp->getMaskElt(i);
3139     if (Val >= 0)
3140       break;
3141   }
3142   return (Val - i) * EltSize;
3143 }
3144
3145 /// isZeroNode - Returns true if Elt is a constant zero or a floating point
3146 /// constant +0.0.
3147 bool X86::isZeroNode(SDValue Elt) {
3148   return ((isa<ConstantSDNode>(Elt) &&
3149            cast<ConstantSDNode>(Elt)->getZExtValue() == 0) ||
3150           (isa<ConstantFPSDNode>(Elt) &&
3151            cast<ConstantFPSDNode>(Elt)->getValueAPF().isPosZero()));
3152 }
3153
3154 /// CommuteVectorShuffle - Swap vector_shuffle operands as well as values in
3155 /// their permute mask.
3156 static SDValue CommuteVectorShuffle(ShuffleVectorSDNode *SVOp,
3157                                     SelectionDAG &DAG) {
3158   EVT VT = SVOp->getValueType(0);
3159   unsigned NumElems = VT.getVectorNumElements();
3160   SmallVector<int, 8> MaskVec;
3161
3162   for (unsigned i = 0; i != NumElems; ++i) {
3163     int idx = SVOp->getMaskElt(i);
3164     if (idx < 0)
3165       MaskVec.push_back(idx);
3166     else if (idx < (int)NumElems)
3167       MaskVec.push_back(idx + NumElems);
3168     else
3169       MaskVec.push_back(idx - NumElems);
3170   }
3171   return DAG.getVectorShuffle(VT, SVOp->getDebugLoc(), SVOp->getOperand(1),
3172                               SVOp->getOperand(0), &MaskVec[0]);
3173 }
3174
3175 /// CommuteVectorShuffleMask - Change values in a shuffle permute mask assuming
3176 /// the two vector operands have swapped position.
3177 static void CommuteVectorShuffleMask(SmallVectorImpl<int> &Mask, EVT VT) {
3178   unsigned NumElems = VT.getVectorNumElements();
3179   for (unsigned i = 0; i != NumElems; ++i) {
3180     int idx = Mask[i];
3181     if (idx < 0)
3182       continue;
3183     else if (idx < (int)NumElems)
3184       Mask[i] = idx + NumElems;
3185     else
3186       Mask[i] = idx - NumElems;
3187   }
3188 }
3189
3190 /// ShouldXformToMOVHLPS - Return true if the node should be transformed to
3191 /// match movhlps. The lower half elements should come from upper half of
3192 /// V1 (and in order), and the upper half elements should come from the upper
3193 /// half of V2 (and in order).
3194 static bool ShouldXformToMOVHLPS(ShuffleVectorSDNode *Op) {
3195   if (Op->getValueType(0).getVectorNumElements() != 4)
3196     return false;
3197   for (unsigned i = 0, e = 2; i != e; ++i)
3198     if (!isUndefOrEqual(Op->getMaskElt(i), i+2))
3199       return false;
3200   for (unsigned i = 2; i != 4; ++i)
3201     if (!isUndefOrEqual(Op->getMaskElt(i), i+4))
3202       return false;
3203   return true;
3204 }
3205
3206 /// isScalarLoadToVector - Returns true if the node is a scalar load that
3207 /// is promoted to a vector. It also returns the LoadSDNode by reference if
3208 /// required.
3209 static bool isScalarLoadToVector(SDNode *N, LoadSDNode **LD = NULL) {
3210   if (N->getOpcode() != ISD::SCALAR_TO_VECTOR)
3211     return false;
3212   N = N->getOperand(0).getNode();
3213   if (!ISD::isNON_EXTLoad(N))
3214     return false;
3215   if (LD)
3216     *LD = cast<LoadSDNode>(N);
3217   return true;
3218 }
3219
3220 /// ShouldXformToMOVLP{S|D} - Return true if the node should be transformed to
3221 /// match movlp{s|d}. The lower half elements should come from lower half of
3222 /// V1 (and in order), and the upper half elements should come from the upper
3223 /// half of V2 (and in order). And since V1 will become the source of the
3224 /// MOVLP, it must be either a vector load or a scalar load to vector.
3225 static bool ShouldXformToMOVLP(SDNode *V1, SDNode *V2,
3226                                ShuffleVectorSDNode *Op) {
3227   if (!ISD::isNON_EXTLoad(V1) && !isScalarLoadToVector(V1))
3228     return false;
3229   // Is V2 is a vector load, don't do this transformation. We will try to use
3230   // load folding shufps op.
3231   if (ISD::isNON_EXTLoad(V2))
3232     return false;
3233
3234   unsigned NumElems = Op->getValueType(0).getVectorNumElements();
3235
3236   if (NumElems != 2 && NumElems != 4)
3237     return false;
3238   for (unsigned i = 0, e = NumElems/2; i != e; ++i)
3239     if (!isUndefOrEqual(Op->getMaskElt(i), i))
3240       return false;
3241   for (unsigned i = NumElems/2; i != NumElems; ++i)
3242     if (!isUndefOrEqual(Op->getMaskElt(i), i+NumElems))
3243       return false;
3244   return true;
3245 }
3246
3247 /// isSplatVector - Returns true if N is a BUILD_VECTOR node whose elements are
3248 /// all the same.
3249 static bool isSplatVector(SDNode *N) {
3250   if (N->getOpcode() != ISD::BUILD_VECTOR)
3251     return false;
3252
3253   SDValue SplatValue = N->getOperand(0);
3254   for (unsigned i = 1, e = N->getNumOperands(); i != e; ++i)
3255     if (N->getOperand(i) != SplatValue)
3256       return false;
3257   return true;
3258 }
3259
3260 /// isZeroShuffle - Returns true if N is a VECTOR_SHUFFLE that can be resolved
3261 /// to an zero vector.
3262 /// FIXME: move to dag combiner / method on ShuffleVectorSDNode
3263 static bool isZeroShuffle(ShuffleVectorSDNode *N) {
3264   SDValue V1 = N->getOperand(0);
3265   SDValue V2 = N->getOperand(1);
3266   unsigned NumElems = N->getValueType(0).getVectorNumElements();
3267   for (unsigned i = 0; i != NumElems; ++i) {
3268     int Idx = N->getMaskElt(i);
3269     if (Idx >= (int)NumElems) {
3270       unsigned Opc = V2.getOpcode();
3271       if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V2.getNode()))
3272         continue;
3273       if (Opc != ISD::BUILD_VECTOR ||
3274           !X86::isZeroNode(V2.getOperand(Idx-NumElems)))
3275         return false;
3276     } else if (Idx >= 0) {
3277       unsigned Opc = V1.getOpcode();
3278       if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V1.getNode()))
3279         continue;
3280       if (Opc != ISD::BUILD_VECTOR ||
3281           !X86::isZeroNode(V1.getOperand(Idx)))
3282         return false;
3283     }
3284   }
3285   return true;
3286 }
3287
3288 /// getZeroVector - Returns a vector of specified type with all zero elements.
3289 ///
3290 static SDValue getZeroVector(EVT VT, bool HasSSE2, SelectionDAG &DAG,
3291                              DebugLoc dl) {
3292   assert(VT.isVector() && "Expected a vector type");
3293
3294   // Always build zero vectors as <4 x i32> or <2 x i32> bitcasted to their dest
3295   // type.  This ensures they get CSE'd.
3296   SDValue Vec;
3297   if (VT.getSizeInBits() == 64) { // MMX
3298     SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
3299     Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v2i32, Cst, Cst);
3300   } else if (HasSSE2) {  // SSE2
3301     SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
3302     Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
3303   } else { // SSE1
3304     SDValue Cst = DAG.getTargetConstantFP(+0.0, MVT::f32);
3305     Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4f32, Cst, Cst, Cst, Cst);
3306   }
3307   return DAG.getNode(ISD::BIT_CONVERT, dl, VT, Vec);
3308 }
3309
3310 /// getOnesVector - Returns a vector of specified type with all bits set.
3311 ///
3312 static SDValue getOnesVector(EVT VT, SelectionDAG &DAG, DebugLoc dl) {
3313   assert(VT.isVector() && "Expected a vector type");
3314
3315   // Always build ones vectors as <4 x i32> or <2 x i32> bitcasted to their dest
3316   // type.  This ensures they get CSE'd.
3317   SDValue Cst = DAG.getTargetConstant(~0U, MVT::i32);
3318   SDValue Vec;
3319   if (VT.getSizeInBits() == 64)  // MMX
3320     Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v2i32, Cst, Cst);
3321   else                                              // SSE
3322     Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
3323   return DAG.getNode(ISD::BIT_CONVERT, dl, VT, Vec);
3324 }
3325
3326
3327 /// NormalizeMask - V2 is a splat, modify the mask (if needed) so all elements
3328 /// that point to V2 points to its first element.
3329 static SDValue NormalizeMask(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
3330   EVT VT = SVOp->getValueType(0);
3331   unsigned NumElems = VT.getVectorNumElements();
3332
3333   bool Changed = false;
3334   SmallVector<int, 8> MaskVec;
3335   SVOp->getMask(MaskVec);
3336
3337   for (unsigned i = 0; i != NumElems; ++i) {
3338     if (MaskVec[i] > (int)NumElems) {
3339       MaskVec[i] = NumElems;
3340       Changed = true;
3341     }
3342   }
3343   if (Changed)
3344     return DAG.getVectorShuffle(VT, SVOp->getDebugLoc(), SVOp->getOperand(0),
3345                                 SVOp->getOperand(1), &MaskVec[0]);
3346   return SDValue(SVOp, 0);
3347 }
3348
3349 /// getMOVLMask - Returns a vector_shuffle mask for an movs{s|d}, movd
3350 /// operation of specified width.
3351 static SDValue getMOVL(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
3352                        SDValue V2) {
3353   unsigned NumElems = VT.getVectorNumElements();
3354   SmallVector<int, 8> Mask;
3355   Mask.push_back(NumElems);
3356   for (unsigned i = 1; i != NumElems; ++i)
3357     Mask.push_back(i);
3358   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
3359 }
3360
3361 /// getUnpackl - Returns a vector_shuffle node for an unpackl operation.
3362 static SDValue getUnpackl(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
3363                           SDValue V2) {
3364   unsigned NumElems = VT.getVectorNumElements();
3365   SmallVector<int, 8> Mask;
3366   for (unsigned i = 0, e = NumElems/2; i != e; ++i) {
3367     Mask.push_back(i);
3368     Mask.push_back(i + NumElems);
3369   }
3370   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
3371 }
3372
3373 /// getUnpackhMask - Returns a vector_shuffle node for an unpackh operation.
3374 static SDValue getUnpackh(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
3375                           SDValue V2) {
3376   unsigned NumElems = VT.getVectorNumElements();
3377   unsigned Half = NumElems/2;
3378   SmallVector<int, 8> Mask;
3379   for (unsigned i = 0; i != Half; ++i) {
3380     Mask.push_back(i + Half);
3381     Mask.push_back(i + NumElems + Half);
3382   }
3383   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
3384 }
3385
3386 /// PromoteSplat - Promote a splat of v4f32, v8i16 or v16i8 to v4i32.
3387 static SDValue PromoteSplat(ShuffleVectorSDNode *SV, SelectionDAG &DAG,
3388                             bool HasSSE2) {
3389   if (SV->getValueType(0).getVectorNumElements() <= 4)
3390     return SDValue(SV, 0);
3391
3392   EVT PVT = MVT::v4f32;
3393   EVT VT = SV->getValueType(0);
3394   DebugLoc dl = SV->getDebugLoc();
3395   SDValue V1 = SV->getOperand(0);
3396   int NumElems = VT.getVectorNumElements();
3397   int EltNo = SV->getSplatIndex();
3398
3399   // unpack elements to the correct location
3400   while (NumElems > 4) {
3401     if (EltNo < NumElems/2) {
3402       V1 = getUnpackl(DAG, dl, VT, V1, V1);
3403     } else {
3404       V1 = getUnpackh(DAG, dl, VT, V1, V1);
3405       EltNo -= NumElems/2;
3406     }
3407     NumElems >>= 1;
3408   }
3409
3410   // Perform the splat.
3411   int SplatMask[4] = { EltNo, EltNo, EltNo, EltNo };
3412   V1 = DAG.getNode(ISD::BIT_CONVERT, dl, PVT, V1);
3413   V1 = DAG.getVectorShuffle(PVT, dl, V1, DAG.getUNDEF(PVT), &SplatMask[0]);
3414   return DAG.getNode(ISD::BIT_CONVERT, dl, VT, V1);
3415 }
3416
3417 /// getShuffleVectorZeroOrUndef - Return a vector_shuffle of the specified
3418 /// vector of zero or undef vector.  This produces a shuffle where the low
3419 /// element of V2 is swizzled into the zero/undef vector, landing at element
3420 /// Idx.  This produces a shuffle mask like 4,1,2,3 (idx=0) or  0,1,2,4 (idx=3).
3421 static SDValue getShuffleVectorZeroOrUndef(SDValue V2, unsigned Idx,
3422                                              bool isZero, bool HasSSE2,
3423                                              SelectionDAG &DAG) {
3424   EVT VT = V2.getValueType();
3425   SDValue V1 = isZero
3426     ? getZeroVector(VT, HasSSE2, DAG, V2.getDebugLoc()) : DAG.getUNDEF(VT);
3427   unsigned NumElems = VT.getVectorNumElements();
3428   SmallVector<int, 16> MaskVec;
3429   for (unsigned i = 0; i != NumElems; ++i)
3430     // If this is the insertion idx, put the low elt of V2 here.
3431     MaskVec.push_back(i == Idx ? NumElems : i);
3432   return DAG.getVectorShuffle(VT, V2.getDebugLoc(), V1, V2, &MaskVec[0]);
3433 }
3434
3435 /// getNumOfConsecutiveZeros - Return the number of elements in a result of
3436 /// a shuffle that is zero.
3437 static
3438 unsigned getNumOfConsecutiveZeros(ShuffleVectorSDNode *SVOp, int NumElems,
3439                                   bool Low, SelectionDAG &DAG) {
3440   unsigned NumZeros = 0;
3441   for (int i = 0; i < NumElems; ++i) {
3442     unsigned Index = Low ? i : NumElems-i-1;
3443     int Idx = SVOp->getMaskElt(Index);
3444     if (Idx < 0) {
3445       ++NumZeros;
3446       continue;
3447     }
3448     SDValue Elt = DAG.getShuffleScalarElt(SVOp, Index);
3449     if (Elt.getNode() && X86::isZeroNode(Elt))
3450       ++NumZeros;
3451     else
3452       break;
3453   }
3454   return NumZeros;
3455 }
3456
3457 /// isVectorShift - Returns true if the shuffle can be implemented as a
3458 /// logical left or right shift of a vector.
3459 /// FIXME: split into pslldqi, psrldqi, palignr variants.
3460 static bool isVectorShift(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
3461                           bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
3462   unsigned NumElems = SVOp->getValueType(0).getVectorNumElements();
3463
3464   isLeft = true;
3465   unsigned NumZeros = getNumOfConsecutiveZeros(SVOp, NumElems, true, DAG);
3466   if (!NumZeros) {
3467     isLeft = false;
3468     NumZeros = getNumOfConsecutiveZeros(SVOp, NumElems, false, DAG);
3469     if (!NumZeros)
3470       return false;
3471   }
3472   bool SeenV1 = false;
3473   bool SeenV2 = false;
3474   for (unsigned i = NumZeros; i < NumElems; ++i) {
3475     unsigned Val = isLeft ? (i - NumZeros) : i;
3476     int Idx_ = SVOp->getMaskElt(isLeft ? i : (i - NumZeros));
3477     if (Idx_ < 0)
3478       continue;
3479     unsigned Idx = (unsigned) Idx_;
3480     if (Idx < NumElems)
3481       SeenV1 = true;
3482     else {
3483       Idx -= NumElems;
3484       SeenV2 = true;
3485     }
3486     if (Idx != Val)
3487       return false;
3488   }
3489   if (SeenV1 && SeenV2)
3490     return false;
3491
3492   ShVal = SeenV1 ? SVOp->getOperand(0) : SVOp->getOperand(1);
3493   ShAmt = NumZeros;
3494   return true;
3495 }
3496
3497
3498 /// LowerBuildVectorv16i8 - Custom lower build_vector of v16i8.
3499 ///
3500 static SDValue LowerBuildVectorv16i8(SDValue Op, unsigned NonZeros,
3501                                        unsigned NumNonZero, unsigned NumZero,
3502                                        SelectionDAG &DAG,
3503                                        const TargetLowering &TLI) {
3504   if (NumNonZero > 8)
3505     return SDValue();
3506
3507   DebugLoc dl = Op.getDebugLoc();
3508   SDValue V(0, 0);
3509   bool First = true;
3510   for (unsigned i = 0; i < 16; ++i) {
3511     bool ThisIsNonZero = (NonZeros & (1 << i)) != 0;
3512     if (ThisIsNonZero && First) {
3513       if (NumZero)
3514         V = getZeroVector(MVT::v8i16, true, DAG, dl);
3515       else
3516         V = DAG.getUNDEF(MVT::v8i16);
3517       First = false;
3518     }
3519
3520     if ((i & 1) != 0) {
3521       SDValue ThisElt(0, 0), LastElt(0, 0);
3522       bool LastIsNonZero = (NonZeros & (1 << (i-1))) != 0;
3523       if (LastIsNonZero) {
3524         LastElt = DAG.getNode(ISD::ZERO_EXTEND, dl,
3525                               MVT::i16, Op.getOperand(i-1));
3526       }
3527       if (ThisIsNonZero) {
3528         ThisElt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i16, Op.getOperand(i));
3529         ThisElt = DAG.getNode(ISD::SHL, dl, MVT::i16,
3530                               ThisElt, DAG.getConstant(8, MVT::i8));
3531         if (LastIsNonZero)
3532           ThisElt = DAG.getNode(ISD::OR, dl, MVT::i16, ThisElt, LastElt);
3533       } else
3534         ThisElt = LastElt;
3535
3536       if (ThisElt.getNode())
3537         V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, V, ThisElt,
3538                         DAG.getIntPtrConstant(i/2));
3539     }
3540   }
3541
3542   return DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v16i8, V);
3543 }
3544
3545 /// LowerBuildVectorv8i16 - Custom lower build_vector of v8i16.
3546 ///
3547 static SDValue LowerBuildVectorv8i16(SDValue Op, unsigned NonZeros,
3548                                      unsigned NumNonZero, unsigned NumZero,
3549                                      SelectionDAG &DAG,
3550                                      const TargetLowering &TLI) {
3551   if (NumNonZero > 4)
3552     return SDValue();
3553
3554   DebugLoc dl = Op.getDebugLoc();
3555   SDValue V(0, 0);
3556   bool First = true;
3557   for (unsigned i = 0; i < 8; ++i) {
3558     bool isNonZero = (NonZeros & (1 << i)) != 0;
3559     if (isNonZero) {
3560       if (First) {
3561         if (NumZero)
3562           V = getZeroVector(MVT::v8i16, true, DAG, dl);
3563         else
3564           V = DAG.getUNDEF(MVT::v8i16);
3565         First = false;
3566       }
3567       V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl,
3568                       MVT::v8i16, V, Op.getOperand(i),
3569                       DAG.getIntPtrConstant(i));
3570     }
3571   }
3572
3573   return V;
3574 }
3575
3576 /// getVShift - Return a vector logical shift node.
3577 ///
3578 static SDValue getVShift(bool isLeft, EVT VT, SDValue SrcOp,
3579                          unsigned NumBits, SelectionDAG &DAG,
3580                          const TargetLowering &TLI, DebugLoc dl) {
3581   bool isMMX = VT.getSizeInBits() == 64;
3582   EVT ShVT = isMMX ? MVT::v1i64 : MVT::v2i64;
3583   unsigned Opc = isLeft ? X86ISD::VSHL : X86ISD::VSRL;
3584   SrcOp = DAG.getNode(ISD::BIT_CONVERT, dl, ShVT, SrcOp);
3585   return DAG.getNode(ISD::BIT_CONVERT, dl, VT,
3586                      DAG.getNode(Opc, dl, ShVT, SrcOp,
3587                              DAG.getConstant(NumBits, TLI.getShiftAmountTy())));
3588 }
3589
3590 SDValue
3591 X86TargetLowering::LowerAsSplatVectorLoad(SDValue SrcOp, EVT VT, DebugLoc dl,
3592                                           SelectionDAG &DAG) const {
3593   
3594   // Check if the scalar load can be widened into a vector load. And if
3595   // the address is "base + cst" see if the cst can be "absorbed" into
3596   // the shuffle mask.
3597   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(SrcOp)) {
3598     SDValue Ptr = LD->getBasePtr();
3599     if (!ISD::isNormalLoad(LD) || LD->isVolatile())
3600       return SDValue();
3601     EVT PVT = LD->getValueType(0);
3602     if (PVT != MVT::i32 && PVT != MVT::f32)
3603       return SDValue();
3604
3605     int FI = -1;
3606     int64_t Offset = 0;
3607     if (FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr)) {
3608       FI = FINode->getIndex();
3609       Offset = 0;
3610     } else if (Ptr.getOpcode() == ISD::ADD &&
3611                isa<ConstantSDNode>(Ptr.getOperand(1)) &&
3612                isa<FrameIndexSDNode>(Ptr.getOperand(0))) {
3613       FI = cast<FrameIndexSDNode>(Ptr.getOperand(0))->getIndex();
3614       Offset = Ptr.getConstantOperandVal(1);
3615       Ptr = Ptr.getOperand(0);
3616     } else {
3617       return SDValue();
3618     }
3619
3620     SDValue Chain = LD->getChain();
3621     // Make sure the stack object alignment is at least 16.
3622     MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
3623     if (DAG.InferPtrAlignment(Ptr) < 16) {
3624       if (MFI->isFixedObjectIndex(FI)) {
3625         // Can't change the alignment. FIXME: It's possible to compute
3626         // the exact stack offset and reference FI + adjust offset instead.
3627         // If someone *really* cares about this. That's the way to implement it.
3628         return SDValue();
3629       } else {
3630         MFI->setObjectAlignment(FI, 16);
3631       }
3632     }
3633
3634     // (Offset % 16) must be multiple of 4. Then address is then
3635     // Ptr + (Offset & ~15).
3636     if (Offset < 0)
3637       return SDValue();
3638     if ((Offset % 16) & 3)
3639       return SDValue();
3640     int64_t StartOffset = Offset & ~15;
3641     if (StartOffset)
3642       Ptr = DAG.getNode(ISD::ADD, Ptr.getDebugLoc(), Ptr.getValueType(),
3643                         Ptr,DAG.getConstant(StartOffset, Ptr.getValueType()));
3644
3645     int EltNo = (Offset - StartOffset) >> 2;
3646     int Mask[4] = { EltNo, EltNo, EltNo, EltNo };
3647     EVT VT = (PVT == MVT::i32) ? MVT::v4i32 : MVT::v4f32;
3648     SDValue V1 = DAG.getLoad(VT, dl, Chain, Ptr,LD->getSrcValue(),0,
3649                              false, false, 0);
3650     // Canonicalize it to a v4i32 shuffle.
3651     V1 = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v4i32, V1);
3652     return DAG.getNode(ISD::BIT_CONVERT, dl, VT,
3653                        DAG.getVectorShuffle(MVT::v4i32, dl, V1,
3654                                             DAG.getUNDEF(MVT::v4i32), &Mask[0]));
3655   }
3656
3657   return SDValue();
3658 }
3659
3660 /// EltsFromConsecutiveLoads - Given the initializing elements 'Elts' of a 
3661 /// vector of type 'VT', see if the elements can be replaced by a single large 
3662 /// load which has the same value as a build_vector whose operands are 'elts'.
3663 ///
3664 /// Example: <load i32 *a, load i32 *a+4, undef, undef> -> zextload a
3665 /// 
3666 /// FIXME: we'd also like to handle the case where the last elements are zero
3667 /// rather than undef via VZEXT_LOAD, but we do not detect that case today.
3668 /// There's even a handy isZeroNode for that purpose.
3669 static SDValue EltsFromConsecutiveLoads(EVT VT, SmallVectorImpl<SDValue> &Elts,
3670                                         DebugLoc &dl, SelectionDAG &DAG) {
3671   EVT EltVT = VT.getVectorElementType();
3672   unsigned NumElems = Elts.size();
3673   
3674   LoadSDNode *LDBase = NULL;
3675   unsigned LastLoadedElt = -1U;
3676   
3677   // For each element in the initializer, see if we've found a load or an undef.
3678   // If we don't find an initial load element, or later load elements are 
3679   // non-consecutive, bail out.
3680   for (unsigned i = 0; i < NumElems; ++i) {
3681     SDValue Elt = Elts[i];
3682     
3683     if (!Elt.getNode() ||
3684         (Elt.getOpcode() != ISD::UNDEF && !ISD::isNON_EXTLoad(Elt.getNode())))
3685       return SDValue();
3686     if (!LDBase) {
3687       if (Elt.getNode()->getOpcode() == ISD::UNDEF)
3688         return SDValue();
3689       LDBase = cast<LoadSDNode>(Elt.getNode());
3690       LastLoadedElt = i;
3691       continue;
3692     }
3693     if (Elt.getOpcode() == ISD::UNDEF)
3694       continue;
3695
3696     LoadSDNode *LD = cast<LoadSDNode>(Elt);
3697     if (!DAG.isConsecutiveLoad(LD, LDBase, EltVT.getSizeInBits()/8, i))
3698       return SDValue();
3699     LastLoadedElt = i;
3700   }
3701
3702   // If we have found an entire vector of loads and undefs, then return a large
3703   // load of the entire vector width starting at the base pointer.  If we found
3704   // consecutive loads for the low half, generate a vzext_load node.
3705   if (LastLoadedElt == NumElems - 1) {
3706     if (DAG.InferPtrAlignment(LDBase->getBasePtr()) >= 16)
3707       return DAG.getLoad(VT, dl, LDBase->getChain(), LDBase->getBasePtr(),
3708                          LDBase->getSrcValue(), LDBase->getSrcValueOffset(),
3709                          LDBase->isVolatile(), LDBase->isNonTemporal(), 0);
3710     return DAG.getLoad(VT, dl, LDBase->getChain(), LDBase->getBasePtr(),
3711                        LDBase->getSrcValue(), LDBase->getSrcValueOffset(),
3712                        LDBase->isVolatile(), LDBase->isNonTemporal(),
3713                        LDBase->getAlignment());
3714   } else if (NumElems == 4 && LastLoadedElt == 1) {
3715     SDVTList Tys = DAG.getVTList(MVT::v2i64, MVT::Other);
3716     SDValue Ops[] = { LDBase->getChain(), LDBase->getBasePtr() };
3717     SDValue ResNode = DAG.getNode(X86ISD::VZEXT_LOAD, dl, Tys, Ops, 2);
3718     return DAG.getNode(ISD::BIT_CONVERT, dl, VT, ResNode);
3719   }
3720   return SDValue();
3721 }
3722
3723 SDValue
3724 X86TargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG) const {
3725   DebugLoc dl = Op.getDebugLoc();
3726   // All zero's are handled with pxor, all one's are handled with pcmpeqd.
3727   if (ISD::isBuildVectorAllZeros(Op.getNode())
3728       || ISD::isBuildVectorAllOnes(Op.getNode())) {
3729     // Canonicalize this to either <4 x i32> or <2 x i32> (SSE vs MMX) to
3730     // 1) ensure the zero vectors are CSE'd, and 2) ensure that i64 scalars are
3731     // eliminated on x86-32 hosts.
3732     if (Op.getValueType() == MVT::v4i32 || Op.getValueType() == MVT::v2i32)
3733       return Op;
3734
3735     if (ISD::isBuildVectorAllOnes(Op.getNode()))
3736       return getOnesVector(Op.getValueType(), DAG, dl);
3737     return getZeroVector(Op.getValueType(), Subtarget->hasSSE2(), DAG, dl);
3738   }
3739
3740   EVT VT = Op.getValueType();
3741   EVT ExtVT = VT.getVectorElementType();
3742   unsigned EVTBits = ExtVT.getSizeInBits();
3743
3744   unsigned NumElems = Op.getNumOperands();
3745   unsigned NumZero  = 0;
3746   unsigned NumNonZero = 0;
3747   unsigned NonZeros = 0;
3748   bool IsAllConstants = true;
3749   SmallSet<SDValue, 8> Values;
3750   for (unsigned i = 0; i < NumElems; ++i) {
3751     SDValue Elt = Op.getOperand(i);
3752     if (Elt.getOpcode() == ISD::UNDEF)
3753       continue;
3754     Values.insert(Elt);
3755     if (Elt.getOpcode() != ISD::Constant &&
3756         Elt.getOpcode() != ISD::ConstantFP)
3757       IsAllConstants = false;
3758     if (X86::isZeroNode(Elt))
3759       NumZero++;
3760     else {
3761       NonZeros |= (1 << i);
3762       NumNonZero++;
3763     }
3764   }
3765
3766   if (NumNonZero == 0) {
3767     // All undef vector. Return an UNDEF.  All zero vectors were handled above.
3768     return DAG.getUNDEF(VT);
3769   }
3770
3771   // Special case for single non-zero, non-undef, element.
3772   if (NumNonZero == 1) {
3773     unsigned Idx = CountTrailingZeros_32(NonZeros);
3774     SDValue Item = Op.getOperand(Idx);
3775
3776     // If this is an insertion of an i64 value on x86-32, and if the top bits of
3777     // the value are obviously zero, truncate the value to i32 and do the
3778     // insertion that way.  Only do this if the value is non-constant or if the
3779     // value is a constant being inserted into element 0.  It is cheaper to do
3780     // a constant pool load than it is to do a movd + shuffle.
3781     if (ExtVT == MVT::i64 && !Subtarget->is64Bit() &&
3782         (!IsAllConstants || Idx == 0)) {
3783       if (DAG.MaskedValueIsZero(Item, APInt::getBitsSet(64, 32, 64))) {
3784         // Handle MMX and SSE both.
3785         EVT VecVT = VT == MVT::v2i64 ? MVT::v4i32 : MVT::v2i32;
3786         unsigned VecElts = VT == MVT::v2i64 ? 4 : 2;
3787
3788         // Truncate the value (which may itself be a constant) to i32, and
3789         // convert it to a vector with movd (S2V+shuffle to zero extend).
3790         Item = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Item);
3791         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VecVT, Item);
3792         Item = getShuffleVectorZeroOrUndef(Item, 0, true,
3793                                            Subtarget->hasSSE2(), DAG);
3794
3795         // Now we have our 32-bit value zero extended in the low element of
3796         // a vector.  If Idx != 0, swizzle it into place.
3797         if (Idx != 0) {
3798           SmallVector<int, 4> Mask;
3799           Mask.push_back(Idx);
3800           for (unsigned i = 1; i != VecElts; ++i)
3801             Mask.push_back(i);
3802           Item = DAG.getVectorShuffle(VecVT, dl, Item,
3803                                       DAG.getUNDEF(Item.getValueType()),
3804                                       &Mask[0]);
3805         }
3806         return DAG.getNode(ISD::BIT_CONVERT, dl, Op.getValueType(), Item);
3807       }
3808     }
3809
3810     // If we have a constant or non-constant insertion into the low element of
3811     // a vector, we can do this with SCALAR_TO_VECTOR + shuffle of zero into
3812     // the rest of the elements.  This will be matched as movd/movq/movss/movsd
3813     // depending on what the source datatype is.
3814     if (Idx == 0) {
3815       if (NumZero == 0) {
3816         return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
3817       } else if (ExtVT == MVT::i32 || ExtVT == MVT::f32 || ExtVT == MVT::f64 ||
3818           (ExtVT == MVT::i64 && Subtarget->is64Bit())) {
3819         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
3820         // Turn it into a MOVL (i.e. movss, movsd, or movd) to a zero vector.
3821         return getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget->hasSSE2(),
3822                                            DAG);
3823       } else if (ExtVT == MVT::i16 || ExtVT == MVT::i8) {
3824         Item = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, Item);
3825         EVT MiddleVT = VT.getSizeInBits() == 64 ? MVT::v2i32 : MVT::v4i32;
3826         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MiddleVT, Item);
3827         Item = getShuffleVectorZeroOrUndef(Item, 0, true,
3828                                            Subtarget->hasSSE2(), DAG);
3829         return DAG.getNode(ISD::BIT_CONVERT, dl, VT, Item);
3830       }
3831     }
3832
3833     // Is it a vector logical left shift?
3834     if (NumElems == 2 && Idx == 1 &&
3835         X86::isZeroNode(Op.getOperand(0)) &&
3836         !X86::isZeroNode(Op.getOperand(1))) {
3837       unsigned NumBits = VT.getSizeInBits();
3838       return getVShift(true, VT,
3839                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
3840                                    VT, Op.getOperand(1)),
3841                        NumBits/2, DAG, *this, dl);
3842     }
3843
3844     if (IsAllConstants) // Otherwise, it's better to do a constpool load.
3845       return SDValue();
3846
3847     // Otherwise, if this is a vector with i32 or f32 elements, and the element
3848     // is a non-constant being inserted into an element other than the low one,
3849     // we can't use a constant pool load.  Instead, use SCALAR_TO_VECTOR (aka
3850     // movd/movss) to move this into the low element, then shuffle it into
3851     // place.
3852     if (EVTBits == 32) {
3853       Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
3854
3855       // Turn it into a shuffle of zero and zero-extended scalar to vector.
3856       Item = getShuffleVectorZeroOrUndef(Item, 0, NumZero > 0,
3857                                          Subtarget->hasSSE2(), DAG);
3858       SmallVector<int, 8> MaskVec;
3859       for (unsigned i = 0; i < NumElems; i++)
3860         MaskVec.push_back(i == Idx ? 0 : 1);
3861       return DAG.getVectorShuffle(VT, dl, Item, DAG.getUNDEF(VT), &MaskVec[0]);
3862     }
3863   }
3864
3865   // Splat is obviously ok. Let legalizer expand it to a shuffle.
3866   if (Values.size() == 1) {
3867     if (EVTBits == 32) {
3868       // Instead of a shuffle like this:
3869       // shuffle (scalar_to_vector (load (ptr + 4))), undef, <0, 0, 0, 0>
3870       // Check if it's possible to issue this instead.
3871       // shuffle (vload ptr)), undef, <1, 1, 1, 1>
3872       unsigned Idx = CountTrailingZeros_32(NonZeros);
3873       SDValue Item = Op.getOperand(Idx);
3874       if (Op.getNode()->isOnlyUserOf(Item.getNode()))
3875         return LowerAsSplatVectorLoad(Item, VT, dl, DAG);
3876     }
3877     return SDValue();
3878   }
3879
3880   // A vector full of immediates; various special cases are already
3881   // handled, so this is best done with a single constant-pool load.
3882   if (IsAllConstants)
3883     return SDValue();
3884
3885   // Let legalizer expand 2-wide build_vectors.
3886   if (EVTBits == 64) {
3887     if (NumNonZero == 1) {
3888       // One half is zero or undef.
3889       unsigned Idx = CountTrailingZeros_32(NonZeros);
3890       SDValue V2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT,
3891                                  Op.getOperand(Idx));
3892       return getShuffleVectorZeroOrUndef(V2, Idx, true,
3893                                          Subtarget->hasSSE2(), DAG);
3894     }
3895     return SDValue();
3896   }
3897
3898   // If element VT is < 32 bits, convert it to inserts into a zero vector.
3899   if (EVTBits == 8 && NumElems == 16) {
3900     SDValue V = LowerBuildVectorv16i8(Op, NonZeros,NumNonZero,NumZero, DAG,
3901                                         *this);
3902     if (V.getNode()) return V;
3903   }
3904
3905   if (EVTBits == 16 && NumElems == 8) {
3906     SDValue V = LowerBuildVectorv8i16(Op, NonZeros,NumNonZero,NumZero, DAG,
3907                                         *this);
3908     if (V.getNode()) return V;
3909   }
3910
3911   // If element VT is == 32 bits, turn it into a number of shuffles.
3912   SmallVector<SDValue, 8> V;
3913   V.resize(NumElems);
3914   if (NumElems == 4 && NumZero > 0) {
3915     for (unsigned i = 0; i < 4; ++i) {
3916       bool isZero = !(NonZeros & (1 << i));
3917       if (isZero)
3918         V[i] = getZeroVector(VT, Subtarget->hasSSE2(), DAG, dl);
3919       else
3920         V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
3921     }
3922
3923     for (unsigned i = 0; i < 2; ++i) {
3924       switch ((NonZeros & (0x3 << i*2)) >> (i*2)) {
3925         default: break;
3926         case 0:
3927           V[i] = V[i*2];  // Must be a zero vector.
3928           break;
3929         case 1:
3930           V[i] = getMOVL(DAG, dl, VT, V[i*2+1], V[i*2]);
3931           break;
3932         case 2:
3933           V[i] = getMOVL(DAG, dl, VT, V[i*2], V[i*2+1]);
3934           break;
3935         case 3:
3936           V[i] = getUnpackl(DAG, dl, VT, V[i*2], V[i*2+1]);
3937           break;
3938       }
3939     }
3940
3941     SmallVector<int, 8> MaskVec;
3942     bool Reverse = (NonZeros & 0x3) == 2;
3943     for (unsigned i = 0; i < 2; ++i)
3944       MaskVec.push_back(Reverse ? 1-i : i);
3945     Reverse = ((NonZeros & (0x3 << 2)) >> 2) == 2;
3946     for (unsigned i = 0; i < 2; ++i)
3947       MaskVec.push_back(Reverse ? 1-i+NumElems : i+NumElems);
3948     return DAG.getVectorShuffle(VT, dl, V[0], V[1], &MaskVec[0]);
3949   }
3950
3951   if (Values.size() > 1 && VT.getSizeInBits() == 128) {
3952     // Check for a build vector of consecutive loads.
3953     for (unsigned i = 0; i < NumElems; ++i)
3954       V[i] = Op.getOperand(i);
3955     
3956     // Check for elements which are consecutive loads.
3957     SDValue LD = EltsFromConsecutiveLoads(VT, V, dl, DAG);
3958     if (LD.getNode())
3959       return LD;
3960     
3961     // For SSE 4.1, use inserts into undef.  
3962     if (getSubtarget()->hasSSE41()) {
3963       V[0] = DAG.getUNDEF(VT);
3964       for (unsigned i = 0; i < NumElems; ++i)
3965         if (Op.getOperand(i).getOpcode() != ISD::UNDEF)
3966           V[0] = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, V[0],
3967                              Op.getOperand(i), DAG.getIntPtrConstant(i));
3968       return V[0];
3969     }
3970     
3971     // Otherwise, expand into a number of unpckl*
3972     // e.g. for v4f32
3973     //   Step 1: unpcklps 0, 2 ==> X: <?, ?, 2, 0>
3974     //         : unpcklps 1, 3 ==> Y: <?, ?, 3, 1>
3975     //   Step 2: unpcklps X, Y ==>    <3, 2, 1, 0>
3976     for (unsigned i = 0; i < NumElems; ++i)
3977       V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
3978     NumElems >>= 1;
3979     while (NumElems != 0) {
3980       for (unsigned i = 0; i < NumElems; ++i)
3981         V[i] = getUnpackl(DAG, dl, VT, V[i], V[i + NumElems]);
3982       NumElems >>= 1;
3983     }
3984     return V[0];
3985   }
3986   return SDValue();
3987 }
3988
3989 SDValue
3990 X86TargetLowering::LowerCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) const {
3991   // We support concatenate two MMX registers and place them in a MMX
3992   // register.  This is better than doing a stack convert.
3993   DebugLoc dl = Op.getDebugLoc();
3994   EVT ResVT = Op.getValueType();
3995   assert(Op.getNumOperands() == 2);
3996   assert(ResVT == MVT::v2i64 || ResVT == MVT::v4i32 ||
3997          ResVT == MVT::v8i16 || ResVT == MVT::v16i8);
3998   int Mask[2];
3999   SDValue InVec = DAG.getNode(ISD::BIT_CONVERT,dl, MVT::v1i64, Op.getOperand(0));
4000   SDValue VecOp = DAG.getNode(X86ISD::MOVQ2DQ, dl, MVT::v2i64, InVec);
4001   InVec = Op.getOperand(1);
4002   if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR) {
4003     unsigned NumElts = ResVT.getVectorNumElements();
4004     VecOp = DAG.getNode(ISD::BIT_CONVERT, dl, ResVT, VecOp);
4005     VecOp = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, ResVT, VecOp,
4006                        InVec.getOperand(0), DAG.getIntPtrConstant(NumElts/2+1));
4007   } else {
4008     InVec = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v1i64, InVec);
4009     SDValue VecOp2 = DAG.getNode(X86ISD::MOVQ2DQ, dl, MVT::v2i64, InVec);
4010     Mask[0] = 0; Mask[1] = 2;
4011     VecOp = DAG.getVectorShuffle(MVT::v2i64, dl, VecOp, VecOp2, Mask);
4012   }
4013   return DAG.getNode(ISD::BIT_CONVERT, dl, ResVT, VecOp);
4014 }
4015
4016 // v8i16 shuffles - Prefer shuffles in the following order:
4017 // 1. [all]   pshuflw, pshufhw, optional move
4018 // 2. [ssse3] 1 x pshufb
4019 // 3. [ssse3] 2 x pshufb + 1 x por
4020 // 4. [all]   mov + pshuflw + pshufhw + N x (pextrw + pinsrw)
4021 static
4022 SDValue LowerVECTOR_SHUFFLEv8i16(ShuffleVectorSDNode *SVOp,
4023                                  SelectionDAG &DAG,
4024                                  const X86TargetLowering &TLI) {
4025   SDValue V1 = SVOp->getOperand(0);
4026   SDValue V2 = SVOp->getOperand(1);
4027   DebugLoc dl = SVOp->getDebugLoc();
4028   SmallVector<int, 8> MaskVals;
4029
4030   // Determine if more than 1 of the words in each of the low and high quadwords
4031   // of the result come from the same quadword of one of the two inputs.  Undef
4032   // mask values count as coming from any quadword, for better codegen.
4033   SmallVector<unsigned, 4> LoQuad(4);
4034   SmallVector<unsigned, 4> HiQuad(4);
4035   BitVector InputQuads(4);
4036   for (unsigned i = 0; i < 8; ++i) {
4037     SmallVectorImpl<unsigned> &Quad = i < 4 ? LoQuad : HiQuad;
4038     int EltIdx = SVOp->getMaskElt(i);
4039     MaskVals.push_back(EltIdx);
4040     if (EltIdx < 0) {
4041       ++Quad[0];
4042       ++Quad[1];
4043       ++Quad[2];
4044       ++Quad[3];
4045       continue;
4046     }
4047     ++Quad[EltIdx / 4];
4048     InputQuads.set(EltIdx / 4);
4049   }
4050
4051   int BestLoQuad = -1;
4052   unsigned MaxQuad = 1;
4053   for (unsigned i = 0; i < 4; ++i) {
4054     if (LoQuad[i] > MaxQuad) {
4055       BestLoQuad = i;
4056       MaxQuad = LoQuad[i];
4057     }
4058   }
4059
4060   int BestHiQuad = -1;
4061   MaxQuad = 1;
4062   for (unsigned i = 0; i < 4; ++i) {
4063     if (HiQuad[i] > MaxQuad) {
4064       BestHiQuad = i;
4065       MaxQuad = HiQuad[i];
4066     }
4067   }
4068
4069   // For SSSE3, If all 8 words of the result come from only 1 quadword of each
4070   // of the two input vectors, shuffle them into one input vector so only a
4071   // single pshufb instruction is necessary. If There are more than 2 input
4072   // quads, disable the next transformation since it does not help SSSE3.
4073   bool V1Used = InputQuads[0] || InputQuads[1];
4074   bool V2Used = InputQuads[2] || InputQuads[3];
4075   if (TLI.getSubtarget()->hasSSSE3()) {
4076     if (InputQuads.count() == 2 && V1Used && V2Used) {
4077       BestLoQuad = InputQuads.find_first();
4078       BestHiQuad = InputQuads.find_next(BestLoQuad);
4079     }
4080     if (InputQuads.count() > 2) {
4081       BestLoQuad = -1;
4082       BestHiQuad = -1;
4083     }
4084   }
4085
4086   // If BestLoQuad or BestHiQuad are set, shuffle the quads together and update
4087   // the shuffle mask.  If a quad is scored as -1, that means that it contains
4088   // words from all 4 input quadwords.
4089   SDValue NewV;
4090   if (BestLoQuad >= 0 || BestHiQuad >= 0) {
4091     SmallVector<int, 8> MaskV;
4092     MaskV.push_back(BestLoQuad < 0 ? 0 : BestLoQuad);
4093     MaskV.push_back(BestHiQuad < 0 ? 1 : BestHiQuad);
4094     NewV = DAG.getVectorShuffle(MVT::v2i64, dl,
4095                   DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v2i64, V1),
4096                   DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v2i64, V2), &MaskV[0]);
4097     NewV = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v8i16, NewV);
4098
4099     // Rewrite the MaskVals and assign NewV to V1 if NewV now contains all the
4100     // source words for the shuffle, to aid later transformations.
4101     bool AllWordsInNewV = true;
4102     bool InOrder[2] = { true, true };
4103     for (unsigned i = 0; i != 8; ++i) {
4104       int idx = MaskVals[i];
4105       if (idx != (int)i)
4106         InOrder[i/4] = false;
4107       if (idx < 0 || (idx/4) == BestLoQuad || (idx/4) == BestHiQuad)
4108         continue;
4109       AllWordsInNewV = false;
4110       break;
4111     }
4112
4113     bool pshuflw = AllWordsInNewV, pshufhw = AllWordsInNewV;
4114     if (AllWordsInNewV) {
4115       for (int i = 0; i != 8; ++i) {
4116         int idx = MaskVals[i];
4117         if (idx < 0)
4118           continue;
4119         idx = MaskVals[i] = (idx / 4) == BestLoQuad ? (idx & 3) : (idx & 3) + 4;
4120         if ((idx != i) && idx < 4)
4121           pshufhw = false;
4122         if ((idx != i) && idx > 3)
4123           pshuflw = false;
4124       }
4125       V1 = NewV;
4126       V2Used = false;
4127       BestLoQuad = 0;
4128       BestHiQuad = 1;
4129     }
4130
4131     // If we've eliminated the use of V2, and the new mask is a pshuflw or
4132     // pshufhw, that's as cheap as it gets.  Return the new shuffle.
4133     if ((pshufhw && InOrder[0]) || (pshuflw && InOrder[1])) {
4134       return DAG.getVectorShuffle(MVT::v8i16, dl, NewV,
4135                                   DAG.getUNDEF(MVT::v8i16), &MaskVals[0]);
4136     }
4137   }
4138
4139   // If we have SSSE3, and all words of the result are from 1 input vector,
4140   // case 2 is generated, otherwise case 3 is generated.  If no SSSE3
4141   // is present, fall back to case 4.
4142   if (TLI.getSubtarget()->hasSSSE3()) {
4143     SmallVector<SDValue,16> pshufbMask;
4144
4145     // If we have elements from both input vectors, set the high bit of the
4146     // shuffle mask element to zero out elements that come from V2 in the V1
4147     // mask, and elements that come from V1 in the V2 mask, so that the two
4148     // results can be OR'd together.
4149     bool TwoInputs = V1Used && V2Used;
4150     for (unsigned i = 0; i != 8; ++i) {
4151       int EltIdx = MaskVals[i] * 2;
4152       if (TwoInputs && (EltIdx >= 16)) {
4153         pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
4154         pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
4155         continue;
4156       }
4157       pshufbMask.push_back(DAG.getConstant(EltIdx,   MVT::i8));
4158       pshufbMask.push_back(DAG.getConstant(EltIdx+1, MVT::i8));
4159     }
4160     V1 = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v16i8, V1);
4161     V1 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V1,
4162                      DAG.getNode(ISD::BUILD_VECTOR, dl,
4163                                  MVT::v16i8, &pshufbMask[0], 16));
4164     if (!TwoInputs)
4165       return DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v8i16, V1);
4166
4167     // Calculate the shuffle mask for the second input, shuffle it, and
4168     // OR it with the first shuffled input.
4169     pshufbMask.clear();
4170     for (unsigned i = 0; i != 8; ++i) {
4171       int EltIdx = MaskVals[i] * 2;
4172       if (EltIdx < 16) {
4173         pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
4174         pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
4175         continue;
4176       }
4177       pshufbMask.push_back(DAG.getConstant(EltIdx - 16, MVT::i8));
4178       pshufbMask.push_back(DAG.getConstant(EltIdx - 15, MVT::i8));
4179     }
4180     V2 = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v16i8, V2);
4181     V2 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V2,
4182                      DAG.getNode(ISD::BUILD_VECTOR, dl,
4183                                  MVT::v16i8, &pshufbMask[0], 16));
4184     V1 = DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2);
4185     return DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v8i16, V1);
4186   }
4187
4188   // If BestLoQuad >= 0, generate a pshuflw to put the low elements in order,
4189   // and update MaskVals with new element order.
4190   BitVector InOrder(8);
4191   if (BestLoQuad >= 0) {
4192     SmallVector<int, 8> MaskV;
4193     for (int i = 0; i != 4; ++i) {
4194       int idx = MaskVals[i];
4195       if (idx < 0) {
4196         MaskV.push_back(-1);
4197         InOrder.set(i);
4198       } else if ((idx / 4) == BestLoQuad) {
4199         MaskV.push_back(idx & 3);
4200         InOrder.set(i);
4201       } else {
4202         MaskV.push_back(-1);
4203       }
4204     }
4205     for (unsigned i = 4; i != 8; ++i)
4206       MaskV.push_back(i);
4207     NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::v8i16),
4208                                 &MaskV[0]);
4209   }
4210
4211   // If BestHi >= 0, generate a pshufhw to put the high elements in order,
4212   // and update MaskVals with the new element order.
4213   if (BestHiQuad >= 0) {
4214     SmallVector<int, 8> MaskV;
4215     for (unsigned i = 0; i != 4; ++i)
4216       MaskV.push_back(i);
4217     for (unsigned i = 4; i != 8; ++i) {
4218       int idx = MaskVals[i];
4219       if (idx < 0) {
4220         MaskV.push_back(-1);
4221         InOrder.set(i);
4222       } else if ((idx / 4) == BestHiQuad) {
4223         MaskV.push_back((idx & 3) + 4);
4224         InOrder.set(i);
4225       } else {
4226         MaskV.push_back(-1);
4227       }
4228     }
4229     NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::v8i16),
4230                                 &MaskV[0]);
4231   }
4232
4233   // In case BestHi & BestLo were both -1, which means each quadword has a word
4234   // from each of the four input quadwords, calculate the InOrder bitvector now
4235   // before falling through to the insert/extract cleanup.
4236   if (BestLoQuad == -1 && BestHiQuad == -1) {
4237     NewV = V1;
4238     for (int i = 0; i != 8; ++i)
4239       if (MaskVals[i] < 0 || MaskVals[i] == i)
4240         InOrder.set(i);
4241   }
4242
4243   // The other elements are put in the right place using pextrw and pinsrw.
4244   for (unsigned i = 0; i != 8; ++i) {
4245     if (InOrder[i])
4246       continue;
4247     int EltIdx = MaskVals[i];
4248     if (EltIdx < 0)
4249       continue;
4250     SDValue ExtOp = (EltIdx < 8)
4251     ? DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V1,
4252                   DAG.getIntPtrConstant(EltIdx))
4253     : DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V2,
4254                   DAG.getIntPtrConstant(EltIdx - 8));
4255     NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, ExtOp,
4256                        DAG.getIntPtrConstant(i));
4257   }
4258   return NewV;
4259 }
4260
4261 // v16i8 shuffles - Prefer shuffles in the following order:
4262 // 1. [ssse3] 1 x pshufb
4263 // 2. [ssse3] 2 x pshufb + 1 x por
4264 // 3. [all]   v8i16 shuffle + N x pextrw + rotate + pinsrw
4265 static
4266 SDValue LowerVECTOR_SHUFFLEv16i8(ShuffleVectorSDNode *SVOp,
4267                                  SelectionDAG &DAG,
4268                                  const X86TargetLowering &TLI) {
4269   SDValue V1 = SVOp->getOperand(0);
4270   SDValue V2 = SVOp->getOperand(1);
4271   DebugLoc dl = SVOp->getDebugLoc();
4272   SmallVector<int, 16> MaskVals;
4273   SVOp->getMask(MaskVals);
4274
4275   // If we have SSSE3, case 1 is generated when all result bytes come from
4276   // one of  the inputs.  Otherwise, case 2 is generated.  If no SSSE3 is
4277   // present, fall back to case 3.
4278   // FIXME: kill V2Only once shuffles are canonizalized by getNode.
4279   bool V1Only = true;
4280   bool V2Only = true;
4281   for (unsigned i = 0; i < 16; ++i) {
4282     int EltIdx = MaskVals[i];
4283     if (EltIdx < 0)
4284       continue;
4285     if (EltIdx < 16)
4286       V2Only = false;
4287     else
4288       V1Only = false;
4289   }
4290
4291   // If SSSE3, use 1 pshufb instruction per vector with elements in the result.
4292   if (TLI.getSubtarget()->hasSSSE3()) {
4293     SmallVector<SDValue,16> pshufbMask;
4294
4295     // If all result elements are from one input vector, then only translate
4296     // undef mask values to 0x80 (zero out result) in the pshufb mask.
4297     //
4298     // Otherwise, we have elements from both input vectors, and must zero out
4299     // elements that come from V2 in the first mask, and V1 in the second mask
4300     // so that we can OR them together.
4301     bool TwoInputs = !(V1Only || V2Only);
4302     for (unsigned i = 0; i != 16; ++i) {
4303       int EltIdx = MaskVals[i];
4304       if (EltIdx < 0 || (TwoInputs && EltIdx >= 16)) {
4305         pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
4306         continue;
4307       }
4308       pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8));
4309     }
4310     // If all the elements are from V2, assign it to V1 and return after
4311     // building the first pshufb.
4312     if (V2Only)
4313       V1 = V2;
4314     V1 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V1,
4315                      DAG.getNode(ISD::BUILD_VECTOR, dl,
4316                                  MVT::v16i8, &pshufbMask[0], 16));
4317     if (!TwoInputs)
4318       return V1;
4319
4320     // Calculate the shuffle mask for the second input, shuffle it, and
4321     // OR it with the first shuffled input.
4322     pshufbMask.clear();
4323     for (unsigned i = 0; i != 16; ++i) {
4324       int EltIdx = MaskVals[i];
4325       if (EltIdx < 16) {
4326         pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
4327         continue;
4328       }
4329       pshufbMask.push_back(DAG.getConstant(EltIdx - 16, MVT::i8));
4330     }
4331     V2 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V2,
4332                      DAG.getNode(ISD::BUILD_VECTOR, dl,
4333                                  MVT::v16i8, &pshufbMask[0], 16));
4334     return DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2);
4335   }
4336
4337   // No SSSE3 - Calculate in place words and then fix all out of place words
4338   // With 0-16 extracts & inserts.  Worst case is 16 bytes out of order from
4339   // the 16 different words that comprise the two doublequadword input vectors.
4340   V1 = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v8i16, V1);
4341   V2 = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v8i16, V2);
4342   SDValue NewV = V2Only ? V2 : V1;
4343   for (int i = 0; i != 8; ++i) {
4344     int Elt0 = MaskVals[i*2];
4345     int Elt1 = MaskVals[i*2+1];
4346
4347     // This word of the result is all undef, skip it.
4348     if (Elt0 < 0 && Elt1 < 0)
4349       continue;
4350
4351     // This word of the result is already in the correct place, skip it.
4352     if (V1Only && (Elt0 == i*2) && (Elt1 == i*2+1))
4353       continue;
4354     if (V2Only && (Elt0 == i*2+16) && (Elt1 == i*2+17))
4355       continue;
4356
4357     SDValue Elt0Src = Elt0 < 16 ? V1 : V2;
4358     SDValue Elt1Src = Elt1 < 16 ? V1 : V2;
4359     SDValue InsElt;
4360
4361     // If Elt0 and Elt1 are defined, are consecutive, and can be load
4362     // using a single extract together, load it and store it.
4363     if ((Elt0 >= 0) && ((Elt0 + 1) == Elt1) && ((Elt0 & 1) == 0)) {
4364       InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src,
4365                            DAG.getIntPtrConstant(Elt1 / 2));
4366       NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt,
4367                         DAG.getIntPtrConstant(i));
4368       continue;
4369     }
4370
4371     // If Elt1 is defined, extract it from the appropriate source.  If the
4372     // source byte is not also odd, shift the extracted word left 8 bits
4373     // otherwise clear the bottom 8 bits if we need to do an or.
4374     if (Elt1 >= 0) {
4375       InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src,
4376                            DAG.getIntPtrConstant(Elt1 / 2));
4377       if ((Elt1 & 1) == 0)
4378         InsElt = DAG.getNode(ISD::SHL, dl, MVT::i16, InsElt,
4379                              DAG.getConstant(8, TLI.getShiftAmountTy()));
4380       else if (Elt0 >= 0)
4381         InsElt = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt,
4382                              DAG.getConstant(0xFF00, MVT::i16));
4383     }
4384     // If Elt0 is defined, extract it from the appropriate source.  If the
4385     // source byte is not also even, shift the extracted word right 8 bits. If
4386     // Elt1 was also defined, OR the extracted values together before
4387     // inserting them in the result.
4388     if (Elt0 >= 0) {
4389       SDValue InsElt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16,
4390                                     Elt0Src, DAG.getIntPtrConstant(Elt0 / 2));
4391       if ((Elt0 & 1) != 0)
4392         InsElt0 = DAG.getNode(ISD::SRL, dl, MVT::i16, InsElt0,
4393                               DAG.getConstant(8, TLI.getShiftAmountTy()));
4394       else if (Elt1 >= 0)
4395         InsElt0 = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt0,
4396                              DAG.getConstant(0x00FF, MVT::i16));
4397       InsElt = Elt1 >= 0 ? DAG.getNode(ISD::OR, dl, MVT::i16, InsElt, InsElt0)
4398                          : InsElt0;
4399     }
4400     NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt,
4401                        DAG.getIntPtrConstant(i));
4402   }
4403   return DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v16i8, NewV);
4404 }
4405
4406 /// RewriteAsNarrowerShuffle - Try rewriting v8i16 and v16i8 shuffles as 4 wide
4407 /// ones, or rewriting v4i32 / v2f32 as 2 wide ones if possible. This can be
4408 /// done when every pair / quad of shuffle mask elements point to elements in
4409 /// the right sequence. e.g.
4410 /// vector_shuffle <>, <>, < 3, 4, | 10, 11, | 0, 1, | 14, 15>
4411 static
4412 SDValue RewriteAsNarrowerShuffle(ShuffleVectorSDNode *SVOp,
4413                                  SelectionDAG &DAG,
4414                                  const TargetLowering &TLI, DebugLoc dl) {
4415   EVT VT = SVOp->getValueType(0);
4416   SDValue V1 = SVOp->getOperand(0);
4417   SDValue V2 = SVOp->getOperand(1);
4418   unsigned NumElems = VT.getVectorNumElements();
4419   unsigned NewWidth = (NumElems == 4) ? 2 : 4;
4420   EVT MaskVT = MVT::getIntVectorWithNumElements(NewWidth);
4421   EVT MaskEltVT = MaskVT.getVectorElementType();
4422   EVT NewVT = MaskVT;
4423   switch (VT.getSimpleVT().SimpleTy) {
4424   default: assert(false && "Unexpected!");
4425   case MVT::v4f32: NewVT = MVT::v2f64; break;
4426   case MVT::v4i32: NewVT = MVT::v2i64; break;
4427   case MVT::v8i16: NewVT = MVT::v4i32; break;
4428   case MVT::v16i8: NewVT = MVT::v4i32; break;
4429   }
4430
4431   if (NewWidth == 2) {
4432     if (VT.isInteger())
4433       NewVT = MVT::v2i64;
4434     else
4435       NewVT = MVT::v2f64;
4436   }
4437   int Scale = NumElems / NewWidth;
4438   SmallVector<int, 8> MaskVec;
4439   for (unsigned i = 0; i < NumElems; i += Scale) {
4440     int StartIdx = -1;
4441     for (int j = 0; j < Scale; ++j) {
4442       int EltIdx = SVOp->getMaskElt(i+j);
4443       if (EltIdx < 0)
4444         continue;
4445       if (StartIdx == -1)
4446         StartIdx = EltIdx - (EltIdx % Scale);
4447       if (EltIdx != StartIdx + j)
4448         return SDValue();
4449     }
4450     if (StartIdx == -1)
4451       MaskVec.push_back(-1);
4452     else
4453       MaskVec.push_back(StartIdx / Scale);
4454   }
4455
4456   V1 = DAG.getNode(ISD::BIT_CONVERT, dl, NewVT, V1);
4457   V2 = DAG.getNode(ISD::BIT_CONVERT, dl, NewVT, V2);
4458   return DAG.getVectorShuffle(NewVT, dl, V1, V2, &MaskVec[0]);
4459 }
4460
4461 /// getVZextMovL - Return a zero-extending vector move low node.
4462 ///
4463 static SDValue getVZextMovL(EVT VT, EVT OpVT,
4464                             SDValue SrcOp, SelectionDAG &DAG,
4465                             const X86Subtarget *Subtarget, DebugLoc dl) {
4466   if (VT == MVT::v2f64 || VT == MVT::v4f32) {
4467     LoadSDNode *LD = NULL;
4468     if (!isScalarLoadToVector(SrcOp.getNode(), &LD))
4469       LD = dyn_cast<LoadSDNode>(SrcOp);
4470     if (!LD) {
4471       // movssrr and movsdrr do not clear top bits. Try to use movd, movq
4472       // instead.
4473       MVT ExtVT = (OpVT == MVT::v2f64) ? MVT::i64 : MVT::i32;
4474       if ((ExtVT.SimpleTy != MVT::i64 || Subtarget->is64Bit()) &&
4475           SrcOp.getOpcode() == ISD::SCALAR_TO_VECTOR &&
4476           SrcOp.getOperand(0).getOpcode() == ISD::BIT_CONVERT &&
4477           SrcOp.getOperand(0).getOperand(0).getValueType() == ExtVT) {
4478         // PR2108
4479         OpVT = (OpVT == MVT::v2f64) ? MVT::v2i64 : MVT::v4i32;
4480         return DAG.getNode(ISD::BIT_CONVERT, dl, VT,
4481                            DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT,
4482                                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
4483                                                    OpVT,
4484                                                    SrcOp.getOperand(0)
4485                                                           .getOperand(0))));
4486       }
4487     }
4488   }
4489
4490   return DAG.getNode(ISD::BIT_CONVERT, dl, VT,
4491                      DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT,
4492                                  DAG.getNode(ISD::BIT_CONVERT, dl,
4493                                              OpVT, SrcOp)));
4494 }
4495
4496 /// LowerVECTOR_SHUFFLE_4wide - Handle all 4 wide cases with a number of
4497 /// shuffles.
4498 static SDValue
4499 LowerVECTOR_SHUFFLE_4wide(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
4500   SDValue V1 = SVOp->getOperand(0);
4501   SDValue V2 = SVOp->getOperand(1);
4502   DebugLoc dl = SVOp->getDebugLoc();
4503   EVT VT = SVOp->getValueType(0);
4504
4505   SmallVector<std::pair<int, int>, 8> Locs;
4506   Locs.resize(4);
4507   SmallVector<int, 8> Mask1(4U, -1);
4508   SmallVector<int, 8> PermMask;
4509   SVOp->getMask(PermMask);
4510
4511   unsigned NumHi = 0;
4512   unsigned NumLo = 0;
4513   for (unsigned i = 0; i != 4; ++i) {
4514     int Idx = PermMask[i];
4515     if (Idx < 0) {
4516       Locs[i] = std::make_pair(-1, -1);
4517     } else {
4518       assert(Idx < 8 && "Invalid VECTOR_SHUFFLE index!");
4519       if (Idx < 4) {
4520         Locs[i] = std::make_pair(0, NumLo);
4521         Mask1[NumLo] = Idx;
4522         NumLo++;
4523       } else {
4524         Locs[i] = std::make_pair(1, NumHi);
4525         if (2+NumHi < 4)
4526           Mask1[2+NumHi] = Idx;
4527         NumHi++;
4528       }
4529     }
4530   }
4531
4532   if (NumLo <= 2 && NumHi <= 2) {
4533     // If no more than two elements come from either vector. This can be
4534     // implemented with two shuffles. First shuffle gather the elements.
4535     // The second shuffle, which takes the first shuffle as both of its
4536     // vector operands, put the elements into the right order.
4537     V1 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
4538
4539     SmallVector<int, 8> Mask2(4U, -1);
4540
4541     for (unsigned i = 0; i != 4; ++i) {
4542       if (Locs[i].first == -1)
4543         continue;
4544       else {
4545         unsigned Idx = (i < 2) ? 0 : 4;
4546         Idx += Locs[i].first * 2 + Locs[i].second;
4547         Mask2[i] = Idx;
4548       }
4549     }
4550
4551     return DAG.getVectorShuffle(VT, dl, V1, V1, &Mask2[0]);
4552   } else if (NumLo == 3 || NumHi == 3) {
4553     // Otherwise, we must have three elements from one vector, call it X, and
4554     // one element from the other, call it Y.  First, use a shufps to build an
4555     // intermediate vector with the one element from Y and the element from X
4556     // that will be in the same half in the final destination (the indexes don't
4557     // matter). Then, use a shufps to build the final vector, taking the half
4558     // containing the element from Y from the intermediate, and the other half
4559     // from X.
4560     if (NumHi == 3) {
4561       // Normalize it so the 3 elements come from V1.
4562       CommuteVectorShuffleMask(PermMask, VT);
4563       std::swap(V1, V2);
4564     }
4565
4566     // Find the element from V2.
4567     unsigned HiIndex;
4568     for (HiIndex = 0; HiIndex < 3; ++HiIndex) {
4569       int Val = PermMask[HiIndex];
4570       if (Val < 0)
4571         continue;
4572       if (Val >= 4)
4573         break;
4574     }
4575
4576     Mask1[0] = PermMask[HiIndex];
4577     Mask1[1] = -1;
4578     Mask1[2] = PermMask[HiIndex^1];
4579     Mask1[3] = -1;
4580     V2 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
4581
4582     if (HiIndex >= 2) {
4583       Mask1[0] = PermMask[0];
4584       Mask1[1] = PermMask[1];
4585       Mask1[2] = HiIndex & 1 ? 6 : 4;
4586       Mask1[3] = HiIndex & 1 ? 4 : 6;
4587       return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
4588     } else {
4589       Mask1[0] = HiIndex & 1 ? 2 : 0;
4590       Mask1[1] = HiIndex & 1 ? 0 : 2;
4591       Mask1[2] = PermMask[2];
4592       Mask1[3] = PermMask[3];
4593       if (Mask1[2] >= 0)
4594         Mask1[2] += 4;
4595       if (Mask1[3] >= 0)
4596         Mask1[3] += 4;
4597       return DAG.getVectorShuffle(VT, dl, V2, V1, &Mask1[0]);
4598     }
4599   }
4600
4601   // Break it into (shuffle shuffle_hi, shuffle_lo).
4602   Locs.clear();
4603   SmallVector<int,8> LoMask(4U, -1);
4604   SmallVector<int,8> HiMask(4U, -1);
4605
4606   SmallVector<int,8> *MaskPtr = &LoMask;
4607   unsigned MaskIdx = 0;
4608   unsigned LoIdx = 0;
4609   unsigned HiIdx = 2;
4610   for (unsigned i = 0; i != 4; ++i) {
4611     if (i == 2) {
4612       MaskPtr = &HiMask;
4613       MaskIdx = 1;
4614       LoIdx = 0;
4615       HiIdx = 2;
4616     }
4617     int Idx = PermMask[i];
4618     if (Idx < 0) {
4619       Locs[i] = std::make_pair(-1, -1);
4620     } else if (Idx < 4) {
4621       Locs[i] = std::make_pair(MaskIdx, LoIdx);
4622       (*MaskPtr)[LoIdx] = Idx;
4623       LoIdx++;
4624     } else {
4625       Locs[i] = std::make_pair(MaskIdx, HiIdx);
4626       (*MaskPtr)[HiIdx] = Idx;
4627       HiIdx++;
4628     }
4629   }
4630
4631   SDValue LoShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &LoMask[0]);
4632   SDValue HiShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &HiMask[0]);
4633   SmallVector<int, 8> MaskOps;
4634   for (unsigned i = 0; i != 4; ++i) {
4635     if (Locs[i].first == -1) {
4636       MaskOps.push_back(-1);
4637     } else {
4638       unsigned Idx = Locs[i].first * 4 + Locs[i].second;
4639       MaskOps.push_back(Idx);
4640     }
4641   }
4642   return DAG.getVectorShuffle(VT, dl, LoShuffle, HiShuffle, &MaskOps[0]);
4643 }
4644
4645 SDValue
4646 X86TargetLowering::LowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG) const {
4647   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
4648   SDValue V1 = Op.getOperand(0);
4649   SDValue V2 = Op.getOperand(1);
4650   EVT VT = Op.getValueType();
4651   DebugLoc dl = Op.getDebugLoc();
4652   unsigned NumElems = VT.getVectorNumElements();
4653   bool isMMX = VT.getSizeInBits() == 64;
4654   bool V1IsUndef = V1.getOpcode() == ISD::UNDEF;
4655   bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
4656   bool V1IsSplat = false;
4657   bool V2IsSplat = false;
4658
4659   if (isZeroShuffle(SVOp))
4660     return getZeroVector(VT, Subtarget->hasSSE2(), DAG, dl);
4661
4662   // Promote splats to v4f32.
4663   if (SVOp->isSplat()) {
4664     if (isMMX || NumElems < 4)
4665       return Op;
4666     return PromoteSplat(SVOp, DAG, Subtarget->hasSSE2());
4667   }
4668
4669   // If the shuffle can be profitably rewritten as a narrower shuffle, then
4670   // do it!
4671   if (VT == MVT::v8i16 || VT == MVT::v16i8) {
4672     SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG, *this, dl);
4673     if (NewOp.getNode())
4674       return DAG.getNode(ISD::BIT_CONVERT, dl, VT,
4675                          LowerVECTOR_SHUFFLE(NewOp, DAG));
4676   } else if ((VT == MVT::v4i32 || (VT == MVT::v4f32 && Subtarget->hasSSE2()))) {
4677     // FIXME: Figure out a cleaner way to do this.
4678     // Try to make use of movq to zero out the top part.
4679     if (ISD::isBuildVectorAllZeros(V2.getNode())) {
4680       SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG, *this, dl);
4681       if (NewOp.getNode()) {
4682         if (isCommutedMOVL(cast<ShuffleVectorSDNode>(NewOp), true, false))
4683           return getVZextMovL(VT, NewOp.getValueType(), NewOp.getOperand(0),
4684                               DAG, Subtarget, dl);
4685       }
4686     } else if (ISD::isBuildVectorAllZeros(V1.getNode())) {
4687       SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG, *this, dl);
4688       if (NewOp.getNode() && X86::isMOVLMask(cast<ShuffleVectorSDNode>(NewOp)))
4689         return getVZextMovL(VT, NewOp.getValueType(), NewOp.getOperand(1),
4690                             DAG, Subtarget, dl);
4691     }
4692   }
4693
4694   if (X86::isPSHUFDMask(SVOp))
4695     return Op;
4696
4697   // Check if this can be converted into a logical shift.
4698   bool isLeft = false;
4699   unsigned ShAmt = 0;
4700   SDValue ShVal;
4701   bool isShift = getSubtarget()->hasSSE2() &&
4702     isVectorShift(SVOp, DAG, isLeft, ShVal, ShAmt);
4703   if (isShift && ShVal.hasOneUse()) {
4704     // If the shifted value has multiple uses, it may be cheaper to use
4705     // v_set0 + movlhps or movhlps, etc.
4706     EVT EltVT = VT.getVectorElementType();
4707     ShAmt *= EltVT.getSizeInBits();
4708     return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
4709   }
4710
4711   if (X86::isMOVLMask(SVOp)) {
4712     if (V1IsUndef)
4713       return V2;
4714     if (ISD::isBuildVectorAllZeros(V1.getNode()))
4715       return getVZextMovL(VT, VT, V2, DAG, Subtarget, dl);
4716     if (!isMMX)
4717       return Op;
4718   }
4719
4720   // FIXME: fold these into legal mask.
4721   if (!isMMX && (X86::isMOVSHDUPMask(SVOp) ||
4722                  X86::isMOVSLDUPMask(SVOp) ||
4723                  X86::isMOVHLPSMask(SVOp) ||
4724                  X86::isMOVLHPSMask(SVOp) ||
4725                  X86::isMOVLPMask(SVOp)))
4726     return Op;
4727
4728   if (ShouldXformToMOVHLPS(SVOp) ||
4729       ShouldXformToMOVLP(V1.getNode(), V2.getNode(), SVOp))
4730     return CommuteVectorShuffle(SVOp, DAG);
4731
4732   if (isShift) {
4733     // No better options. Use a vshl / vsrl.
4734     EVT EltVT = VT.getVectorElementType();
4735     ShAmt *= EltVT.getSizeInBits();
4736     return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
4737   }
4738
4739   bool Commuted = false;
4740   // FIXME: This should also accept a bitcast of a splat?  Be careful, not
4741   // 1,1,1,1 -> v8i16 though.
4742   V1IsSplat = isSplatVector(V1.getNode());
4743   V2IsSplat = isSplatVector(V2.getNode());
4744
4745   // Canonicalize the splat or undef, if present, to be on the RHS.
4746   if ((V1IsSplat || V1IsUndef) && !(V2IsSplat || V2IsUndef)) {
4747     Op = CommuteVectorShuffle(SVOp, DAG);
4748     SVOp = cast<ShuffleVectorSDNode>(Op);
4749     V1 = SVOp->getOperand(0);
4750     V2 = SVOp->getOperand(1);
4751     std::swap(V1IsSplat, V2IsSplat);
4752     std::swap(V1IsUndef, V2IsUndef);
4753     Commuted = true;
4754   }
4755
4756   if (isCommutedMOVL(SVOp, V2IsSplat, V2IsUndef)) {
4757     // Shuffling low element of v1 into undef, just return v1.
4758     if (V2IsUndef)
4759       return V1;
4760     // If V2 is a splat, the mask may be malformed such as <4,3,3,3>, which
4761     // the instruction selector will not match, so get a canonical MOVL with
4762     // swapped operands to undo the commute.
4763     return getMOVL(DAG, dl, VT, V2, V1);
4764   }
4765
4766   if (X86::isUNPCKL_v_undef_Mask(SVOp) ||
4767       X86::isUNPCKH_v_undef_Mask(SVOp) ||
4768       X86::isUNPCKLMask(SVOp) ||
4769       X86::isUNPCKHMask(SVOp))
4770     return Op;
4771
4772   if (V2IsSplat) {
4773     // Normalize mask so all entries that point to V2 points to its first
4774     // element then try to match unpck{h|l} again. If match, return a
4775     // new vector_shuffle with the corrected mask.
4776     SDValue NewMask = NormalizeMask(SVOp, DAG);
4777     ShuffleVectorSDNode *NSVOp = cast<ShuffleVectorSDNode>(NewMask);
4778     if (NSVOp != SVOp) {
4779       if (X86::isUNPCKLMask(NSVOp, true)) {
4780         return NewMask;
4781       } else if (X86::isUNPCKHMask(NSVOp, true)) {
4782         return NewMask;
4783       }
4784     }
4785   }
4786
4787   if (Commuted) {
4788     // Commute is back and try unpck* again.
4789     // FIXME: this seems wrong.
4790     SDValue NewOp = CommuteVectorShuffle(SVOp, DAG);
4791     ShuffleVectorSDNode *NewSVOp = cast<ShuffleVectorSDNode>(NewOp);
4792     if (X86::isUNPCKL_v_undef_Mask(NewSVOp) ||
4793         X86::isUNPCKH_v_undef_Mask(NewSVOp) ||
4794         X86::isUNPCKLMask(NewSVOp) ||
4795         X86::isUNPCKHMask(NewSVOp))
4796       return NewOp;
4797   }
4798
4799   // FIXME: for mmx, bitcast v2i32 to v4i16 for shuffle.
4800
4801   // Normalize the node to match x86 shuffle ops if needed
4802   if (!isMMX && V2.getOpcode() != ISD::UNDEF && isCommutedSHUFP(SVOp))
4803     return CommuteVectorShuffle(SVOp, DAG);
4804
4805   // Check for legal shuffle and return?
4806   SmallVector<int, 16> PermMask;
4807   SVOp->getMask(PermMask);
4808   if (isShuffleMaskLegal(PermMask, VT))
4809     return Op;
4810
4811   // Handle v8i16 specifically since SSE can do byte extraction and insertion.
4812   if (VT == MVT::v8i16) {
4813     SDValue NewOp = LowerVECTOR_SHUFFLEv8i16(SVOp, DAG, *this);
4814     if (NewOp.getNode())
4815       return NewOp;
4816   }
4817
4818   if (VT == MVT::v16i8) {
4819     SDValue NewOp = LowerVECTOR_SHUFFLEv16i8(SVOp, DAG, *this);
4820     if (NewOp.getNode())
4821       return NewOp;
4822   }
4823
4824   // Handle all 4 wide cases with a number of shuffles except for MMX.
4825   if (NumElems == 4 && !isMMX)
4826     return LowerVECTOR_SHUFFLE_4wide(SVOp, DAG);
4827
4828   return SDValue();
4829 }
4830
4831 SDValue
4832 X86TargetLowering::LowerEXTRACT_VECTOR_ELT_SSE4(SDValue Op,
4833                                                 SelectionDAG &DAG) const {
4834   EVT VT = Op.getValueType();
4835   DebugLoc dl = Op.getDebugLoc();
4836   if (VT.getSizeInBits() == 8) {
4837     SDValue Extract = DAG.getNode(X86ISD::PEXTRB, dl, MVT::i32,
4838                                     Op.getOperand(0), Op.getOperand(1));
4839     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
4840                                     DAG.getValueType(VT));
4841     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
4842   } else if (VT.getSizeInBits() == 16) {
4843     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
4844     // If Idx is 0, it's cheaper to do a move instead of a pextrw.
4845     if (Idx == 0)
4846       return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
4847                          DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
4848                                      DAG.getNode(ISD::BIT_CONVERT, dl,
4849                                                  MVT::v4i32,
4850                                                  Op.getOperand(0)),
4851                                      Op.getOperand(1)));
4852     SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, MVT::i32,
4853                                     Op.getOperand(0), Op.getOperand(1));
4854     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
4855                                     DAG.getValueType(VT));
4856     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
4857   } else if (VT == MVT::f32) {
4858     // EXTRACTPS outputs to a GPR32 register which will require a movd to copy
4859     // the result back to FR32 register. It's only worth matching if the
4860     // result has a single use which is a store or a bitcast to i32.  And in
4861     // the case of a store, it's not worth it if the index is a constant 0,
4862     // because a MOVSSmr can be used instead, which is smaller and faster.
4863     if (!Op.hasOneUse())
4864       return SDValue();
4865     SDNode *User = *Op.getNode()->use_begin();
4866     if ((User->getOpcode() != ISD::STORE ||
4867          (isa<ConstantSDNode>(Op.getOperand(1)) &&
4868           cast<ConstantSDNode>(Op.getOperand(1))->isNullValue())) &&
4869         (User->getOpcode() != ISD::BIT_CONVERT ||
4870          User->getValueType(0) != MVT::i32))
4871       return SDValue();
4872     SDValue Extract = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
4873                                   DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v4i32,
4874                                               Op.getOperand(0)),
4875                                               Op.getOperand(1));
4876     return DAG.getNode(ISD::BIT_CONVERT, dl, MVT::f32, Extract);
4877   } else if (VT == MVT::i32) {
4878     // ExtractPS works with constant index.
4879     if (isa<ConstantSDNode>(Op.getOperand(1)))
4880       return Op;
4881   }
4882   return SDValue();
4883 }
4884
4885
4886 SDValue
4887 X86TargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op,
4888                                            SelectionDAG &DAG) const {
4889   if (!isa<ConstantSDNode>(Op.getOperand(1)))
4890     return SDValue();
4891
4892   if (Subtarget->hasSSE41()) {
4893     SDValue Res = LowerEXTRACT_VECTOR_ELT_SSE4(Op, DAG);
4894     if (Res.getNode())
4895       return Res;
4896   }
4897
4898   EVT VT = Op.getValueType();
4899   DebugLoc dl = Op.getDebugLoc();
4900   // TODO: handle v16i8.
4901   if (VT.getSizeInBits() == 16) {
4902     SDValue Vec = Op.getOperand(0);
4903     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
4904     if (Idx == 0)
4905       return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
4906                          DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
4907                                      DAG.getNode(ISD::BIT_CONVERT, dl,
4908                                                  MVT::v4i32, Vec),
4909                                      Op.getOperand(1)));
4910     // Transform it so it match pextrw which produces a 32-bit result.
4911     EVT EltVT = MVT::i32;
4912     SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, EltVT,
4913                                     Op.getOperand(0), Op.getOperand(1));
4914     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, EltVT, Extract,
4915                                     DAG.getValueType(VT));
4916     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
4917   } else if (VT.getSizeInBits() == 32) {
4918     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
4919     if (Idx == 0)
4920       return Op;
4921
4922     // SHUFPS the element to the lowest double word, then movss.
4923     int Mask[4] = { Idx, -1, -1, -1 };
4924     EVT VVT = Op.getOperand(0).getValueType();
4925     SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
4926                                        DAG.getUNDEF(VVT), Mask);
4927     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
4928                        DAG.getIntPtrConstant(0));
4929   } else if (VT.getSizeInBits() == 64) {
4930     // FIXME: .td only matches this for <2 x f64>, not <2 x i64> on 32b
4931     // FIXME: seems like this should be unnecessary if mov{h,l}pd were taught
4932     //        to match extract_elt for f64.
4933     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
4934     if (Idx == 0)
4935       return Op;
4936
4937     // UNPCKHPD the element to the lowest double word, then movsd.
4938     // Note if the lower 64 bits of the result of the UNPCKHPD is then stored
4939     // to a f64mem, the whole operation is folded into a single MOVHPDmr.
4940     int Mask[2] = { 1, -1 };
4941     EVT VVT = Op.getOperand(0).getValueType();
4942     SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
4943                                        DAG.getUNDEF(VVT), Mask);
4944     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
4945                        DAG.getIntPtrConstant(0));
4946   }
4947
4948   return SDValue();
4949 }
4950
4951 SDValue
4952 X86TargetLowering::LowerINSERT_VECTOR_ELT_SSE4(SDValue Op,
4953                                                SelectionDAG &DAG) const {
4954   EVT VT = Op.getValueType();
4955   EVT EltVT = VT.getVectorElementType();
4956   DebugLoc dl = Op.getDebugLoc();
4957
4958   SDValue N0 = Op.getOperand(0);
4959   SDValue N1 = Op.getOperand(1);
4960   SDValue N2 = Op.getOperand(2);
4961
4962   if ((EltVT.getSizeInBits() == 8 || EltVT.getSizeInBits() == 16) &&
4963       isa<ConstantSDNode>(N2)) {
4964     unsigned Opc;
4965     if (VT == MVT::v8i16)
4966       Opc = X86ISD::PINSRW;
4967     else if (VT == MVT::v4i16)
4968       Opc = X86ISD::MMX_PINSRW;
4969     else if (VT == MVT::v16i8)
4970       Opc = X86ISD::PINSRB;
4971     else
4972       Opc = X86ISD::PINSRB;
4973
4974     // Transform it so it match pinsr{b,w} which expects a GR32 as its second
4975     // argument.
4976     if (N1.getValueType() != MVT::i32)
4977       N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
4978     if (N2.getValueType() != MVT::i32)
4979       N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue());
4980     return DAG.getNode(Opc, dl, VT, N0, N1, N2);
4981   } else if (EltVT == MVT::f32 && isa<ConstantSDNode>(N2)) {
4982     // Bits [7:6] of the constant are the source select.  This will always be
4983     //  zero here.  The DAG Combiner may combine an extract_elt index into these
4984     //  bits.  For example (insert (extract, 3), 2) could be matched by putting
4985     //  the '3' into bits [7:6] of X86ISD::INSERTPS.
4986     // Bits [5:4] of the constant are the destination select.  This is the
4987     //  value of the incoming immediate.
4988     // Bits [3:0] of the constant are the zero mask.  The DAG Combiner may
4989     //   combine either bitwise AND or insert of float 0.0 to set these bits.
4990     N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue() << 4);
4991     // Create this as a scalar to vector..
4992     N1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4f32, N1);
4993     return DAG.getNode(X86ISD::INSERTPS, dl, VT, N0, N1, N2);
4994   } else if (EltVT == MVT::i32 && isa<ConstantSDNode>(N2)) {
4995     // PINSR* works with constant index.
4996     return Op;
4997   }
4998   return SDValue();
4999 }
5000
5001 SDValue
5002 X86TargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) const {
5003   EVT VT = Op.getValueType();
5004   EVT EltVT = VT.getVectorElementType();
5005
5006   if (Subtarget->hasSSE41())
5007     return LowerINSERT_VECTOR_ELT_SSE4(Op, DAG);
5008
5009   if (EltVT == MVT::i8)
5010     return SDValue();
5011
5012   DebugLoc dl = Op.getDebugLoc();
5013   SDValue N0 = Op.getOperand(0);
5014   SDValue N1 = Op.getOperand(1);
5015   SDValue N2 = Op.getOperand(2);
5016
5017   if (EltVT.getSizeInBits() == 16 && isa<ConstantSDNode>(N2)) {
5018     // Transform it so it match pinsrw which expects a 16-bit value in a GR32
5019     // as its second argument.
5020     if (N1.getValueType() != MVT::i32)
5021       N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
5022     if (N2.getValueType() != MVT::i32)
5023       N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue());
5024     return DAG.getNode(VT == MVT::v8i16 ? X86ISD::PINSRW : X86ISD::MMX_PINSRW,
5025                        dl, VT, N0, N1, N2);
5026   }
5027   return SDValue();
5028 }
5029
5030 SDValue
5031 X86TargetLowering::LowerSCALAR_TO_VECTOR(SDValue Op, SelectionDAG &DAG) const {
5032   DebugLoc dl = Op.getDebugLoc();
5033   if (Op.getValueType() == MVT::v2f32)
5034     return DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v2f32,
5035                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i32,
5036                                    DAG.getNode(ISD::BIT_CONVERT, dl, MVT::i32,
5037                                                Op.getOperand(0))));
5038
5039   if (Op.getValueType() == MVT::v1i64 && Op.getOperand(0).getValueType() == MVT::i64)
5040     return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v1i64, Op.getOperand(0));
5041
5042   SDValue AnyExt = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, Op.getOperand(0));
5043   EVT VT = MVT::v2i32;
5044   switch (Op.getValueType().getSimpleVT().SimpleTy) {
5045   default: break;
5046   case MVT::v16i8:
5047   case MVT::v8i16:
5048     VT = MVT::v4i32;
5049     break;
5050   }
5051   return DAG.getNode(ISD::BIT_CONVERT, dl, Op.getValueType(),
5052                      DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, AnyExt));
5053 }
5054
5055 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
5056 // their target countpart wrapped in the X86ISD::Wrapper node. Suppose N is
5057 // one of the above mentioned nodes. It has to be wrapped because otherwise
5058 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
5059 // be used to form addressing mode. These wrapped nodes will be selected
5060 // into MOV32ri.
5061 SDValue
5062 X86TargetLowering::LowerConstantPool(SDValue Op, SelectionDAG &DAG) const {
5063   ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
5064
5065   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
5066   // global base reg.
5067   unsigned char OpFlag = 0;
5068   unsigned WrapperKind = X86ISD::Wrapper;
5069   CodeModel::Model M = getTargetMachine().getCodeModel();
5070
5071   if (Subtarget->isPICStyleRIPRel() &&
5072       (M == CodeModel::Small || M == CodeModel::Kernel))
5073     WrapperKind = X86ISD::WrapperRIP;
5074   else if (Subtarget->isPICStyleGOT())
5075     OpFlag = X86II::MO_GOTOFF;
5076   else if (Subtarget->isPICStyleStubPIC())
5077     OpFlag = X86II::MO_PIC_BASE_OFFSET;
5078
5079   SDValue Result = DAG.getTargetConstantPool(CP->getConstVal(), getPointerTy(),
5080                                              CP->getAlignment(),
5081                                              CP->getOffset(), OpFlag);
5082   DebugLoc DL = CP->getDebugLoc();
5083   Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
5084   // With PIC, the address is actually $g + Offset.
5085   if (OpFlag) {
5086     Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
5087                          DAG.getNode(X86ISD::GlobalBaseReg,
5088                                      DebugLoc(), getPointerTy()),
5089                          Result);
5090   }
5091
5092   return Result;
5093 }
5094
5095 SDValue X86TargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) const {
5096   JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
5097
5098   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
5099   // global base reg.
5100   unsigned char OpFlag = 0;
5101   unsigned WrapperKind = X86ISD::Wrapper;
5102   CodeModel::Model M = getTargetMachine().getCodeModel();
5103
5104   if (Subtarget->isPICStyleRIPRel() &&
5105       (M == CodeModel::Small || M == CodeModel::Kernel))
5106     WrapperKind = X86ISD::WrapperRIP;
5107   else if (Subtarget->isPICStyleGOT())
5108     OpFlag = X86II::MO_GOTOFF;
5109   else if (Subtarget->isPICStyleStubPIC())
5110     OpFlag = X86II::MO_PIC_BASE_OFFSET;
5111
5112   SDValue Result = DAG.getTargetJumpTable(JT->getIndex(), getPointerTy(),
5113                                           OpFlag);
5114   DebugLoc DL = JT->getDebugLoc();
5115   Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
5116
5117   // With PIC, the address is actually $g + Offset.
5118   if (OpFlag) {
5119     Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
5120                          DAG.getNode(X86ISD::GlobalBaseReg,
5121                                      DebugLoc(), getPointerTy()),
5122                          Result);
5123   }
5124
5125   return Result;
5126 }
5127
5128 SDValue
5129 X86TargetLowering::LowerExternalSymbol(SDValue Op, SelectionDAG &DAG) const {
5130   const char *Sym = cast<ExternalSymbolSDNode>(Op)->getSymbol();
5131
5132   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
5133   // global base reg.
5134   unsigned char OpFlag = 0;
5135   unsigned WrapperKind = X86ISD::Wrapper;
5136   CodeModel::Model M = getTargetMachine().getCodeModel();
5137
5138   if (Subtarget->isPICStyleRIPRel() &&
5139       (M == CodeModel::Small || M == CodeModel::Kernel))
5140     WrapperKind = X86ISD::WrapperRIP;
5141   else if (Subtarget->isPICStyleGOT())
5142     OpFlag = X86II::MO_GOTOFF;
5143   else if (Subtarget->isPICStyleStubPIC())
5144     OpFlag = X86II::MO_PIC_BASE_OFFSET;
5145
5146   SDValue Result = DAG.getTargetExternalSymbol(Sym, getPointerTy(), OpFlag);
5147
5148   DebugLoc DL = Op.getDebugLoc();
5149   Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
5150
5151
5152   // With PIC, the address is actually $g + Offset.
5153   if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
5154       !Subtarget->is64Bit()) {
5155     Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
5156                          DAG.getNode(X86ISD::GlobalBaseReg,
5157                                      DebugLoc(), getPointerTy()),
5158                          Result);
5159   }
5160
5161   return Result;
5162 }
5163
5164 SDValue
5165 X86TargetLowering::LowerBlockAddress(SDValue Op, SelectionDAG &DAG) const {
5166   // Create the TargetBlockAddressAddress node.
5167   unsigned char OpFlags =
5168     Subtarget->ClassifyBlockAddressReference();
5169   CodeModel::Model M = getTargetMachine().getCodeModel();
5170   const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
5171   DebugLoc dl = Op.getDebugLoc();
5172   SDValue Result = DAG.getBlockAddress(BA, getPointerTy(),
5173                                        /*isTarget=*/true, OpFlags);
5174
5175   if (Subtarget->isPICStyleRIPRel() &&
5176       (M == CodeModel::Small || M == CodeModel::Kernel))
5177     Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
5178   else
5179     Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
5180
5181   // With PIC, the address is actually $g + Offset.
5182   if (isGlobalRelativeToPICBase(OpFlags)) {
5183     Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
5184                          DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
5185                          Result);
5186   }
5187
5188   return Result;
5189 }
5190
5191 SDValue
5192 X86TargetLowering::LowerGlobalAddress(const GlobalValue *GV, DebugLoc dl,
5193                                       int64_t Offset,
5194                                       SelectionDAG &DAG) const {
5195   // Create the TargetGlobalAddress node, folding in the constant
5196   // offset if it is legal.
5197   unsigned char OpFlags =
5198     Subtarget->ClassifyGlobalReference(GV, getTargetMachine());
5199   CodeModel::Model M = getTargetMachine().getCodeModel();
5200   SDValue Result;
5201   if (OpFlags == X86II::MO_NO_FLAG &&
5202       X86::isOffsetSuitableForCodeModel(Offset, M)) {
5203     // A direct static reference to a global.
5204     Result = DAG.getTargetGlobalAddress(GV, getPointerTy(), Offset);
5205     Offset = 0;
5206   } else {
5207     Result = DAG.getTargetGlobalAddress(GV, getPointerTy(), 0, OpFlags);
5208   }
5209
5210   if (Subtarget->isPICStyleRIPRel() &&
5211       (M == CodeModel::Small || M == CodeModel::Kernel))
5212     Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
5213   else
5214     Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
5215
5216   // With PIC, the address is actually $g + Offset.
5217   if (isGlobalRelativeToPICBase(OpFlags)) {
5218     Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
5219                          DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
5220                          Result);
5221   }
5222
5223   // For globals that require a load from a stub to get the address, emit the
5224   // load.
5225   if (isGlobalStubReference(OpFlags))
5226     Result = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Result,
5227                          PseudoSourceValue::getGOT(), 0, false, false, 0);
5228
5229   // If there was a non-zero offset that we didn't fold, create an explicit
5230   // addition for it.
5231   if (Offset != 0)
5232     Result = DAG.getNode(ISD::ADD, dl, getPointerTy(), Result,
5233                          DAG.getConstant(Offset, getPointerTy()));
5234
5235   return Result;
5236 }
5237
5238 SDValue
5239 X86TargetLowering::LowerGlobalAddress(SDValue Op, SelectionDAG &DAG) const {
5240   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
5241   int64_t Offset = cast<GlobalAddressSDNode>(Op)->getOffset();
5242   return LowerGlobalAddress(GV, Op.getDebugLoc(), Offset, DAG);
5243 }
5244
5245 static SDValue
5246 GetTLSADDR(SelectionDAG &DAG, SDValue Chain, GlobalAddressSDNode *GA,
5247            SDValue *InFlag, const EVT PtrVT, unsigned ReturnReg,
5248            unsigned char OperandFlags) {
5249   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
5250   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Flag);
5251   DebugLoc dl = GA->getDebugLoc();
5252   SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(),
5253                                            GA->getValueType(0),
5254                                            GA->getOffset(),
5255                                            OperandFlags);
5256   if (InFlag) {
5257     SDValue Ops[] = { Chain,  TGA, *InFlag };
5258     Chain = DAG.getNode(X86ISD::TLSADDR, dl, NodeTys, Ops, 3);
5259   } else {
5260     SDValue Ops[]  = { Chain, TGA };
5261     Chain = DAG.getNode(X86ISD::TLSADDR, dl, NodeTys, Ops, 2);
5262   }
5263
5264   // TLSADDR will be codegen'ed as call. Inform MFI that function has calls.
5265   MFI->setHasCalls(true);
5266
5267   SDValue Flag = Chain.getValue(1);
5268   return DAG.getCopyFromReg(Chain, dl, ReturnReg, PtrVT, Flag);
5269 }
5270
5271 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 32 bit
5272 static SDValue
5273 LowerToTLSGeneralDynamicModel32(GlobalAddressSDNode *GA, SelectionDAG &DAG,
5274                                 const EVT PtrVT) {
5275   SDValue InFlag;
5276   DebugLoc dl = GA->getDebugLoc();  // ? function entry point might be better
5277   SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
5278                                      DAG.getNode(X86ISD::GlobalBaseReg,
5279                                                  DebugLoc(), PtrVT), InFlag);
5280   InFlag = Chain.getValue(1);
5281
5282   return GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX, X86II::MO_TLSGD);
5283 }
5284
5285 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 64 bit
5286 static SDValue
5287 LowerToTLSGeneralDynamicModel64(GlobalAddressSDNode *GA, SelectionDAG &DAG,
5288                                 const EVT PtrVT) {
5289   return GetTLSADDR(DAG, DAG.getEntryNode(), GA, NULL, PtrVT,
5290                     X86::RAX, X86II::MO_TLSGD);
5291 }
5292
5293 // Lower ISD::GlobalTLSAddress using the "initial exec" (for no-pic) or
5294 // "local exec" model.
5295 static SDValue LowerToTLSExecModel(GlobalAddressSDNode *GA, SelectionDAG &DAG,
5296                                    const EVT PtrVT, TLSModel::Model model,
5297                                    bool is64Bit) {
5298   DebugLoc dl = GA->getDebugLoc();
5299   // Get the Thread Pointer
5300   SDValue Base = DAG.getNode(X86ISD::SegmentBaseAddress,
5301                              DebugLoc(), PtrVT,
5302                              DAG.getRegister(is64Bit? X86::FS : X86::GS,
5303                                              MVT::i32));
5304
5305   SDValue ThreadPointer = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Base,
5306                                       NULL, 0, false, false, 0);
5307
5308   unsigned char OperandFlags = 0;
5309   // Most TLS accesses are not RIP relative, even on x86-64.  One exception is
5310   // initialexec.
5311   unsigned WrapperKind = X86ISD::Wrapper;
5312   if (model == TLSModel::LocalExec) {
5313     OperandFlags = is64Bit ? X86II::MO_TPOFF : X86II::MO_NTPOFF;
5314   } else if (is64Bit) {
5315     assert(model == TLSModel::InitialExec);
5316     OperandFlags = X86II::MO_GOTTPOFF;
5317     WrapperKind = X86ISD::WrapperRIP;
5318   } else {
5319     assert(model == TLSModel::InitialExec);
5320     OperandFlags = X86II::MO_INDNTPOFF;
5321   }
5322
5323   // emit "addl x@ntpoff,%eax" (local exec) or "addl x@indntpoff,%eax" (initial
5324   // exec)
5325   SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), GA->getValueType(0),
5326                                            GA->getOffset(), OperandFlags);
5327   SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
5328
5329   if (model == TLSModel::InitialExec)
5330     Offset = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Offset,
5331                          PseudoSourceValue::getGOT(), 0, false, false, 0);
5332
5333   // The address of the thread local variable is the add of the thread
5334   // pointer with the offset of the variable.
5335   return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
5336 }
5337
5338 SDValue
5339 X86TargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const {
5340   // TODO: implement the "local dynamic" model
5341   // TODO: implement the "initial exec"model for pic executables
5342   assert(Subtarget->isTargetELF() &&
5343          "TLS not implemented for non-ELF targets");
5344   GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
5345   const GlobalValue *GV = GA->getGlobal();
5346
5347   // If GV is an alias then use the aliasee for determining
5348   // thread-localness.
5349   if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(GV))
5350     GV = GA->resolveAliasedGlobal(false);
5351
5352   TLSModel::Model model = getTLSModel(GV,
5353                                       getTargetMachine().getRelocationModel());
5354
5355   switch (model) {
5356   case TLSModel::GeneralDynamic:
5357   case TLSModel::LocalDynamic: // not implemented
5358     if (Subtarget->is64Bit())
5359       return LowerToTLSGeneralDynamicModel64(GA, DAG, getPointerTy());
5360     return LowerToTLSGeneralDynamicModel32(GA, DAG, getPointerTy());
5361
5362   case TLSModel::InitialExec:
5363   case TLSModel::LocalExec:
5364     return LowerToTLSExecModel(GA, DAG, getPointerTy(), model,
5365                                Subtarget->is64Bit());
5366   }
5367
5368   llvm_unreachable("Unreachable");
5369   return SDValue();
5370 }
5371
5372
5373 /// LowerShift - Lower SRA_PARTS and friends, which return two i32 values and
5374 /// take a 2 x i32 value to shift plus a shift amount.
5375 SDValue X86TargetLowering::LowerShift(SDValue Op, SelectionDAG &DAG) const {
5376   assert(Op.getNumOperands() == 3 && "Not a double-shift!");
5377   EVT VT = Op.getValueType();
5378   unsigned VTBits = VT.getSizeInBits();
5379   DebugLoc dl = Op.getDebugLoc();
5380   bool isSRA = Op.getOpcode() == ISD::SRA_PARTS;
5381   SDValue ShOpLo = Op.getOperand(0);
5382   SDValue ShOpHi = Op.getOperand(1);
5383   SDValue ShAmt  = Op.getOperand(2);
5384   SDValue Tmp1 = isSRA ? DAG.getNode(ISD::SRA, dl, VT, ShOpHi,
5385                                      DAG.getConstant(VTBits - 1, MVT::i8))
5386                        : DAG.getConstant(0, VT);
5387
5388   SDValue Tmp2, Tmp3;
5389   if (Op.getOpcode() == ISD::SHL_PARTS) {
5390     Tmp2 = DAG.getNode(X86ISD::SHLD, dl, VT, ShOpHi, ShOpLo, ShAmt);
5391     Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ShAmt);
5392   } else {
5393     Tmp2 = DAG.getNode(X86ISD::SHRD, dl, VT, ShOpLo, ShOpHi, ShAmt);
5394     Tmp3 = DAG.getNode(isSRA ? ISD::SRA : ISD::SRL, dl, VT, ShOpHi, ShAmt);
5395   }
5396
5397   SDValue AndNode = DAG.getNode(ISD::AND, dl, MVT::i8, ShAmt,
5398                                 DAG.getConstant(VTBits, MVT::i8));
5399   SDValue Cond = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
5400                              AndNode, DAG.getConstant(0, MVT::i8));
5401
5402   SDValue Hi, Lo;
5403   SDValue CC = DAG.getConstant(X86::COND_NE, MVT::i8);
5404   SDValue Ops0[4] = { Tmp2, Tmp3, CC, Cond };
5405   SDValue Ops1[4] = { Tmp3, Tmp1, CC, Cond };
5406
5407   if (Op.getOpcode() == ISD::SHL_PARTS) {
5408     Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0, 4);
5409     Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1, 4);
5410   } else {
5411     Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0, 4);
5412     Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1, 4);
5413   }
5414
5415   SDValue Ops[2] = { Lo, Hi };
5416   return DAG.getMergeValues(Ops, 2, dl);
5417 }
5418
5419 SDValue X86TargetLowering::LowerSINT_TO_FP(SDValue Op,
5420                                            SelectionDAG &DAG) const {
5421   EVT SrcVT = Op.getOperand(0).getValueType();
5422
5423   if (SrcVT.isVector()) {
5424     if (SrcVT == MVT::v2i32 && Op.getValueType() == MVT::v2f64) {
5425       return Op;
5426     }
5427     return SDValue();
5428   }
5429
5430   assert(SrcVT.getSimpleVT() <= MVT::i64 && SrcVT.getSimpleVT() >= MVT::i16 &&
5431          "Unknown SINT_TO_FP to lower!");
5432
5433   // These are really Legal; return the operand so the caller accepts it as
5434   // Legal.
5435   if (SrcVT == MVT::i32 && isScalarFPTypeInSSEReg(Op.getValueType()))
5436     return Op;
5437   if (SrcVT == MVT::i64 && isScalarFPTypeInSSEReg(Op.getValueType()) &&
5438       Subtarget->is64Bit()) {
5439     return Op;
5440   }
5441
5442   DebugLoc dl = Op.getDebugLoc();
5443   unsigned Size = SrcVT.getSizeInBits()/8;
5444   MachineFunction &MF = DAG.getMachineFunction();
5445   int SSFI = MF.getFrameInfo()->CreateStackObject(Size, Size, false);
5446   SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
5447   SDValue Chain = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
5448                                StackSlot,
5449                                PseudoSourceValue::getFixedStack(SSFI), 0,
5450                                false, false, 0);
5451   return BuildFILD(Op, SrcVT, Chain, StackSlot, DAG);
5452 }
5453
5454 SDValue X86TargetLowering::BuildFILD(SDValue Op, EVT SrcVT, SDValue Chain,
5455                                      SDValue StackSlot,
5456                                      SelectionDAG &DAG) const {
5457   // Build the FILD
5458   DebugLoc dl = Op.getDebugLoc();
5459   SDVTList Tys;
5460   bool useSSE = isScalarFPTypeInSSEReg(Op.getValueType());
5461   if (useSSE)
5462     Tys = DAG.getVTList(MVT::f64, MVT::Other, MVT::Flag);
5463   else
5464     Tys = DAG.getVTList(Op.getValueType(), MVT::Other);
5465   SDValue Ops[] = { Chain, StackSlot, DAG.getValueType(SrcVT) };
5466   SDValue Result = DAG.getNode(useSSE ? X86ISD::FILD_FLAG : X86ISD::FILD, dl,
5467                                Tys, Ops, array_lengthof(Ops));
5468
5469   if (useSSE) {
5470     Chain = Result.getValue(1);
5471     SDValue InFlag = Result.getValue(2);
5472
5473     // FIXME: Currently the FST is flagged to the FILD_FLAG. This
5474     // shouldn't be necessary except that RFP cannot be live across
5475     // multiple blocks. When stackifier is fixed, they can be uncoupled.
5476     MachineFunction &MF = DAG.getMachineFunction();
5477     int SSFI = MF.getFrameInfo()->CreateStackObject(8, 8, false);
5478     SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
5479     Tys = DAG.getVTList(MVT::Other);
5480     SDValue Ops[] = {
5481       Chain, Result, StackSlot, DAG.getValueType(Op.getValueType()), InFlag
5482     };
5483     Chain = DAG.getNode(X86ISD::FST, dl, Tys, Ops, array_lengthof(Ops));
5484     Result = DAG.getLoad(Op.getValueType(), dl, Chain, StackSlot,
5485                          PseudoSourceValue::getFixedStack(SSFI), 0,
5486                          false, false, 0);
5487   }
5488
5489   return Result;
5490 }
5491
5492 // LowerUINT_TO_FP_i64 - 64-bit unsigned integer to double expansion.
5493 SDValue X86TargetLowering::LowerUINT_TO_FP_i64(SDValue Op,
5494                                                SelectionDAG &DAG) const {
5495   // This algorithm is not obvious. Here it is in C code, more or less:
5496   /*
5497     double uint64_to_double( uint32_t hi, uint32_t lo ) {
5498       static const __m128i exp = { 0x4330000045300000ULL, 0 };
5499       static const __m128d bias = { 0x1.0p84, 0x1.0p52 };
5500
5501       // Copy ints to xmm registers.
5502       __m128i xh = _mm_cvtsi32_si128( hi );
5503       __m128i xl = _mm_cvtsi32_si128( lo );
5504
5505       // Combine into low half of a single xmm register.
5506       __m128i x = _mm_unpacklo_epi32( xh, xl );
5507       __m128d d;
5508       double sd;
5509
5510       // Merge in appropriate exponents to give the integer bits the right
5511       // magnitude.
5512       x = _mm_unpacklo_epi32( x, exp );
5513
5514       // Subtract away the biases to deal with the IEEE-754 double precision
5515       // implicit 1.
5516       d = _mm_sub_pd( (__m128d) x, bias );
5517
5518       // All conversions up to here are exact. The correctly rounded result is
5519       // calculated using the current rounding mode using the following
5520       // horizontal add.
5521       d = _mm_add_sd( d, _mm_unpackhi_pd( d, d ) );
5522       _mm_store_sd( &sd, d );   // Because we are returning doubles in XMM, this
5523                                 // store doesn't really need to be here (except
5524                                 // maybe to zero the other double)
5525       return sd;
5526     }
5527   */
5528
5529   DebugLoc dl = Op.getDebugLoc();
5530   LLVMContext *Context = DAG.getContext();
5531
5532   // Build some magic constants.
5533   std::vector<Constant*> CV0;
5534   CV0.push_back(ConstantInt::get(*Context, APInt(32, 0x45300000)));
5535   CV0.push_back(ConstantInt::get(*Context, APInt(32, 0x43300000)));
5536   CV0.push_back(ConstantInt::get(*Context, APInt(32, 0)));
5537   CV0.push_back(ConstantInt::get(*Context, APInt(32, 0)));
5538   Constant *C0 = ConstantVector::get(CV0);
5539   SDValue CPIdx0 = DAG.getConstantPool(C0, getPointerTy(), 16);
5540
5541   std::vector<Constant*> CV1;
5542   CV1.push_back(
5543     ConstantFP::get(*Context, APFloat(APInt(64, 0x4530000000000000ULL))));
5544   CV1.push_back(
5545     ConstantFP::get(*Context, APFloat(APInt(64, 0x4330000000000000ULL))));
5546   Constant *C1 = ConstantVector::get(CV1);
5547   SDValue CPIdx1 = DAG.getConstantPool(C1, getPointerTy(), 16);
5548
5549   SDValue XR1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
5550                             DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
5551                                         Op.getOperand(0),
5552                                         DAG.getIntPtrConstant(1)));
5553   SDValue XR2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
5554                             DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
5555                                         Op.getOperand(0),
5556                                         DAG.getIntPtrConstant(0)));
5557   SDValue Unpck1 = getUnpackl(DAG, dl, MVT::v4i32, XR1, XR2);
5558   SDValue CLod0 = DAG.getLoad(MVT::v4i32, dl, DAG.getEntryNode(), CPIdx0,
5559                               PseudoSourceValue::getConstantPool(), 0,
5560                               false, false, 16);
5561   SDValue Unpck2 = getUnpackl(DAG, dl, MVT::v4i32, Unpck1, CLod0);
5562   SDValue XR2F = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v2f64, Unpck2);
5563   SDValue CLod1 = DAG.getLoad(MVT::v2f64, dl, CLod0.getValue(1), CPIdx1,
5564                               PseudoSourceValue::getConstantPool(), 0,
5565                               false, false, 16);
5566   SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, XR2F, CLod1);
5567
5568   // Add the halves; easiest way is to swap them into another reg first.
5569   int ShufMask[2] = { 1, -1 };
5570   SDValue Shuf = DAG.getVectorShuffle(MVT::v2f64, dl, Sub,
5571                                       DAG.getUNDEF(MVT::v2f64), ShufMask);
5572   SDValue Add = DAG.getNode(ISD::FADD, dl, MVT::v2f64, Shuf, Sub);
5573   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Add,
5574                      DAG.getIntPtrConstant(0));
5575 }
5576
5577 // LowerUINT_TO_FP_i32 - 32-bit unsigned integer to float expansion.
5578 SDValue X86TargetLowering::LowerUINT_TO_FP_i32(SDValue Op,
5579                                                SelectionDAG &DAG) const {
5580   DebugLoc dl = Op.getDebugLoc();
5581   // FP constant to bias correct the final result.
5582   SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL),
5583                                    MVT::f64);
5584
5585   // Load the 32-bit value into an XMM register.
5586   SDValue Load = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
5587                              DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
5588                                          Op.getOperand(0),
5589                                          DAG.getIntPtrConstant(0)));
5590
5591   Load = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
5592                      DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v2f64, Load),
5593                      DAG.getIntPtrConstant(0));
5594
5595   // Or the load with the bias.
5596   SDValue Or = DAG.getNode(ISD::OR, dl, MVT::v2i64,
5597                            DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v2i64,
5598                                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
5599                                                    MVT::v2f64, Load)),
5600                            DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v2i64,
5601                                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
5602                                                    MVT::v2f64, Bias)));
5603   Or = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
5604                    DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v2f64, Or),
5605                    DAG.getIntPtrConstant(0));
5606
5607   // Subtract the bias.
5608   SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::f64, Or, Bias);
5609
5610   // Handle final rounding.
5611   EVT DestVT = Op.getValueType();
5612
5613   if (DestVT.bitsLT(MVT::f64)) {
5614     return DAG.getNode(ISD::FP_ROUND, dl, DestVT, Sub,
5615                        DAG.getIntPtrConstant(0));
5616   } else if (DestVT.bitsGT(MVT::f64)) {
5617     return DAG.getNode(ISD::FP_EXTEND, dl, DestVT, Sub);
5618   }
5619
5620   // Handle final rounding.
5621   return Sub;
5622 }
5623
5624 SDValue X86TargetLowering::LowerUINT_TO_FP(SDValue Op,
5625                                            SelectionDAG &DAG) const {
5626   SDValue N0 = Op.getOperand(0);
5627   DebugLoc dl = Op.getDebugLoc();
5628
5629   // Now not UINT_TO_FP is legal (it's marked custom), dag combiner won't
5630   // optimize it to a SINT_TO_FP when the sign bit is known zero. Perform
5631   // the optimization here.
5632   if (DAG.SignBitIsZero(N0))
5633     return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(), N0);
5634
5635   EVT SrcVT = N0.getValueType();
5636   if (SrcVT == MVT::i64) {
5637     // We only handle SSE2 f64 target here; caller can expand the rest.
5638     if (Op.getValueType() != MVT::f64 || !X86ScalarSSEf64)
5639       return SDValue();
5640
5641     return LowerUINT_TO_FP_i64(Op, DAG);
5642   } else if (SrcVT == MVT::i32 && X86ScalarSSEf64) {
5643     return LowerUINT_TO_FP_i32(Op, DAG);
5644   }
5645
5646   assert(SrcVT == MVT::i32 && "Unknown UINT_TO_FP to lower!");
5647
5648   // Make a 64-bit buffer, and use it to build an FILD.
5649   SDValue StackSlot = DAG.CreateStackTemporary(MVT::i64);
5650   SDValue WordOff = DAG.getConstant(4, getPointerTy());
5651   SDValue OffsetSlot = DAG.getNode(ISD::ADD, dl,
5652                                    getPointerTy(), StackSlot, WordOff);
5653   SDValue Store1 = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
5654                                 StackSlot, NULL, 0, false, false, 0);
5655   SDValue Store2 = DAG.getStore(Store1, dl, DAG.getConstant(0, MVT::i32),
5656                                 OffsetSlot, NULL, 0, false, false, 0);
5657   return BuildFILD(Op, MVT::i64, Store2, StackSlot, DAG);
5658 }
5659
5660 std::pair<SDValue,SDValue> X86TargetLowering::
5661 FP_TO_INTHelper(SDValue Op, SelectionDAG &DAG, bool IsSigned) const {
5662   DebugLoc dl = Op.getDebugLoc();
5663
5664   EVT DstTy = Op.getValueType();
5665
5666   if (!IsSigned) {
5667     assert(DstTy == MVT::i32 && "Unexpected FP_TO_UINT");
5668     DstTy = MVT::i64;
5669   }
5670
5671   assert(DstTy.getSimpleVT() <= MVT::i64 &&
5672          DstTy.getSimpleVT() >= MVT::i16 &&
5673          "Unknown FP_TO_SINT to lower!");
5674
5675   // These are really Legal.
5676   if (DstTy == MVT::i32 &&
5677       isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
5678     return std::make_pair(SDValue(), SDValue());
5679   if (Subtarget->is64Bit() &&
5680       DstTy == MVT::i64 &&
5681       isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
5682     return std::make_pair(SDValue(), SDValue());
5683
5684   // We lower FP->sint64 into FISTP64, followed by a load, all to a temporary
5685   // stack slot.
5686   MachineFunction &MF = DAG.getMachineFunction();
5687   unsigned MemSize = DstTy.getSizeInBits()/8;
5688   int SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
5689   SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
5690
5691   unsigned Opc;
5692   switch (DstTy.getSimpleVT().SimpleTy) {
5693   default: llvm_unreachable("Invalid FP_TO_SINT to lower!");
5694   case MVT::i16: Opc = X86ISD::FP_TO_INT16_IN_MEM; break;
5695   case MVT::i32: Opc = X86ISD::FP_TO_INT32_IN_MEM; break;
5696   case MVT::i64: Opc = X86ISD::FP_TO_INT64_IN_MEM; break;
5697   }
5698
5699   SDValue Chain = DAG.getEntryNode();
5700   SDValue Value = Op.getOperand(0);
5701   if (isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType())) {
5702     assert(DstTy == MVT::i64 && "Invalid FP_TO_SINT to lower!");
5703     Chain = DAG.getStore(Chain, dl, Value, StackSlot,
5704                          PseudoSourceValue::getFixedStack(SSFI), 0,
5705                          false, false, 0);
5706     SDVTList Tys = DAG.getVTList(Op.getOperand(0).getValueType(), MVT::Other);
5707     SDValue Ops[] = {
5708       Chain, StackSlot, DAG.getValueType(Op.getOperand(0).getValueType())
5709     };
5710     Value = DAG.getNode(X86ISD::FLD, dl, Tys, Ops, 3);
5711     Chain = Value.getValue(1);
5712     SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
5713     StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
5714   }
5715
5716   // Build the FP_TO_INT*_IN_MEM
5717   SDValue Ops[] = { Chain, Value, StackSlot };
5718   SDValue FIST = DAG.getNode(Opc, dl, MVT::Other, Ops, 3);
5719
5720   return std::make_pair(FIST, StackSlot);
5721 }
5722
5723 SDValue X86TargetLowering::LowerFP_TO_SINT(SDValue Op,
5724                                            SelectionDAG &DAG) const {
5725   if (Op.getValueType().isVector()) {
5726     if (Op.getValueType() == MVT::v2i32 &&
5727         Op.getOperand(0).getValueType() == MVT::v2f64) {
5728       return Op;
5729     }
5730     return SDValue();
5731   }
5732
5733   std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG, true);
5734   SDValue FIST = Vals.first, StackSlot = Vals.second;
5735   // If FP_TO_INTHelper failed, the node is actually supposed to be Legal.
5736   if (FIST.getNode() == 0) return Op;
5737
5738   // Load the result.
5739   return DAG.getLoad(Op.getValueType(), Op.getDebugLoc(),
5740                      FIST, StackSlot, NULL, 0, false, false, 0);
5741 }
5742
5743 SDValue X86TargetLowering::LowerFP_TO_UINT(SDValue Op,
5744                                            SelectionDAG &DAG) const {
5745   std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG, false);
5746   SDValue FIST = Vals.first, StackSlot = Vals.second;
5747   assert(FIST.getNode() && "Unexpected failure");
5748
5749   // Load the result.
5750   return DAG.getLoad(Op.getValueType(), Op.getDebugLoc(),
5751                      FIST, StackSlot, NULL, 0, false, false, 0);
5752 }
5753
5754 SDValue X86TargetLowering::LowerFABS(SDValue Op,
5755                                      SelectionDAG &DAG) const {
5756   LLVMContext *Context = DAG.getContext();
5757   DebugLoc dl = Op.getDebugLoc();
5758   EVT VT = Op.getValueType();
5759   EVT EltVT = VT;
5760   if (VT.isVector())
5761     EltVT = VT.getVectorElementType();
5762   std::vector<Constant*> CV;
5763   if (EltVT == MVT::f64) {
5764     Constant *C = ConstantFP::get(*Context, APFloat(APInt(64, ~(1ULL << 63))));
5765     CV.push_back(C);
5766     CV.push_back(C);
5767   } else {
5768     Constant *C = ConstantFP::get(*Context, APFloat(APInt(32, ~(1U << 31))));
5769     CV.push_back(C);
5770     CV.push_back(C);
5771     CV.push_back(C);
5772     CV.push_back(C);
5773   }
5774   Constant *C = ConstantVector::get(CV);
5775   SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
5776   SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
5777                              PseudoSourceValue::getConstantPool(), 0,
5778                              false, false, 16);
5779   return DAG.getNode(X86ISD::FAND, dl, VT, Op.getOperand(0), Mask);
5780 }
5781
5782 SDValue X86TargetLowering::LowerFNEG(SDValue Op, SelectionDAG &DAG) const {
5783   LLVMContext *Context = DAG.getContext();
5784   DebugLoc dl = Op.getDebugLoc();
5785   EVT VT = Op.getValueType();
5786   EVT EltVT = VT;
5787   if (VT.isVector())
5788     EltVT = VT.getVectorElementType();
5789   std::vector<Constant*> CV;
5790   if (EltVT == MVT::f64) {
5791     Constant *C = ConstantFP::get(*Context, APFloat(APInt(64, 1ULL << 63)));
5792     CV.push_back(C);
5793     CV.push_back(C);
5794   } else {
5795     Constant *C = ConstantFP::get(*Context, APFloat(APInt(32, 1U << 31)));
5796     CV.push_back(C);
5797     CV.push_back(C);
5798     CV.push_back(C);
5799     CV.push_back(C);
5800   }
5801   Constant *C = ConstantVector::get(CV);
5802   SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
5803   SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
5804                              PseudoSourceValue::getConstantPool(), 0,
5805                              false, false, 16);
5806   if (VT.isVector()) {
5807     return DAG.getNode(ISD::BIT_CONVERT, dl, VT,
5808                        DAG.getNode(ISD::XOR, dl, MVT::v2i64,
5809                     DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v2i64,
5810                                 Op.getOperand(0)),
5811                     DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v2i64, Mask)));
5812   } else {
5813     return DAG.getNode(X86ISD::FXOR, dl, VT, Op.getOperand(0), Mask);
5814   }
5815 }
5816
5817 SDValue X86TargetLowering::LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) const {
5818   LLVMContext *Context = DAG.getContext();
5819   SDValue Op0 = Op.getOperand(0);
5820   SDValue Op1 = Op.getOperand(1);
5821   DebugLoc dl = Op.getDebugLoc();
5822   EVT VT = Op.getValueType();
5823   EVT SrcVT = Op1.getValueType();
5824
5825   // If second operand is smaller, extend it first.
5826   if (SrcVT.bitsLT(VT)) {
5827     Op1 = DAG.getNode(ISD::FP_EXTEND, dl, VT, Op1);
5828     SrcVT = VT;
5829   }
5830   // And if it is bigger, shrink it first.
5831   if (SrcVT.bitsGT(VT)) {
5832     Op1 = DAG.getNode(ISD::FP_ROUND, dl, VT, Op1, DAG.getIntPtrConstant(1));
5833     SrcVT = VT;
5834   }
5835
5836   // At this point the operands and the result should have the same
5837   // type, and that won't be f80 since that is not custom lowered.
5838
5839   // First get the sign bit of second operand.
5840   std::vector<Constant*> CV;
5841   if (SrcVT == MVT::f64) {
5842     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, 1ULL << 63))));
5843     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, 0))));
5844   } else {
5845     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 1U << 31))));
5846     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
5847     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
5848     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
5849   }
5850   Constant *C = ConstantVector::get(CV);
5851   SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
5852   SDValue Mask1 = DAG.getLoad(SrcVT, dl, DAG.getEntryNode(), CPIdx,
5853                               PseudoSourceValue::getConstantPool(), 0,
5854                               false, false, 16);
5855   SDValue SignBit = DAG.getNode(X86ISD::FAND, dl, SrcVT, Op1, Mask1);
5856
5857   // Shift sign bit right or left if the two operands have different types.
5858   if (SrcVT.bitsGT(VT)) {
5859     // Op0 is MVT::f32, Op1 is MVT::f64.
5860     SignBit = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f64, SignBit);
5861     SignBit = DAG.getNode(X86ISD::FSRL, dl, MVT::v2f64, SignBit,
5862                           DAG.getConstant(32, MVT::i32));
5863     SignBit = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v4f32, SignBit);
5864     SignBit = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f32, SignBit,
5865                           DAG.getIntPtrConstant(0));
5866   }
5867
5868   // Clear first operand sign bit.
5869   CV.clear();
5870   if (VT == MVT::f64) {
5871     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, ~(1ULL << 63)))));
5872     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, 0))));
5873   } else {
5874     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, ~(1U << 31)))));
5875     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
5876     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
5877     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
5878   }
5879   C = ConstantVector::get(CV);
5880   CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
5881   SDValue Mask2 = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
5882                               PseudoSourceValue::getConstantPool(), 0,
5883                               false, false, 16);
5884   SDValue Val = DAG.getNode(X86ISD::FAND, dl, VT, Op0, Mask2);
5885
5886   // Or the value with the sign bit.
5887   return DAG.getNode(X86ISD::FOR, dl, VT, Val, SignBit);
5888 }
5889
5890 /// Emit nodes that will be selected as "test Op0,Op0", or something
5891 /// equivalent.
5892 SDValue X86TargetLowering::EmitTest(SDValue Op, unsigned X86CC,
5893                                     SelectionDAG &DAG) const {
5894   DebugLoc dl = Op.getDebugLoc();
5895
5896   // CF and OF aren't always set the way we want. Determine which
5897   // of these we need.
5898   bool NeedCF = false;
5899   bool NeedOF = false;
5900   switch (X86CC) {
5901   case X86::COND_A: case X86::COND_AE:
5902   case X86::COND_B: case X86::COND_BE:
5903     NeedCF = true;
5904     break;
5905   case X86::COND_G: case X86::COND_GE:
5906   case X86::COND_L: case X86::COND_LE:
5907   case X86::COND_O: case X86::COND_NO:
5908     NeedOF = true;
5909     break;
5910   default: break;
5911   }
5912
5913   // See if we can use the EFLAGS value from the operand instead of
5914   // doing a separate TEST. TEST always sets OF and CF to 0, so unless
5915   // we prove that the arithmetic won't overflow, we can't use OF or CF.
5916   if (Op.getResNo() == 0 && !NeedOF && !NeedCF) {
5917     unsigned Opcode = 0;
5918     unsigned NumOperands = 0;
5919     switch (Op.getNode()->getOpcode()) {
5920     case ISD::ADD:
5921       // Due to an isel shortcoming, be conservative if this add is likely to
5922       // be selected as part of a load-modify-store instruction. When the root
5923       // node in a match is a store, isel doesn't know how to remap non-chain
5924       // non-flag uses of other nodes in the match, such as the ADD in this
5925       // case. This leads to the ADD being left around and reselected, with
5926       // the result being two adds in the output.
5927       for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
5928            UE = Op.getNode()->use_end(); UI != UE; ++UI)
5929         if (UI->getOpcode() == ISD::STORE)
5930           goto default_case;
5931       if (ConstantSDNode *C =
5932             dyn_cast<ConstantSDNode>(Op.getNode()->getOperand(1))) {
5933         // An add of one will be selected as an INC.
5934         if (C->getAPIntValue() == 1) {
5935           Opcode = X86ISD::INC;
5936           NumOperands = 1;
5937           break;
5938         }
5939         // An add of negative one (subtract of one) will be selected as a DEC.
5940         if (C->getAPIntValue().isAllOnesValue()) {
5941           Opcode = X86ISD::DEC;
5942           NumOperands = 1;
5943           break;
5944         }
5945       }
5946       // Otherwise use a regular EFLAGS-setting add.
5947       Opcode = X86ISD::ADD;
5948       NumOperands = 2;
5949       break;
5950     case ISD::AND: {
5951       // If the primary and result isn't used, don't bother using X86ISD::AND,
5952       // because a TEST instruction will be better.
5953       bool NonFlagUse = false;
5954       for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
5955              UE = Op.getNode()->use_end(); UI != UE; ++UI) {
5956         SDNode *User = *UI;
5957         unsigned UOpNo = UI.getOperandNo();
5958         if (User->getOpcode() == ISD::TRUNCATE && User->hasOneUse()) {
5959           // Look pass truncate.
5960           UOpNo = User->use_begin().getOperandNo();
5961           User = *User->use_begin();
5962         }
5963         if (User->getOpcode() != ISD::BRCOND &&
5964             User->getOpcode() != ISD::SETCC &&
5965             (User->getOpcode() != ISD::SELECT || UOpNo != 0)) {
5966           NonFlagUse = true;
5967           break;
5968         }
5969       }
5970       if (!NonFlagUse)
5971         break;
5972     }
5973     // FALL THROUGH
5974     case ISD::SUB:
5975     case ISD::OR:
5976     case ISD::XOR:
5977       // Due to the ISEL shortcoming noted above, be conservative if this op is
5978       // likely to be selected as part of a load-modify-store instruction.
5979       for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
5980            UE = Op.getNode()->use_end(); UI != UE; ++UI)
5981         if (UI->getOpcode() == ISD::STORE)
5982           goto default_case;
5983       // Otherwise use a regular EFLAGS-setting instruction.
5984       switch (Op.getNode()->getOpcode()) {
5985       case ISD::SUB: Opcode = X86ISD::SUB; break;
5986       case ISD::OR:  Opcode = X86ISD::OR;  break;
5987       case ISD::XOR: Opcode = X86ISD::XOR; break;
5988       case ISD::AND: Opcode = X86ISD::AND; break;
5989       default: llvm_unreachable("unexpected operator!");
5990       }
5991       NumOperands = 2;
5992       break;
5993     case X86ISD::ADD:
5994     case X86ISD::SUB:
5995     case X86ISD::INC:
5996     case X86ISD::DEC:
5997     case X86ISD::OR:
5998     case X86ISD::XOR:
5999     case X86ISD::AND:
6000       return SDValue(Op.getNode(), 1);
6001     default:
6002     default_case:
6003       break;
6004     }
6005     if (Opcode != 0) {
6006       SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
6007       SmallVector<SDValue, 4> Ops;
6008       for (unsigned i = 0; i != NumOperands; ++i)
6009         Ops.push_back(Op.getOperand(i));
6010       SDValue New = DAG.getNode(Opcode, dl, VTs, &Ops[0], NumOperands);
6011       DAG.ReplaceAllUsesWith(Op, New);
6012       return SDValue(New.getNode(), 1);
6013     }
6014   }
6015
6016   // Otherwise just emit a CMP with 0, which is the TEST pattern.
6017   return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
6018                      DAG.getConstant(0, Op.getValueType()));
6019 }
6020
6021 /// Emit nodes that will be selected as "cmp Op0,Op1", or something
6022 /// equivalent.
6023 SDValue X86TargetLowering::EmitCmp(SDValue Op0, SDValue Op1, unsigned X86CC,
6024                                    SelectionDAG &DAG) const {
6025   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op1))
6026     if (C->getAPIntValue() == 0)
6027       return EmitTest(Op0, X86CC, DAG);
6028
6029   DebugLoc dl = Op0.getDebugLoc();
6030   return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op0, Op1);
6031 }
6032
6033 /// LowerToBT - Result of 'and' is compared against zero. Turn it into a BT node
6034 /// if it's possible.
6035 SDValue X86TargetLowering::LowerToBT(SDValue And, ISD::CondCode CC,
6036                                      DebugLoc dl, SelectionDAG &DAG) const {
6037   SDValue Op0 = And.getOperand(0);
6038   SDValue Op1 = And.getOperand(1);
6039   if (Op0.getOpcode() == ISD::TRUNCATE)
6040     Op0 = Op0.getOperand(0);
6041   if (Op1.getOpcode() == ISD::TRUNCATE)
6042     Op1 = Op1.getOperand(0);
6043
6044   SDValue LHS, RHS;
6045   if (Op1.getOpcode() == ISD::SHL) {
6046     if (ConstantSDNode *And10C = dyn_cast<ConstantSDNode>(Op1.getOperand(0)))
6047       if (And10C->getZExtValue() == 1) {
6048         LHS = Op0;
6049         RHS = Op1.getOperand(1);
6050       }
6051   } else if (Op0.getOpcode() == ISD::SHL) {
6052     if (ConstantSDNode *And00C = dyn_cast<ConstantSDNode>(Op0.getOperand(0)))
6053       if (And00C->getZExtValue() == 1) {
6054         LHS = Op1;
6055         RHS = Op0.getOperand(1);
6056       }
6057   } else if (Op1.getOpcode() == ISD::Constant) {
6058     ConstantSDNode *AndRHS = cast<ConstantSDNode>(Op1);
6059     SDValue AndLHS = Op0;
6060     if (AndRHS->getZExtValue() == 1 && AndLHS.getOpcode() == ISD::SRL) {
6061       LHS = AndLHS.getOperand(0);
6062       RHS = AndLHS.getOperand(1);
6063     }
6064   }
6065
6066   if (LHS.getNode()) {
6067     // If LHS is i8, promote it to i32 with any_extend.  There is no i8 BT
6068     // instruction.  Since the shift amount is in-range-or-undefined, we know
6069     // that doing a bittest on the i32 value is ok.  We extend to i32 because
6070     // the encoding for the i16 version is larger than the i32 version.
6071     // Also promote i16 to i32 for performance / code size reason.
6072     if (LHS.getValueType() == MVT::i8 ||
6073         (Subtarget->shouldPromote16Bit() && LHS.getValueType() == MVT::i16))
6074       LHS = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, LHS);
6075
6076     // If the operand types disagree, extend the shift amount to match.  Since
6077     // BT ignores high bits (like shifts) we can use anyextend.
6078     if (LHS.getValueType() != RHS.getValueType())
6079       RHS = DAG.getNode(ISD::ANY_EXTEND, dl, LHS.getValueType(), RHS);
6080
6081     SDValue BT = DAG.getNode(X86ISD::BT, dl, MVT::i32, LHS, RHS);
6082     unsigned Cond = CC == ISD::SETEQ ? X86::COND_AE : X86::COND_B;
6083     return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
6084                        DAG.getConstant(Cond, MVT::i8), BT);
6085   }
6086
6087   return SDValue();
6088 }
6089
6090 SDValue X86TargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
6091   assert(Op.getValueType() == MVT::i8 && "SetCC type must be 8-bit integer");
6092   SDValue Op0 = Op.getOperand(0);
6093   SDValue Op1 = Op.getOperand(1);
6094   DebugLoc dl = Op.getDebugLoc();
6095   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
6096
6097   // Optimize to BT if possible.
6098   // Lower (X & (1 << N)) == 0 to BT(X, N).
6099   // Lower ((X >>u N) & 1) != 0 to BT(X, N).
6100   // Lower ((X >>s N) & 1) != 0 to BT(X, N).
6101   if (Op0.getOpcode() == ISD::AND &&
6102       Op0.hasOneUse() &&
6103       Op1.getOpcode() == ISD::Constant &&
6104       cast<ConstantSDNode>(Op1)->getZExtValue() == 0 &&
6105       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
6106     SDValue NewSetCC = LowerToBT(Op0, CC, dl, DAG);
6107     if (NewSetCC.getNode())
6108       return NewSetCC;
6109   }
6110
6111   // Look for "(setcc) == / != 1" to avoid unncessary setcc.
6112   if (Op0.getOpcode() == X86ISD::SETCC &&
6113       Op1.getOpcode() == ISD::Constant &&
6114       (cast<ConstantSDNode>(Op1)->getZExtValue() == 1 ||
6115        cast<ConstantSDNode>(Op1)->isNullValue()) &&
6116       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
6117     X86::CondCode CCode = (X86::CondCode)Op0.getConstantOperandVal(0);
6118     bool Invert = (CC == ISD::SETNE) ^
6119       cast<ConstantSDNode>(Op1)->isNullValue();
6120     if (Invert)
6121       CCode = X86::GetOppositeBranchCondition(CCode);
6122     return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
6123                        DAG.getConstant(CCode, MVT::i8), Op0.getOperand(1));
6124   }
6125
6126   bool isFP = Op1.getValueType().isFloatingPoint();
6127   unsigned X86CC = TranslateX86CC(CC, isFP, Op0, Op1, DAG);
6128   if (X86CC == X86::COND_INVALID)
6129     return SDValue();
6130
6131   SDValue Cond = EmitCmp(Op0, Op1, X86CC, DAG);
6132
6133   // Use sbb x, x to materialize carry bit into a GPR.
6134   if (X86CC == X86::COND_B)
6135     return DAG.getNode(ISD::AND, dl, MVT::i8,
6136                        DAG.getNode(X86ISD::SETCC_CARRY, dl, MVT::i8,
6137                                    DAG.getConstant(X86CC, MVT::i8), Cond),
6138                        DAG.getConstant(1, MVT::i8));
6139
6140   return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
6141                      DAG.getConstant(X86CC, MVT::i8), Cond);
6142 }
6143
6144 SDValue X86TargetLowering::LowerVSETCC(SDValue Op, SelectionDAG &DAG) const {
6145   SDValue Cond;
6146   SDValue Op0 = Op.getOperand(0);
6147   SDValue Op1 = Op.getOperand(1);
6148   SDValue CC = Op.getOperand(2);
6149   EVT VT = Op.getValueType();
6150   ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
6151   bool isFP = Op.getOperand(1).getValueType().isFloatingPoint();
6152   DebugLoc dl = Op.getDebugLoc();
6153
6154   if (isFP) {
6155     unsigned SSECC = 8;
6156     EVT VT0 = Op0.getValueType();
6157     assert(VT0 == MVT::v4f32 || VT0 == MVT::v2f64);
6158     unsigned Opc = VT0 == MVT::v4f32 ? X86ISD::CMPPS : X86ISD::CMPPD;
6159     bool Swap = false;
6160
6161     switch (SetCCOpcode) {
6162     default: break;
6163     case ISD::SETOEQ:
6164     case ISD::SETEQ:  SSECC = 0; break;
6165     case ISD::SETOGT:
6166     case ISD::SETGT: Swap = true; // Fallthrough
6167     case ISD::SETLT:
6168     case ISD::SETOLT: SSECC = 1; break;
6169     case ISD::SETOGE:
6170     case ISD::SETGE: Swap = true; // Fallthrough
6171     case ISD::SETLE:
6172     case ISD::SETOLE: SSECC = 2; break;
6173     case ISD::SETUO:  SSECC = 3; break;
6174     case ISD::SETUNE:
6175     case ISD::SETNE:  SSECC = 4; break;
6176     case ISD::SETULE: Swap = true;
6177     case ISD::SETUGE: SSECC = 5; break;
6178     case ISD::SETULT: Swap = true;
6179     case ISD::SETUGT: SSECC = 6; break;
6180     case ISD::SETO:   SSECC = 7; break;
6181     }
6182     if (Swap)
6183       std::swap(Op0, Op1);
6184
6185     // In the two special cases we can't handle, emit two comparisons.
6186     if (SSECC == 8) {
6187       if (SetCCOpcode == ISD::SETUEQ) {
6188         SDValue UNORD, EQ;
6189         UNORD = DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(3, MVT::i8));
6190         EQ = DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(0, MVT::i8));
6191         return DAG.getNode(ISD::OR, dl, VT, UNORD, EQ);
6192       }
6193       else if (SetCCOpcode == ISD::SETONE) {
6194         SDValue ORD, NEQ;
6195         ORD = DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(7, MVT::i8));
6196         NEQ = DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(4, MVT::i8));
6197         return DAG.getNode(ISD::AND, dl, VT, ORD, NEQ);
6198       }
6199       llvm_unreachable("Illegal FP comparison");
6200     }
6201     // Handle all other FP comparisons here.
6202     return DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(SSECC, MVT::i8));
6203   }
6204
6205   // We are handling one of the integer comparisons here.  Since SSE only has
6206   // GT and EQ comparisons for integer, swapping operands and multiple
6207   // operations may be required for some comparisons.
6208   unsigned Opc = 0, EQOpc = 0, GTOpc = 0;
6209   bool Swap = false, Invert = false, FlipSigns = false;
6210
6211   switch (VT.getSimpleVT().SimpleTy) {
6212   default: break;
6213   case MVT::v8i8:
6214   case MVT::v16i8: EQOpc = X86ISD::PCMPEQB; GTOpc = X86ISD::PCMPGTB; break;
6215   case MVT::v4i16:
6216   case MVT::v8i16: EQOpc = X86ISD::PCMPEQW; GTOpc = X86ISD::PCMPGTW; break;
6217   case MVT::v2i32:
6218   case MVT::v4i32: EQOpc = X86ISD::PCMPEQD; GTOpc = X86ISD::PCMPGTD; break;
6219   case MVT::v2i64: EQOpc = X86ISD::PCMPEQQ; GTOpc = X86ISD::PCMPGTQ; break;
6220   }
6221
6222   switch (SetCCOpcode) {
6223   default: break;
6224   case ISD::SETNE:  Invert = true;
6225   case ISD::SETEQ:  Opc = EQOpc; break;
6226   case ISD::SETLT:  Swap = true;
6227   case ISD::SETGT:  Opc = GTOpc; break;
6228   case ISD::SETGE:  Swap = true;
6229   case ISD::SETLE:  Opc = GTOpc; Invert = true; break;
6230   case ISD::SETULT: Swap = true;
6231   case ISD::SETUGT: Opc = GTOpc; FlipSigns = true; break;
6232   case ISD::SETUGE: Swap = true;
6233   case ISD::SETULE: Opc = GTOpc; FlipSigns = true; Invert = true; break;
6234   }
6235   if (Swap)
6236     std::swap(Op0, Op1);
6237
6238   // Since SSE has no unsigned integer comparisons, we need to flip  the sign
6239   // bits of the inputs before performing those operations.
6240   if (FlipSigns) {
6241     EVT EltVT = VT.getVectorElementType();
6242     SDValue SignBit = DAG.getConstant(APInt::getSignBit(EltVT.getSizeInBits()),
6243                                       EltVT);
6244     std::vector<SDValue> SignBits(VT.getVectorNumElements(), SignBit);
6245     SDValue SignVec = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &SignBits[0],
6246                                     SignBits.size());
6247     Op0 = DAG.getNode(ISD::XOR, dl, VT, Op0, SignVec);
6248     Op1 = DAG.getNode(ISD::XOR, dl, VT, Op1, SignVec);
6249   }
6250
6251   SDValue Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
6252
6253   // If the logical-not of the result is required, perform that now.
6254   if (Invert)
6255     Result = DAG.getNOT(dl, Result, VT);
6256
6257   return Result;
6258 }
6259
6260 // isX86LogicalCmp - Return true if opcode is a X86 logical comparison.
6261 static bool isX86LogicalCmp(SDValue Op) {
6262   unsigned Opc = Op.getNode()->getOpcode();
6263   if (Opc == X86ISD::CMP || Opc == X86ISD::COMI || Opc == X86ISD::UCOMI)
6264     return true;
6265   if (Op.getResNo() == 1 &&
6266       (Opc == X86ISD::ADD ||
6267        Opc == X86ISD::SUB ||
6268        Opc == X86ISD::SMUL ||
6269        Opc == X86ISD::UMUL ||
6270        Opc == X86ISD::INC ||
6271        Opc == X86ISD::DEC ||
6272        Opc == X86ISD::OR ||
6273        Opc == X86ISD::XOR ||
6274        Opc == X86ISD::AND))
6275     return true;
6276
6277   return false;
6278 }
6279
6280 SDValue X86TargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
6281   bool addTest = true;
6282   SDValue Cond  = Op.getOperand(0);
6283   DebugLoc dl = Op.getDebugLoc();
6284   SDValue CC;
6285
6286   if (Cond.getOpcode() == ISD::SETCC) {
6287     SDValue NewCond = LowerSETCC(Cond, DAG);
6288     if (NewCond.getNode())
6289       Cond = NewCond;
6290   }
6291
6292   // (select (x == 0), -1, 0) -> (sign_bit (x - 1))
6293   SDValue Op1 = Op.getOperand(1);
6294   SDValue Op2 = Op.getOperand(2);
6295   if (Cond.getOpcode() == X86ISD::SETCC &&
6296       cast<ConstantSDNode>(Cond.getOperand(0))->getZExtValue() == X86::COND_E) {
6297     SDValue Cmp = Cond.getOperand(1);
6298     if (Cmp.getOpcode() == X86ISD::CMP) {
6299       ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(Op1);
6300       ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(Op2);
6301       ConstantSDNode *RHSC =
6302         dyn_cast<ConstantSDNode>(Cmp.getOperand(1).getNode());
6303       if (N1C && N1C->isAllOnesValue() &&
6304           N2C && N2C->isNullValue() &&
6305           RHSC && RHSC->isNullValue()) {
6306         SDValue CmpOp0 = Cmp.getOperand(0);
6307         Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
6308                           CmpOp0, DAG.getConstant(1, CmpOp0.getValueType()));
6309         return DAG.getNode(X86ISD::SETCC_CARRY, dl, Op.getValueType(),
6310                            DAG.getConstant(X86::COND_B, MVT::i8), Cmp);
6311       }
6312     }
6313   }
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     EVT VT = Op.getValueType();
6332
6333     bool IllegalFPCMov = false;
6334     if (VT.isFloatingPoint() && !VT.isVector() &&
6335         !isScalarFPTypeInSSEReg(VT))  // FPStack?
6336       IllegalFPCMov = !hasFPCMov(cast<ConstantSDNode>(CC)->getSExtValue());
6337
6338     if ((isX86LogicalCmp(Cmp) && !IllegalFPCMov) ||
6339         Opc == X86ISD::BT) { // FIXME
6340       Cond = Cmp;
6341       addTest = false;
6342     }
6343   }
6344
6345   if (addTest) {
6346     // Look pass the truncate.
6347     if (Cond.getOpcode() == ISD::TRUNCATE)
6348       Cond = Cond.getOperand(0);
6349
6350     // We know the result of AND is compared against zero. Try to match
6351     // it to BT.
6352     if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) { 
6353       SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, dl, DAG);
6354       if (NewSetCC.getNode()) {
6355         CC = NewSetCC.getOperand(0);
6356         Cond = NewSetCC.getOperand(1);
6357         addTest = false;
6358       }
6359     }
6360   }
6361
6362   if (addTest) {
6363     CC = DAG.getConstant(X86::COND_NE, MVT::i8);
6364     Cond = EmitTest(Cond, X86::COND_NE, DAG);
6365   }
6366
6367   // X86ISD::CMOV means set the result (which is operand 1) to the RHS if
6368   // condition is true.
6369   SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::Flag);
6370   SDValue Ops[] = { Op2, Op1, CC, Cond };
6371   return DAG.getNode(X86ISD::CMOV, dl, VTs, Ops, array_lengthof(Ops));
6372 }
6373
6374 // isAndOrOfSingleUseSetCCs - Return true if node is an ISD::AND or
6375 // ISD::OR of two X86ISD::SETCC nodes each of which has no other use apart
6376 // from the AND / OR.
6377 static bool isAndOrOfSetCCs(SDValue Op, unsigned &Opc) {
6378   Opc = Op.getOpcode();
6379   if (Opc != ISD::OR && Opc != ISD::AND)
6380     return false;
6381   return (Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
6382           Op.getOperand(0).hasOneUse() &&
6383           Op.getOperand(1).getOpcode() == X86ISD::SETCC &&
6384           Op.getOperand(1).hasOneUse());
6385 }
6386
6387 // isXor1OfSetCC - Return true if node is an ISD::XOR of a X86ISD::SETCC and
6388 // 1 and that the SETCC node has a single use.
6389 static bool isXor1OfSetCC(SDValue Op) {
6390   if (Op.getOpcode() != ISD::XOR)
6391     return false;
6392   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
6393   if (N1C && N1C->getAPIntValue() == 1) {
6394     return Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
6395       Op.getOperand(0).hasOneUse();
6396   }
6397   return false;
6398 }
6399
6400 SDValue X86TargetLowering::LowerBRCOND(SDValue Op, SelectionDAG &DAG) const {
6401   bool addTest = true;
6402   SDValue Chain = Op.getOperand(0);
6403   SDValue Cond  = Op.getOperand(1);
6404   SDValue Dest  = Op.getOperand(2);
6405   DebugLoc dl = Op.getDebugLoc();
6406   SDValue CC;
6407
6408   if (Cond.getOpcode() == ISD::SETCC) {
6409     SDValue NewCond = LowerSETCC(Cond, DAG);
6410     if (NewCond.getNode())
6411       Cond = NewCond;
6412   }
6413 #if 0
6414   // FIXME: LowerXALUO doesn't handle these!!
6415   else if (Cond.getOpcode() == X86ISD::ADD  ||
6416            Cond.getOpcode() == X86ISD::SUB  ||
6417            Cond.getOpcode() == X86ISD::SMUL ||
6418            Cond.getOpcode() == X86ISD::UMUL)
6419     Cond = LowerXALUO(Cond, DAG);
6420 #endif
6421
6422   // Look pass (and (setcc_carry (cmp ...)), 1).
6423   if (Cond.getOpcode() == ISD::AND &&
6424       Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
6425     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
6426     if (C && C->getAPIntValue() == 1) 
6427       Cond = Cond.getOperand(0);
6428   }
6429
6430   // If condition flag is set by a X86ISD::CMP, then use it as the condition
6431   // setting operand in place of the X86ISD::SETCC.
6432   if (Cond.getOpcode() == X86ISD::SETCC ||
6433       Cond.getOpcode() == X86ISD::SETCC_CARRY) {
6434     CC = Cond.getOperand(0);
6435
6436     SDValue Cmp = Cond.getOperand(1);
6437     unsigned Opc = Cmp.getOpcode();
6438     // FIXME: WHY THE SPECIAL CASING OF LogicalCmp??
6439     if (isX86LogicalCmp(Cmp) || Opc == X86ISD::BT) {
6440       Cond = Cmp;
6441       addTest = false;
6442     } else {
6443       switch (cast<ConstantSDNode>(CC)->getZExtValue()) {
6444       default: break;
6445       case X86::COND_O:
6446       case X86::COND_B:
6447         // These can only come from an arithmetic instruction with overflow,
6448         // e.g. SADDO, UADDO.
6449         Cond = Cond.getNode()->getOperand(1);
6450         addTest = false;
6451         break;
6452       }
6453     }
6454   } else {
6455     unsigned CondOpc;
6456     if (Cond.hasOneUse() && isAndOrOfSetCCs(Cond, CondOpc)) {
6457       SDValue Cmp = Cond.getOperand(0).getOperand(1);
6458       if (CondOpc == ISD::OR) {
6459         // Also, recognize the pattern generated by an FCMP_UNE. We can emit
6460         // two branches instead of an explicit OR instruction with a
6461         // separate test.
6462         if (Cmp == Cond.getOperand(1).getOperand(1) &&
6463             isX86LogicalCmp(Cmp)) {
6464           CC = Cond.getOperand(0).getOperand(0);
6465           Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
6466                               Chain, Dest, CC, Cmp);
6467           CC = Cond.getOperand(1).getOperand(0);
6468           Cond = Cmp;
6469           addTest = false;
6470         }
6471       } else { // ISD::AND
6472         // Also, recognize the pattern generated by an FCMP_OEQ. We can emit
6473         // two branches instead of an explicit AND instruction with a
6474         // separate test. However, we only do this if this block doesn't
6475         // have a fall-through edge, because this requires an explicit
6476         // jmp when the condition is false.
6477         if (Cmp == Cond.getOperand(1).getOperand(1) &&
6478             isX86LogicalCmp(Cmp) &&
6479             Op.getNode()->hasOneUse()) {
6480           X86::CondCode CCode =
6481             (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
6482           CCode = X86::GetOppositeBranchCondition(CCode);
6483           CC = DAG.getConstant(CCode, MVT::i8);
6484           SDValue User = SDValue(*Op.getNode()->use_begin(), 0);
6485           // Look for an unconditional branch following this conditional branch.
6486           // We need this because we need to reverse the successors in order
6487           // to implement FCMP_OEQ.
6488           if (User.getOpcode() == ISD::BR) {
6489             SDValue FalseBB = User.getOperand(1);
6490             SDValue NewBR =
6491               DAG.UpdateNodeOperands(User, User.getOperand(0), Dest);
6492             assert(NewBR == User);
6493             Dest = FalseBB;
6494
6495             Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
6496                                 Chain, Dest, CC, Cmp);
6497             X86::CondCode CCode =
6498               (X86::CondCode)Cond.getOperand(1).getConstantOperandVal(0);
6499             CCode = X86::GetOppositeBranchCondition(CCode);
6500             CC = DAG.getConstant(CCode, MVT::i8);
6501             Cond = Cmp;
6502             addTest = false;
6503           }
6504         }
6505       }
6506     } else if (Cond.hasOneUse() && isXor1OfSetCC(Cond)) {
6507       // Recognize for xorb (setcc), 1 patterns. The xor inverts the condition.
6508       // It should be transformed during dag combiner except when the condition
6509       // is set by a arithmetics with overflow node.
6510       X86::CondCode CCode =
6511         (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
6512       CCode = X86::GetOppositeBranchCondition(CCode);
6513       CC = DAG.getConstant(CCode, MVT::i8);
6514       Cond = Cond.getOperand(0).getOperand(1);
6515       addTest = false;
6516     }
6517   }
6518
6519   if (addTest) {
6520     // Look pass the truncate.
6521     if (Cond.getOpcode() == ISD::TRUNCATE)
6522       Cond = Cond.getOperand(0);
6523
6524     // We know the result of AND is compared against zero. Try to match
6525     // it to BT.
6526     if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) { 
6527       SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, dl, DAG);
6528       if (NewSetCC.getNode()) {
6529         CC = NewSetCC.getOperand(0);
6530         Cond = NewSetCC.getOperand(1);
6531         addTest = false;
6532       }
6533     }
6534   }
6535
6536   if (addTest) {
6537     CC = DAG.getConstant(X86::COND_NE, MVT::i8);
6538     Cond = EmitTest(Cond, X86::COND_NE, DAG);
6539   }
6540   return DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
6541                      Chain, Dest, CC, Cond);
6542 }
6543
6544
6545 // Lower dynamic stack allocation to _alloca call for Cygwin/Mingw targets.
6546 // Calls to _alloca is needed to probe the stack when allocating more than 4k
6547 // bytes in one go. Touching the stack at 4K increments is necessary to ensure
6548 // that the guard pages used by the OS virtual memory manager are allocated in
6549 // correct sequence.
6550 SDValue
6551 X86TargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
6552                                            SelectionDAG &DAG) const {
6553   assert(Subtarget->isTargetCygMing() &&
6554          "This should be used only on Cygwin/Mingw targets");
6555   DebugLoc dl = Op.getDebugLoc();
6556
6557   // Get the inputs.
6558   SDValue Chain = Op.getOperand(0);
6559   SDValue Size  = Op.getOperand(1);
6560   // FIXME: Ensure alignment here
6561
6562   SDValue Flag;
6563
6564   EVT IntPtr = getPointerTy();
6565   EVT SPTy = Subtarget->is64Bit() ? MVT::i64 : MVT::i32;
6566
6567   Chain = DAG.getCopyToReg(Chain, dl, X86::EAX, Size, Flag);
6568   Flag = Chain.getValue(1);
6569
6570   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Flag);
6571
6572   Chain = DAG.getNode(X86ISD::MINGW_ALLOCA, dl, NodeTys, Chain, Flag);
6573   Flag = Chain.getValue(1);
6574
6575   Chain = DAG.getCopyFromReg(Chain, dl, X86StackPtr, SPTy).getValue(1);
6576
6577   SDValue Ops1[2] = { Chain.getValue(0), Chain };
6578   return DAG.getMergeValues(Ops1, 2, dl);
6579 }
6580
6581 SDValue
6582 X86TargetLowering::EmitTargetCodeForMemset(SelectionDAG &DAG, DebugLoc dl,
6583                                            SDValue Chain,
6584                                            SDValue Dst, SDValue Src,
6585                                            SDValue Size, unsigned Align,
6586                                            bool isVolatile,
6587                                            const Value *DstSV,
6588                                            uint64_t DstSVOff) const {
6589   ConstantSDNode *ConstantSize = dyn_cast<ConstantSDNode>(Size);
6590
6591   // If not DWORD aligned or size is more than the threshold, call the library.
6592   // The libc version is likely to be faster for these cases. It can use the
6593   // address value and run time information about the CPU.
6594   if ((Align & 3) != 0 ||
6595       !ConstantSize ||
6596       ConstantSize->getZExtValue() >
6597         getSubtarget()->getMaxInlineSizeThreshold()) {
6598     SDValue InFlag(0, 0);
6599
6600     // Check to see if there is a specialized entry-point for memory zeroing.
6601     ConstantSDNode *V = dyn_cast<ConstantSDNode>(Src);
6602
6603     if (const char *bzeroEntry =  V &&
6604         V->isNullValue() ? Subtarget->getBZeroEntry() : 0) {
6605       EVT IntPtr = getPointerTy();
6606       const Type *IntPtrTy = TD->getIntPtrType(*DAG.getContext());
6607       TargetLowering::ArgListTy Args;
6608       TargetLowering::ArgListEntry Entry;
6609       Entry.Node = Dst;
6610       Entry.Ty = IntPtrTy;
6611       Args.push_back(Entry);
6612       Entry.Node = Size;
6613       Args.push_back(Entry);
6614       std::pair<SDValue,SDValue> CallResult =
6615         LowerCallTo(Chain, Type::getVoidTy(*DAG.getContext()),
6616                     false, false, false, false,
6617                     0, CallingConv::C, false, /*isReturnValueUsed=*/false,
6618                     DAG.getExternalSymbol(bzeroEntry, IntPtr), Args, DAG, dl);
6619       return CallResult.second;
6620     }
6621
6622     // Otherwise have the target-independent code call memset.
6623     return SDValue();
6624   }
6625
6626   uint64_t SizeVal = ConstantSize->getZExtValue();
6627   SDValue InFlag(0, 0);
6628   EVT AVT;
6629   SDValue Count;
6630   ConstantSDNode *ValC = dyn_cast<ConstantSDNode>(Src);
6631   unsigned BytesLeft = 0;
6632   bool TwoRepStos = false;
6633   if (ValC) {
6634     unsigned ValReg;
6635     uint64_t Val = ValC->getZExtValue() & 255;
6636
6637     // If the value is a constant, then we can potentially use larger sets.
6638     switch (Align & 3) {
6639     case 2:   // WORD aligned
6640       AVT = MVT::i16;
6641       ValReg = X86::AX;
6642       Val = (Val << 8) | Val;
6643       break;
6644     case 0:  // DWORD aligned
6645       AVT = MVT::i32;
6646       ValReg = X86::EAX;
6647       Val = (Val << 8)  | Val;
6648       Val = (Val << 16) | Val;
6649       if (Subtarget->is64Bit() && ((Align & 0x7) == 0)) {  // QWORD aligned
6650         AVT = MVT::i64;
6651         ValReg = X86::RAX;
6652         Val = (Val << 32) | Val;
6653       }
6654       break;
6655     default:  // Byte aligned
6656       AVT = MVT::i8;
6657       ValReg = X86::AL;
6658       Count = DAG.getIntPtrConstant(SizeVal);
6659       break;
6660     }
6661
6662     if (AVT.bitsGT(MVT::i8)) {
6663       unsigned UBytes = AVT.getSizeInBits() / 8;
6664       Count = DAG.getIntPtrConstant(SizeVal / UBytes);
6665       BytesLeft = SizeVal % UBytes;
6666     }
6667
6668     Chain  = DAG.getCopyToReg(Chain, dl, ValReg, DAG.getConstant(Val, AVT),
6669                               InFlag);
6670     InFlag = Chain.getValue(1);
6671   } else {
6672     AVT = MVT::i8;
6673     Count  = DAG.getIntPtrConstant(SizeVal);
6674     Chain  = DAG.getCopyToReg(Chain, dl, X86::AL, Src, InFlag);
6675     InFlag = Chain.getValue(1);
6676   }
6677
6678   Chain  = DAG.getCopyToReg(Chain, dl, Subtarget->is64Bit() ? X86::RCX :
6679                                                               X86::ECX,
6680                             Count, InFlag);
6681   InFlag = Chain.getValue(1);
6682   Chain  = DAG.getCopyToReg(Chain, dl, Subtarget->is64Bit() ? X86::RDI :
6683                                                               X86::EDI,
6684                             Dst, InFlag);
6685   InFlag = Chain.getValue(1);
6686
6687   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Flag);
6688   SDValue Ops[] = { Chain, DAG.getValueType(AVT), InFlag };
6689   Chain = DAG.getNode(X86ISD::REP_STOS, dl, Tys, Ops, array_lengthof(Ops));
6690
6691   if (TwoRepStos) {
6692     InFlag = Chain.getValue(1);
6693     Count  = Size;
6694     EVT CVT = Count.getValueType();
6695     SDValue Left = DAG.getNode(ISD::AND, dl, CVT, Count,
6696                                DAG.getConstant((AVT == MVT::i64) ? 7 : 3, CVT));
6697     Chain  = DAG.getCopyToReg(Chain, dl, (CVT == MVT::i64) ? X86::RCX :
6698                                                              X86::ECX,
6699                               Left, InFlag);
6700     InFlag = Chain.getValue(1);
6701     Tys = DAG.getVTList(MVT::Other, MVT::Flag);
6702     SDValue Ops[] = { Chain, DAG.getValueType(MVT::i8), InFlag };
6703     Chain = DAG.getNode(X86ISD::REP_STOS, dl, Tys, Ops, array_lengthof(Ops));
6704   } else if (BytesLeft) {
6705     // Handle the last 1 - 7 bytes.
6706     unsigned Offset = SizeVal - BytesLeft;
6707     EVT AddrVT = Dst.getValueType();
6708     EVT SizeVT = Size.getValueType();
6709
6710     Chain = DAG.getMemset(Chain, dl,
6711                           DAG.getNode(ISD::ADD, dl, AddrVT, Dst,
6712                                       DAG.getConstant(Offset, AddrVT)),
6713                           Src,
6714                           DAG.getConstant(BytesLeft, SizeVT),
6715                           Align, isVolatile, DstSV, DstSVOff + Offset);
6716   }
6717
6718   // TODO: Use a Tokenfactor, as in memcpy, instead of a single chain.
6719   return Chain;
6720 }
6721
6722 SDValue
6723 X86TargetLowering::EmitTargetCodeForMemcpy(SelectionDAG &DAG, DebugLoc dl,
6724                                       SDValue Chain, SDValue Dst, SDValue Src,
6725                                       SDValue Size, unsigned Align,
6726                                       bool isVolatile, bool AlwaysInline,
6727                                       const Value *DstSV,
6728                                       uint64_t DstSVOff,
6729                                       const Value *SrcSV,
6730                                       uint64_t SrcSVOff) const {
6731   // This requires the copy size to be a constant, preferrably
6732   // within a subtarget-specific limit.
6733   ConstantSDNode *ConstantSize = dyn_cast<ConstantSDNode>(Size);
6734   if (!ConstantSize)
6735     return SDValue();
6736   uint64_t SizeVal = ConstantSize->getZExtValue();
6737   if (!AlwaysInline && SizeVal > getSubtarget()->getMaxInlineSizeThreshold())
6738     return SDValue();
6739
6740   /// If not DWORD aligned, call the library.
6741   if ((Align & 3) != 0)
6742     return SDValue();
6743
6744   // DWORD aligned
6745   EVT AVT = MVT::i32;
6746   if (Subtarget->is64Bit() && ((Align & 0x7) == 0))  // QWORD aligned
6747     AVT = MVT::i64;
6748
6749   unsigned UBytes = AVT.getSizeInBits() / 8;
6750   unsigned CountVal = SizeVal / UBytes;
6751   SDValue Count = DAG.getIntPtrConstant(CountVal);
6752   unsigned BytesLeft = SizeVal % UBytes;
6753
6754   SDValue InFlag(0, 0);
6755   Chain  = DAG.getCopyToReg(Chain, dl, Subtarget->is64Bit() ? X86::RCX :
6756                                                               X86::ECX,
6757                             Count, InFlag);
6758   InFlag = Chain.getValue(1);
6759   Chain  = DAG.getCopyToReg(Chain, dl, Subtarget->is64Bit() ? X86::RDI :
6760                                                               X86::EDI,
6761                             Dst, InFlag);
6762   InFlag = Chain.getValue(1);
6763   Chain  = DAG.getCopyToReg(Chain, dl, Subtarget->is64Bit() ? X86::RSI :
6764                                                               X86::ESI,
6765                             Src, InFlag);
6766   InFlag = Chain.getValue(1);
6767
6768   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Flag);
6769   SDValue Ops[] = { Chain, DAG.getValueType(AVT), InFlag };
6770   SDValue RepMovs = DAG.getNode(X86ISD::REP_MOVS, dl, Tys, Ops,
6771                                 array_lengthof(Ops));
6772
6773   SmallVector<SDValue, 4> Results;
6774   Results.push_back(RepMovs);
6775   if (BytesLeft) {
6776     // Handle the last 1 - 7 bytes.
6777     unsigned Offset = SizeVal - BytesLeft;
6778     EVT DstVT = Dst.getValueType();
6779     EVT SrcVT = Src.getValueType();
6780     EVT SizeVT = Size.getValueType();
6781     Results.push_back(DAG.getMemcpy(Chain, dl,
6782                                     DAG.getNode(ISD::ADD, dl, DstVT, Dst,
6783                                                 DAG.getConstant(Offset, DstVT)),
6784                                     DAG.getNode(ISD::ADD, dl, SrcVT, Src,
6785                                                 DAG.getConstant(Offset, SrcVT)),
6786                                     DAG.getConstant(BytesLeft, SizeVT),
6787                                     Align, isVolatile, AlwaysInline,
6788                                     DstSV, DstSVOff + Offset,
6789                                     SrcSV, SrcSVOff + Offset));
6790   }
6791
6792   return DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
6793                      &Results[0], Results.size());
6794 }
6795
6796 SDValue X86TargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) const {
6797   MachineFunction &MF = DAG.getMachineFunction();
6798   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
6799
6800   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
6801   DebugLoc dl = Op.getDebugLoc();
6802
6803   if (!Subtarget->is64Bit()) {
6804     // vastart just stores the address of the VarArgsFrameIndex slot into the
6805     // memory location argument.
6806     SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
6807                                    getPointerTy());
6808     return DAG.getStore(Op.getOperand(0), dl, FR, Op.getOperand(1), SV, 0,
6809                         false, false, 0);
6810   }
6811
6812   // __va_list_tag:
6813   //   gp_offset         (0 - 6 * 8)
6814   //   fp_offset         (48 - 48 + 8 * 16)
6815   //   overflow_arg_area (point to parameters coming in memory).
6816   //   reg_save_area
6817   SmallVector<SDValue, 8> MemOps;
6818   SDValue FIN = Op.getOperand(1);
6819   // Store gp_offset
6820   SDValue Store = DAG.getStore(Op.getOperand(0), dl,
6821                                DAG.getConstant(FuncInfo->getVarArgsGPOffset(),
6822                                                MVT::i32),
6823                                FIN, SV, 0, false, false, 0);
6824   MemOps.push_back(Store);
6825
6826   // Store fp_offset
6827   FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(),
6828                     FIN, DAG.getIntPtrConstant(4));
6829   Store = DAG.getStore(Op.getOperand(0), dl,
6830                        DAG.getConstant(FuncInfo->getVarArgsFPOffset(),
6831                                        MVT::i32),
6832                        FIN, SV, 0, false, false, 0);
6833   MemOps.push_back(Store);
6834
6835   // Store ptr to overflow_arg_area
6836   FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(),
6837                     FIN, DAG.getIntPtrConstant(4));
6838   SDValue OVFIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
6839                                     getPointerTy());
6840   Store = DAG.getStore(Op.getOperand(0), dl, OVFIN, FIN, SV, 0,
6841                        false, false, 0);
6842   MemOps.push_back(Store);
6843
6844   // Store ptr to reg_save_area.
6845   FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(),
6846                     FIN, DAG.getIntPtrConstant(8));
6847   SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
6848                                     getPointerTy());
6849   Store = DAG.getStore(Op.getOperand(0), dl, RSFIN, FIN, SV, 0,
6850                        false, false, 0);
6851   MemOps.push_back(Store);
6852   return DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
6853                      &MemOps[0], MemOps.size());
6854 }
6855
6856 SDValue X86TargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) const {
6857   // X86-64 va_list is a struct { i32, i32, i8*, i8* }.
6858   assert(Subtarget->is64Bit() && "This code only handles 64-bit va_arg!");
6859   SDValue Chain = Op.getOperand(0);
6860   SDValue SrcPtr = Op.getOperand(1);
6861   SDValue SrcSV = Op.getOperand(2);
6862
6863   report_fatal_error("VAArgInst is not yet implemented for x86-64!");
6864   return SDValue();
6865 }
6866
6867 SDValue X86TargetLowering::LowerVACOPY(SDValue Op, SelectionDAG &DAG) const {
6868   // X86-64 va_list is a struct { i32, i32, i8*, i8* }.
6869   assert(Subtarget->is64Bit() && "This code only handles 64-bit va_copy!");
6870   SDValue Chain = Op.getOperand(0);
6871   SDValue DstPtr = Op.getOperand(1);
6872   SDValue SrcPtr = Op.getOperand(2);
6873   const Value *DstSV = cast<SrcValueSDNode>(Op.getOperand(3))->getValue();
6874   const Value *SrcSV = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
6875   DebugLoc dl = Op.getDebugLoc();
6876
6877   return DAG.getMemcpy(Chain, dl, DstPtr, SrcPtr,
6878                        DAG.getIntPtrConstant(24), 8, /*isVolatile*/false,
6879                        false, DstSV, 0, SrcSV, 0);
6880 }
6881
6882 SDValue
6883 X86TargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op, SelectionDAG &DAG) const {
6884   DebugLoc dl = Op.getDebugLoc();
6885   unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
6886   switch (IntNo) {
6887   default: return SDValue();    // Don't custom lower most intrinsics.
6888   // Comparison intrinsics.
6889   case Intrinsic::x86_sse_comieq_ss:
6890   case Intrinsic::x86_sse_comilt_ss:
6891   case Intrinsic::x86_sse_comile_ss:
6892   case Intrinsic::x86_sse_comigt_ss:
6893   case Intrinsic::x86_sse_comige_ss:
6894   case Intrinsic::x86_sse_comineq_ss:
6895   case Intrinsic::x86_sse_ucomieq_ss:
6896   case Intrinsic::x86_sse_ucomilt_ss:
6897   case Intrinsic::x86_sse_ucomile_ss:
6898   case Intrinsic::x86_sse_ucomigt_ss:
6899   case Intrinsic::x86_sse_ucomige_ss:
6900   case Intrinsic::x86_sse_ucomineq_ss:
6901   case Intrinsic::x86_sse2_comieq_sd:
6902   case Intrinsic::x86_sse2_comilt_sd:
6903   case Intrinsic::x86_sse2_comile_sd:
6904   case Intrinsic::x86_sse2_comigt_sd:
6905   case Intrinsic::x86_sse2_comige_sd:
6906   case Intrinsic::x86_sse2_comineq_sd:
6907   case Intrinsic::x86_sse2_ucomieq_sd:
6908   case Intrinsic::x86_sse2_ucomilt_sd:
6909   case Intrinsic::x86_sse2_ucomile_sd:
6910   case Intrinsic::x86_sse2_ucomigt_sd:
6911   case Intrinsic::x86_sse2_ucomige_sd:
6912   case Intrinsic::x86_sse2_ucomineq_sd: {
6913     unsigned Opc = 0;
6914     ISD::CondCode CC = ISD::SETCC_INVALID;
6915     switch (IntNo) {
6916     default: break;
6917     case Intrinsic::x86_sse_comieq_ss:
6918     case Intrinsic::x86_sse2_comieq_sd:
6919       Opc = X86ISD::COMI;
6920       CC = ISD::SETEQ;
6921       break;
6922     case Intrinsic::x86_sse_comilt_ss:
6923     case Intrinsic::x86_sse2_comilt_sd:
6924       Opc = X86ISD::COMI;
6925       CC = ISD::SETLT;
6926       break;
6927     case Intrinsic::x86_sse_comile_ss:
6928     case Intrinsic::x86_sse2_comile_sd:
6929       Opc = X86ISD::COMI;
6930       CC = ISD::SETLE;
6931       break;
6932     case Intrinsic::x86_sse_comigt_ss:
6933     case Intrinsic::x86_sse2_comigt_sd:
6934       Opc = X86ISD::COMI;
6935       CC = ISD::SETGT;
6936       break;
6937     case Intrinsic::x86_sse_comige_ss:
6938     case Intrinsic::x86_sse2_comige_sd:
6939       Opc = X86ISD::COMI;
6940       CC = ISD::SETGE;
6941       break;
6942     case Intrinsic::x86_sse_comineq_ss:
6943     case Intrinsic::x86_sse2_comineq_sd:
6944       Opc = X86ISD::COMI;
6945       CC = ISD::SETNE;
6946       break;
6947     case Intrinsic::x86_sse_ucomieq_ss:
6948     case Intrinsic::x86_sse2_ucomieq_sd:
6949       Opc = X86ISD::UCOMI;
6950       CC = ISD::SETEQ;
6951       break;
6952     case Intrinsic::x86_sse_ucomilt_ss:
6953     case Intrinsic::x86_sse2_ucomilt_sd:
6954       Opc = X86ISD::UCOMI;
6955       CC = ISD::SETLT;
6956       break;
6957     case Intrinsic::x86_sse_ucomile_ss:
6958     case Intrinsic::x86_sse2_ucomile_sd:
6959       Opc = X86ISD::UCOMI;
6960       CC = ISD::SETLE;
6961       break;
6962     case Intrinsic::x86_sse_ucomigt_ss:
6963     case Intrinsic::x86_sse2_ucomigt_sd:
6964       Opc = X86ISD::UCOMI;
6965       CC = ISD::SETGT;
6966       break;
6967     case Intrinsic::x86_sse_ucomige_ss:
6968     case Intrinsic::x86_sse2_ucomige_sd:
6969       Opc = X86ISD::UCOMI;
6970       CC = ISD::SETGE;
6971       break;
6972     case Intrinsic::x86_sse_ucomineq_ss:
6973     case Intrinsic::x86_sse2_ucomineq_sd:
6974       Opc = X86ISD::UCOMI;
6975       CC = ISD::SETNE;
6976       break;
6977     }
6978
6979     SDValue LHS = Op.getOperand(1);
6980     SDValue RHS = Op.getOperand(2);
6981     unsigned X86CC = TranslateX86CC(CC, true, LHS, RHS, DAG);
6982     assert(X86CC != X86::COND_INVALID && "Unexpected illegal condition!");
6983     SDValue Cond = DAG.getNode(Opc, dl, MVT::i32, LHS, RHS);
6984     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
6985                                 DAG.getConstant(X86CC, MVT::i8), Cond);
6986     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
6987   }
6988   // ptest intrinsics. The intrinsic these come from are designed to return
6989   // an integer value, not just an instruction so lower it to the ptest
6990   // pattern and a setcc for the result.
6991   case Intrinsic::x86_sse41_ptestz:
6992   case Intrinsic::x86_sse41_ptestc:
6993   case Intrinsic::x86_sse41_ptestnzc:{
6994     unsigned X86CC = 0;
6995     switch (IntNo) {
6996     default: llvm_unreachable("Bad fallthrough in Intrinsic lowering.");
6997     case Intrinsic::x86_sse41_ptestz:
6998       // ZF = 1
6999       X86CC = X86::COND_E;
7000       break;
7001     case Intrinsic::x86_sse41_ptestc:
7002       // CF = 1
7003       X86CC = X86::COND_B;
7004       break;
7005     case Intrinsic::x86_sse41_ptestnzc:
7006       // ZF and CF = 0
7007       X86CC = X86::COND_A;
7008       break;
7009     }
7010
7011     SDValue LHS = Op.getOperand(1);
7012     SDValue RHS = Op.getOperand(2);
7013     SDValue Test = DAG.getNode(X86ISD::PTEST, dl, MVT::i32, LHS, RHS);
7014     SDValue CC = DAG.getConstant(X86CC, MVT::i8);
7015     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8, CC, Test);
7016     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
7017   }
7018
7019   // Fix vector shift instructions where the last operand is a non-immediate
7020   // i32 value.
7021   case Intrinsic::x86_sse2_pslli_w:
7022   case Intrinsic::x86_sse2_pslli_d:
7023   case Intrinsic::x86_sse2_pslli_q:
7024   case Intrinsic::x86_sse2_psrli_w:
7025   case Intrinsic::x86_sse2_psrli_d:
7026   case Intrinsic::x86_sse2_psrli_q:
7027   case Intrinsic::x86_sse2_psrai_w:
7028   case Intrinsic::x86_sse2_psrai_d:
7029   case Intrinsic::x86_mmx_pslli_w:
7030   case Intrinsic::x86_mmx_pslli_d:
7031   case Intrinsic::x86_mmx_pslli_q:
7032   case Intrinsic::x86_mmx_psrli_w:
7033   case Intrinsic::x86_mmx_psrli_d:
7034   case Intrinsic::x86_mmx_psrli_q:
7035   case Intrinsic::x86_mmx_psrai_w:
7036   case Intrinsic::x86_mmx_psrai_d: {
7037     SDValue ShAmt = Op.getOperand(2);
7038     if (isa<ConstantSDNode>(ShAmt))
7039       return SDValue();
7040
7041     unsigned NewIntNo = 0;
7042     EVT ShAmtVT = MVT::v4i32;
7043     switch (IntNo) {
7044     case Intrinsic::x86_sse2_pslli_w:
7045       NewIntNo = Intrinsic::x86_sse2_psll_w;
7046       break;
7047     case Intrinsic::x86_sse2_pslli_d:
7048       NewIntNo = Intrinsic::x86_sse2_psll_d;
7049       break;
7050     case Intrinsic::x86_sse2_pslli_q:
7051       NewIntNo = Intrinsic::x86_sse2_psll_q;
7052       break;
7053     case Intrinsic::x86_sse2_psrli_w:
7054       NewIntNo = Intrinsic::x86_sse2_psrl_w;
7055       break;
7056     case Intrinsic::x86_sse2_psrli_d:
7057       NewIntNo = Intrinsic::x86_sse2_psrl_d;
7058       break;
7059     case Intrinsic::x86_sse2_psrli_q:
7060       NewIntNo = Intrinsic::x86_sse2_psrl_q;
7061       break;
7062     case Intrinsic::x86_sse2_psrai_w:
7063       NewIntNo = Intrinsic::x86_sse2_psra_w;
7064       break;
7065     case Intrinsic::x86_sse2_psrai_d:
7066       NewIntNo = Intrinsic::x86_sse2_psra_d;
7067       break;
7068     default: {
7069       ShAmtVT = MVT::v2i32;
7070       switch (IntNo) {
7071       case Intrinsic::x86_mmx_pslli_w:
7072         NewIntNo = Intrinsic::x86_mmx_psll_w;
7073         break;
7074       case Intrinsic::x86_mmx_pslli_d:
7075         NewIntNo = Intrinsic::x86_mmx_psll_d;
7076         break;
7077       case Intrinsic::x86_mmx_pslli_q:
7078         NewIntNo = Intrinsic::x86_mmx_psll_q;
7079         break;
7080       case Intrinsic::x86_mmx_psrli_w:
7081         NewIntNo = Intrinsic::x86_mmx_psrl_w;
7082         break;
7083       case Intrinsic::x86_mmx_psrli_d:
7084         NewIntNo = Intrinsic::x86_mmx_psrl_d;
7085         break;
7086       case Intrinsic::x86_mmx_psrli_q:
7087         NewIntNo = Intrinsic::x86_mmx_psrl_q;
7088         break;
7089       case Intrinsic::x86_mmx_psrai_w:
7090         NewIntNo = Intrinsic::x86_mmx_psra_w;
7091         break;
7092       case Intrinsic::x86_mmx_psrai_d:
7093         NewIntNo = Intrinsic::x86_mmx_psra_d;
7094         break;
7095       default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
7096       }
7097       break;
7098     }
7099     }
7100
7101     // The vector shift intrinsics with scalars uses 32b shift amounts but
7102     // the sse2/mmx shift instructions reads 64 bits. Set the upper 32 bits
7103     // to be zero.
7104     SDValue ShOps[4];
7105     ShOps[0] = ShAmt;
7106     ShOps[1] = DAG.getConstant(0, MVT::i32);
7107     if (ShAmtVT == MVT::v4i32) {
7108       ShOps[2] = DAG.getUNDEF(MVT::i32);
7109       ShOps[3] = DAG.getUNDEF(MVT::i32);
7110       ShAmt =  DAG.getNode(ISD::BUILD_VECTOR, dl, ShAmtVT, &ShOps[0], 4);
7111     } else {
7112       ShAmt =  DAG.getNode(ISD::BUILD_VECTOR, dl, ShAmtVT, &ShOps[0], 2);
7113     }
7114
7115     EVT VT = Op.getValueType();
7116     ShAmt = DAG.getNode(ISD::BIT_CONVERT, dl, VT, ShAmt);
7117     return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
7118                        DAG.getConstant(NewIntNo, MVT::i32),
7119                        Op.getOperand(1), ShAmt);
7120   }
7121   }
7122 }
7123
7124 SDValue X86TargetLowering::LowerRETURNADDR(SDValue Op,
7125                                            SelectionDAG &DAG) const {
7126   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
7127   DebugLoc dl = Op.getDebugLoc();
7128
7129   if (Depth > 0) {
7130     SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
7131     SDValue Offset =
7132       DAG.getConstant(TD->getPointerSize(),
7133                       Subtarget->is64Bit() ? MVT::i64 : MVT::i32);
7134     return DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(),
7135                        DAG.getNode(ISD::ADD, dl, getPointerTy(),
7136                                    FrameAddr, Offset),
7137                        NULL, 0, false, false, 0);
7138   }
7139
7140   // Just load the return address.
7141   SDValue RetAddrFI = getReturnAddressFrameIndex(DAG);
7142   return DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(),
7143                      RetAddrFI, NULL, 0, false, false, 0);
7144 }
7145
7146 SDValue X86TargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
7147   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
7148   MFI->setFrameAddressIsTaken(true);
7149   EVT VT = Op.getValueType();
7150   DebugLoc dl = Op.getDebugLoc();  // FIXME probably not meaningful
7151   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
7152   unsigned FrameReg = Subtarget->is64Bit() ? X86::RBP : X86::EBP;
7153   SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
7154   while (Depth--)
7155     FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr, NULL, 0,
7156                             false, false, 0);
7157   return FrameAddr;
7158 }
7159
7160 SDValue X86TargetLowering::LowerFRAME_TO_ARGS_OFFSET(SDValue Op,
7161                                                      SelectionDAG &DAG) const {
7162   return DAG.getIntPtrConstant(2*TD->getPointerSize());
7163 }
7164
7165 SDValue X86TargetLowering::LowerEH_RETURN(SDValue Op, SelectionDAG &DAG) const {
7166   MachineFunction &MF = DAG.getMachineFunction();
7167   SDValue Chain     = Op.getOperand(0);
7168   SDValue Offset    = Op.getOperand(1);
7169   SDValue Handler   = Op.getOperand(2);
7170   DebugLoc dl       = Op.getDebugLoc();
7171
7172   SDValue Frame = DAG.getRegister(Subtarget->is64Bit() ? X86::RBP : X86::EBP,
7173                                   getPointerTy());
7174   unsigned StoreAddrReg = (Subtarget->is64Bit() ? X86::RCX : X86::ECX);
7175
7176   SDValue StoreAddr = DAG.getNode(ISD::SUB, dl, getPointerTy(), Frame,
7177                                   DAG.getIntPtrConstant(-TD->getPointerSize()));
7178   StoreAddr = DAG.getNode(ISD::ADD, dl, getPointerTy(), StoreAddr, Offset);
7179   Chain = DAG.getStore(Chain, dl, Handler, StoreAddr, NULL, 0, false, false, 0);
7180   Chain = DAG.getCopyToReg(Chain, dl, StoreAddrReg, StoreAddr);
7181   MF.getRegInfo().addLiveOut(StoreAddrReg);
7182
7183   return DAG.getNode(X86ISD::EH_RETURN, dl,
7184                      MVT::Other,
7185                      Chain, DAG.getRegister(StoreAddrReg, getPointerTy()));
7186 }
7187
7188 SDValue X86TargetLowering::LowerTRAMPOLINE(SDValue Op,
7189                                              SelectionDAG &DAG) const {
7190   SDValue Root = Op.getOperand(0);
7191   SDValue Trmp = Op.getOperand(1); // trampoline
7192   SDValue FPtr = Op.getOperand(2); // nested function
7193   SDValue Nest = Op.getOperand(3); // 'nest' parameter value
7194   DebugLoc dl  = Op.getDebugLoc();
7195
7196   const Value *TrmpAddr = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
7197
7198   if (Subtarget->is64Bit()) {
7199     SDValue OutChains[6];
7200
7201     // Large code-model.
7202     const unsigned char JMP64r  = 0xFF; // 64-bit jmp through register opcode.
7203     const unsigned char MOV64ri = 0xB8; // X86::MOV64ri opcode.
7204
7205     const unsigned char N86R10 = RegInfo->getX86RegNum(X86::R10);
7206     const unsigned char N86R11 = RegInfo->getX86RegNum(X86::R11);
7207
7208     const unsigned char REX_WB = 0x40 | 0x08 | 0x01; // REX prefix
7209
7210     // Load the pointer to the nested function into R11.
7211     unsigned OpCode = ((MOV64ri | N86R11) << 8) | REX_WB; // movabsq r11
7212     SDValue Addr = Trmp;
7213     OutChains[0] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
7214                                 Addr, TrmpAddr, 0, false, false, 0);
7215
7216     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
7217                        DAG.getConstant(2, MVT::i64));
7218     OutChains[1] = DAG.getStore(Root, dl, FPtr, Addr, TrmpAddr, 2,
7219                                 false, false, 2);
7220
7221     // Load the 'nest' parameter value into R10.
7222     // R10 is specified in X86CallingConv.td
7223     OpCode = ((MOV64ri | N86R10) << 8) | REX_WB; // movabsq r10
7224     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
7225                        DAG.getConstant(10, MVT::i64));
7226     OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
7227                                 Addr, TrmpAddr, 10, false, false, 0);
7228
7229     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
7230                        DAG.getConstant(12, MVT::i64));
7231     OutChains[3] = DAG.getStore(Root, dl, Nest, Addr, TrmpAddr, 12,
7232                                 false, false, 2);
7233
7234     // Jump to the nested function.
7235     OpCode = (JMP64r << 8) | REX_WB; // jmpq *...
7236     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
7237                        DAG.getConstant(20, MVT::i64));
7238     OutChains[4] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
7239                                 Addr, TrmpAddr, 20, false, false, 0);
7240
7241     unsigned char ModRM = N86R11 | (4 << 3) | (3 << 6); // ...r11
7242     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
7243                        DAG.getConstant(22, MVT::i64));
7244     OutChains[5] = DAG.getStore(Root, dl, DAG.getConstant(ModRM, MVT::i8), Addr,
7245                                 TrmpAddr, 22, false, false, 0);
7246
7247     SDValue Ops[] =
7248       { Trmp, DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains, 6) };
7249     return DAG.getMergeValues(Ops, 2, dl);
7250   } else {
7251     const Function *Func =
7252       cast<Function>(cast<SrcValueSDNode>(Op.getOperand(5))->getValue());
7253     CallingConv::ID CC = Func->getCallingConv();
7254     unsigned NestReg;
7255
7256     switch (CC) {
7257     default:
7258       llvm_unreachable("Unsupported calling convention");
7259     case CallingConv::C:
7260     case CallingConv::X86_StdCall: {
7261       // Pass 'nest' parameter in ECX.
7262       // Must be kept in sync with X86CallingConv.td
7263       NestReg = X86::ECX;
7264
7265       // Check that ECX wasn't needed by an 'inreg' parameter.
7266       const FunctionType *FTy = Func->getFunctionType();
7267       const AttrListPtr &Attrs = Func->getAttributes();
7268
7269       if (!Attrs.isEmpty() && !Func->isVarArg()) {
7270         unsigned InRegCount = 0;
7271         unsigned Idx = 1;
7272
7273         for (FunctionType::param_iterator I = FTy->param_begin(),
7274              E = FTy->param_end(); I != E; ++I, ++Idx)
7275           if (Attrs.paramHasAttr(Idx, Attribute::InReg))
7276             // FIXME: should only count parameters that are lowered to integers.
7277             InRegCount += (TD->getTypeSizeInBits(*I) + 31) / 32;
7278
7279         if (InRegCount > 2) {
7280           report_fatal_error("Nest register in use - reduce number of inreg parameters!");
7281         }
7282       }
7283       break;
7284     }
7285     case CallingConv::X86_FastCall:
7286     case CallingConv::Fast:
7287       // Pass 'nest' parameter in EAX.
7288       // Must be kept in sync with X86CallingConv.td
7289       NestReg = X86::EAX;
7290       break;
7291     }
7292
7293     SDValue OutChains[4];
7294     SDValue Addr, Disp;
7295
7296     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
7297                        DAG.getConstant(10, MVT::i32));
7298     Disp = DAG.getNode(ISD::SUB, dl, MVT::i32, FPtr, Addr);
7299
7300     // This is storing the opcode for MOV32ri.
7301     const unsigned char MOV32ri = 0xB8; // X86::MOV32ri's opcode byte.
7302     const unsigned char N86Reg = RegInfo->getX86RegNum(NestReg);
7303     OutChains[0] = DAG.getStore(Root, dl,
7304                                 DAG.getConstant(MOV32ri|N86Reg, MVT::i8),
7305                                 Trmp, TrmpAddr, 0, false, false, 0);
7306
7307     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
7308                        DAG.getConstant(1, MVT::i32));
7309     OutChains[1] = DAG.getStore(Root, dl, Nest, Addr, TrmpAddr, 1,
7310                                 false, false, 1);
7311
7312     const unsigned char JMP = 0xE9; // jmp <32bit dst> opcode.
7313     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
7314                        DAG.getConstant(5, MVT::i32));
7315     OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(JMP, MVT::i8), Addr,
7316                                 TrmpAddr, 5, false, false, 1);
7317
7318     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
7319                        DAG.getConstant(6, MVT::i32));
7320     OutChains[3] = DAG.getStore(Root, dl, Disp, Addr, TrmpAddr, 6,
7321                                 false, false, 1);
7322
7323     SDValue Ops[] =
7324       { Trmp, DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains, 4) };
7325     return DAG.getMergeValues(Ops, 2, dl);
7326   }
7327 }
7328
7329 SDValue X86TargetLowering::LowerFLT_ROUNDS_(SDValue Op,
7330                                             SelectionDAG &DAG) const {
7331   /*
7332    The rounding mode is in bits 11:10 of FPSR, and has the following
7333    settings:
7334      00 Round to nearest
7335      01 Round to -inf
7336      10 Round to +inf
7337      11 Round to 0
7338
7339   FLT_ROUNDS, on the other hand, expects the following:
7340     -1 Undefined
7341      0 Round to 0
7342      1 Round to nearest
7343      2 Round to +inf
7344      3 Round to -inf
7345
7346   To perform the conversion, we do:
7347     (((((FPSR & 0x800) >> 11) | ((FPSR & 0x400) >> 9)) + 1) & 3)
7348   */
7349
7350   MachineFunction &MF = DAG.getMachineFunction();
7351   const TargetMachine &TM = MF.getTarget();
7352   const TargetFrameInfo &TFI = *TM.getFrameInfo();
7353   unsigned StackAlignment = TFI.getStackAlignment();
7354   EVT VT = Op.getValueType();
7355   DebugLoc dl = Op.getDebugLoc();
7356
7357   // Save FP Control Word to stack slot
7358   int SSFI = MF.getFrameInfo()->CreateStackObject(2, StackAlignment, false);
7359   SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
7360
7361   SDValue Chain = DAG.getNode(X86ISD::FNSTCW16m, dl, MVT::Other,
7362                               DAG.getEntryNode(), StackSlot);
7363
7364   // Load FP Control Word from stack slot
7365   SDValue CWD = DAG.getLoad(MVT::i16, dl, Chain, StackSlot, NULL, 0,
7366                             false, false, 0);
7367
7368   // Transform as necessary
7369   SDValue CWD1 =
7370     DAG.getNode(ISD::SRL, dl, MVT::i16,
7371                 DAG.getNode(ISD::AND, dl, MVT::i16,
7372                             CWD, DAG.getConstant(0x800, MVT::i16)),
7373                 DAG.getConstant(11, MVT::i8));
7374   SDValue CWD2 =
7375     DAG.getNode(ISD::SRL, dl, MVT::i16,
7376                 DAG.getNode(ISD::AND, dl, MVT::i16,
7377                             CWD, DAG.getConstant(0x400, MVT::i16)),
7378                 DAG.getConstant(9, MVT::i8));
7379
7380   SDValue RetVal =
7381     DAG.getNode(ISD::AND, dl, MVT::i16,
7382                 DAG.getNode(ISD::ADD, dl, MVT::i16,
7383                             DAG.getNode(ISD::OR, dl, MVT::i16, CWD1, CWD2),
7384                             DAG.getConstant(1, MVT::i16)),
7385                 DAG.getConstant(3, MVT::i16));
7386
7387
7388   return DAG.getNode((VT.getSizeInBits() < 16 ?
7389                       ISD::TRUNCATE : ISD::ZERO_EXTEND), dl, VT, RetVal);
7390 }
7391
7392 SDValue X86TargetLowering::LowerCTLZ(SDValue Op, SelectionDAG &DAG) const {
7393   EVT VT = Op.getValueType();
7394   EVT OpVT = VT;
7395   unsigned NumBits = VT.getSizeInBits();
7396   DebugLoc dl = Op.getDebugLoc();
7397
7398   Op = Op.getOperand(0);
7399   if (VT == MVT::i8) {
7400     // Zero extend to i32 since there is not an i8 bsr.
7401     OpVT = MVT::i32;
7402     Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
7403   }
7404
7405   // Issue a bsr (scan bits in reverse) which also sets EFLAGS.
7406   SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
7407   Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
7408
7409   // If src is zero (i.e. bsr sets ZF), returns NumBits.
7410   SDValue Ops[] = {
7411     Op,
7412     DAG.getConstant(NumBits+NumBits-1, OpVT),
7413     DAG.getConstant(X86::COND_E, MVT::i8),
7414     Op.getValue(1)
7415   };
7416   Op = DAG.getNode(X86ISD::CMOV, dl, OpVT, Ops, array_lengthof(Ops));
7417
7418   // Finally xor with NumBits-1.
7419   Op = DAG.getNode(ISD::XOR, dl, OpVT, Op, DAG.getConstant(NumBits-1, OpVT));
7420
7421   if (VT == MVT::i8)
7422     Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
7423   return Op;
7424 }
7425
7426 SDValue X86TargetLowering::LowerCTTZ(SDValue Op, SelectionDAG &DAG) const {
7427   EVT VT = Op.getValueType();
7428   EVT OpVT = VT;
7429   unsigned NumBits = VT.getSizeInBits();
7430   DebugLoc dl = Op.getDebugLoc();
7431
7432   Op = Op.getOperand(0);
7433   if (VT == MVT::i8) {
7434     OpVT = MVT::i32;
7435     Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
7436   }
7437
7438   // Issue a bsf (scan bits forward) which also sets EFLAGS.
7439   SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
7440   Op = DAG.getNode(X86ISD::BSF, dl, VTs, Op);
7441
7442   // If src is zero (i.e. bsf sets ZF), returns NumBits.
7443   SDValue Ops[] = {
7444     Op,
7445     DAG.getConstant(NumBits, OpVT),
7446     DAG.getConstant(X86::COND_E, MVT::i8),
7447     Op.getValue(1)
7448   };
7449   Op = DAG.getNode(X86ISD::CMOV, dl, OpVT, Ops, array_lengthof(Ops));
7450
7451   if (VT == MVT::i8)
7452     Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
7453   return Op;
7454 }
7455
7456 SDValue X86TargetLowering::LowerMUL_V2I64(SDValue Op, SelectionDAG &DAG) const {
7457   EVT VT = Op.getValueType();
7458   assert(VT == MVT::v2i64 && "Only know how to lower V2I64 multiply");
7459   DebugLoc dl = Op.getDebugLoc();
7460
7461   //  ulong2 Ahi = __builtin_ia32_psrlqi128( a, 32);
7462   //  ulong2 Bhi = __builtin_ia32_psrlqi128( b, 32);
7463   //  ulong2 AloBlo = __builtin_ia32_pmuludq128( a, b );
7464   //  ulong2 AloBhi = __builtin_ia32_pmuludq128( a, Bhi );
7465   //  ulong2 AhiBlo = __builtin_ia32_pmuludq128( Ahi, b );
7466   //
7467   //  AloBhi = __builtin_ia32_psllqi128( AloBhi, 32 );
7468   //  AhiBlo = __builtin_ia32_psllqi128( AhiBlo, 32 );
7469   //  return AloBlo + AloBhi + AhiBlo;
7470
7471   SDValue A = Op.getOperand(0);
7472   SDValue B = Op.getOperand(1);
7473
7474   SDValue Ahi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
7475                        DAG.getConstant(Intrinsic::x86_sse2_psrli_q, MVT::i32),
7476                        A, DAG.getConstant(32, MVT::i32));
7477   SDValue Bhi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
7478                        DAG.getConstant(Intrinsic::x86_sse2_psrli_q, MVT::i32),
7479                        B, DAG.getConstant(32, MVT::i32));
7480   SDValue AloBlo = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
7481                        DAG.getConstant(Intrinsic::x86_sse2_pmulu_dq, MVT::i32),
7482                        A, B);
7483   SDValue AloBhi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
7484                        DAG.getConstant(Intrinsic::x86_sse2_pmulu_dq, MVT::i32),
7485                        A, Bhi);
7486   SDValue AhiBlo = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
7487                        DAG.getConstant(Intrinsic::x86_sse2_pmulu_dq, MVT::i32),
7488                        Ahi, B);
7489   AloBhi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
7490                        DAG.getConstant(Intrinsic::x86_sse2_pslli_q, MVT::i32),
7491                        AloBhi, DAG.getConstant(32, MVT::i32));
7492   AhiBlo = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
7493                        DAG.getConstant(Intrinsic::x86_sse2_pslli_q, MVT::i32),
7494                        AhiBlo, DAG.getConstant(32, MVT::i32));
7495   SDValue Res = DAG.getNode(ISD::ADD, dl, VT, AloBlo, AloBhi);
7496   Res = DAG.getNode(ISD::ADD, dl, VT, Res, AhiBlo);
7497   return Res;
7498 }
7499
7500
7501 SDValue X86TargetLowering::LowerXALUO(SDValue Op, SelectionDAG &DAG) const {
7502   // Lower the "add/sub/mul with overflow" instruction into a regular ins plus
7503   // a "setcc" instruction that checks the overflow flag. The "brcond" lowering
7504   // looks for this combo and may remove the "setcc" instruction if the "setcc"
7505   // has only one use.
7506   SDNode *N = Op.getNode();
7507   SDValue LHS = N->getOperand(0);
7508   SDValue RHS = N->getOperand(1);
7509   unsigned BaseOp = 0;
7510   unsigned Cond = 0;
7511   DebugLoc dl = Op.getDebugLoc();
7512
7513   switch (Op.getOpcode()) {
7514   default: llvm_unreachable("Unknown ovf instruction!");
7515   case ISD::SADDO:
7516     // A subtract of one will be selected as a INC. Note that INC doesn't
7517     // set CF, so we can't do this for UADDO.
7518     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op))
7519       if (C->getAPIntValue() == 1) {
7520         BaseOp = X86ISD::INC;
7521         Cond = X86::COND_O;
7522         break;
7523       }
7524     BaseOp = X86ISD::ADD;
7525     Cond = X86::COND_O;
7526     break;
7527   case ISD::UADDO:
7528     BaseOp = X86ISD::ADD;
7529     Cond = X86::COND_B;
7530     break;
7531   case ISD::SSUBO:
7532     // A subtract of one will be selected as a DEC. Note that DEC doesn't
7533     // set CF, so we can't do this for USUBO.
7534     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op))
7535       if (C->getAPIntValue() == 1) {
7536         BaseOp = X86ISD::DEC;
7537         Cond = X86::COND_O;
7538         break;
7539       }
7540     BaseOp = X86ISD::SUB;
7541     Cond = X86::COND_O;
7542     break;
7543   case ISD::USUBO:
7544     BaseOp = X86ISD::SUB;
7545     Cond = X86::COND_B;
7546     break;
7547   case ISD::SMULO:
7548     BaseOp = X86ISD::SMUL;
7549     Cond = X86::COND_O;
7550     break;
7551   case ISD::UMULO:
7552     BaseOp = X86ISD::UMUL;
7553     Cond = X86::COND_B;
7554     break;
7555   }
7556
7557   // Also sets EFLAGS.
7558   SDVTList VTs = DAG.getVTList(N->getValueType(0), MVT::i32);
7559   SDValue Sum = DAG.getNode(BaseOp, dl, VTs, LHS, RHS);
7560
7561   SDValue SetCC =
7562     DAG.getNode(X86ISD::SETCC, dl, N->getValueType(1),
7563                 DAG.getConstant(Cond, MVT::i32), SDValue(Sum.getNode(), 1));
7564
7565   DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), SetCC);
7566   return Sum;
7567 }
7568
7569 SDValue X86TargetLowering::LowerCMP_SWAP(SDValue Op, SelectionDAG &DAG) const {
7570   EVT T = Op.getValueType();
7571   DebugLoc dl = Op.getDebugLoc();
7572   unsigned Reg = 0;
7573   unsigned size = 0;
7574   switch(T.getSimpleVT().SimpleTy) {
7575   default:
7576     assert(false && "Invalid value type!");
7577   case MVT::i8:  Reg = X86::AL;  size = 1; break;
7578   case MVT::i16: Reg = X86::AX;  size = 2; break;
7579   case MVT::i32: Reg = X86::EAX; size = 4; break;
7580   case MVT::i64:
7581     assert(Subtarget->is64Bit() && "Node not type legal!");
7582     Reg = X86::RAX; size = 8;
7583     break;
7584   }
7585   SDValue cpIn = DAG.getCopyToReg(Op.getOperand(0), dl, Reg,
7586                                     Op.getOperand(2), SDValue());
7587   SDValue Ops[] = { cpIn.getValue(0),
7588                     Op.getOperand(1),
7589                     Op.getOperand(3),
7590                     DAG.getTargetConstant(size, MVT::i8),
7591                     cpIn.getValue(1) };
7592   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Flag);
7593   SDValue Result = DAG.getNode(X86ISD::LCMPXCHG_DAG, dl, Tys, Ops, 5);
7594   SDValue cpOut =
7595     DAG.getCopyFromReg(Result.getValue(0), dl, Reg, T, Result.getValue(1));
7596   return cpOut;
7597 }
7598
7599 SDValue X86TargetLowering::LowerREADCYCLECOUNTER(SDValue Op,
7600                                                  SelectionDAG &DAG) const {
7601   assert(Subtarget->is64Bit() && "Result not type legalized?");
7602   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Flag);
7603   SDValue TheChain = Op.getOperand(0);
7604   DebugLoc dl = Op.getDebugLoc();
7605   SDValue rd = DAG.getNode(X86ISD::RDTSC_DAG, dl, Tys, &TheChain, 1);
7606   SDValue rax = DAG.getCopyFromReg(rd, dl, X86::RAX, MVT::i64, rd.getValue(1));
7607   SDValue rdx = DAG.getCopyFromReg(rax.getValue(1), dl, X86::RDX, MVT::i64,
7608                                    rax.getValue(2));
7609   SDValue Tmp = DAG.getNode(ISD::SHL, dl, MVT::i64, rdx,
7610                             DAG.getConstant(32, MVT::i8));
7611   SDValue Ops[] = {
7612     DAG.getNode(ISD::OR, dl, MVT::i64, rax, Tmp),
7613     rdx.getValue(1)
7614   };
7615   return DAG.getMergeValues(Ops, 2, dl);
7616 }
7617
7618 SDValue X86TargetLowering::LowerLOAD_SUB(SDValue Op, SelectionDAG &DAG) const {
7619   SDNode *Node = Op.getNode();
7620   DebugLoc dl = Node->getDebugLoc();
7621   EVT T = Node->getValueType(0);
7622   SDValue negOp = DAG.getNode(ISD::SUB, dl, T,
7623                               DAG.getConstant(0, T), Node->getOperand(2));
7624   return DAG.getAtomic(ISD::ATOMIC_LOAD_ADD, dl,
7625                        cast<AtomicSDNode>(Node)->getMemoryVT(),
7626                        Node->getOperand(0),
7627                        Node->getOperand(1), negOp,
7628                        cast<AtomicSDNode>(Node)->getSrcValue(),
7629                        cast<AtomicSDNode>(Node)->getAlignment());
7630 }
7631
7632 /// LowerOperation - Provide custom lowering hooks for some operations.
7633 ///
7634 SDValue X86TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
7635   switch (Op.getOpcode()) {
7636   default: llvm_unreachable("Should not custom lower this!");
7637   case ISD::ATOMIC_CMP_SWAP:    return LowerCMP_SWAP(Op,DAG);
7638   case ISD::ATOMIC_LOAD_SUB:    return LowerLOAD_SUB(Op,DAG);
7639   case ISD::BUILD_VECTOR:       return LowerBUILD_VECTOR(Op, DAG);
7640   case ISD::CONCAT_VECTORS:     return LowerCONCAT_VECTORS(Op, DAG);
7641   case ISD::VECTOR_SHUFFLE:     return LowerVECTOR_SHUFFLE(Op, DAG);
7642   case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
7643   case ISD::INSERT_VECTOR_ELT:  return LowerINSERT_VECTOR_ELT(Op, DAG);
7644   case ISD::SCALAR_TO_VECTOR:   return LowerSCALAR_TO_VECTOR(Op, DAG);
7645   case ISD::ConstantPool:       return LowerConstantPool(Op, DAG);
7646   case ISD::GlobalAddress:      return LowerGlobalAddress(Op, DAG);
7647   case ISD::GlobalTLSAddress:   return LowerGlobalTLSAddress(Op, DAG);
7648   case ISD::ExternalSymbol:     return LowerExternalSymbol(Op, DAG);
7649   case ISD::BlockAddress:       return LowerBlockAddress(Op, DAG);
7650   case ISD::SHL_PARTS:
7651   case ISD::SRA_PARTS:
7652   case ISD::SRL_PARTS:          return LowerShift(Op, DAG);
7653   case ISD::SINT_TO_FP:         return LowerSINT_TO_FP(Op, DAG);
7654   case ISD::UINT_TO_FP:         return LowerUINT_TO_FP(Op, DAG);
7655   case ISD::FP_TO_SINT:         return LowerFP_TO_SINT(Op, DAG);
7656   case ISD::FP_TO_UINT:         return LowerFP_TO_UINT(Op, DAG);
7657   case ISD::FABS:               return LowerFABS(Op, DAG);
7658   case ISD::FNEG:               return LowerFNEG(Op, DAG);
7659   case ISD::FCOPYSIGN:          return LowerFCOPYSIGN(Op, DAG);
7660   case ISD::SETCC:              return LowerSETCC(Op, DAG);
7661   case ISD::VSETCC:             return LowerVSETCC(Op, DAG);
7662   case ISD::SELECT:             return LowerSELECT(Op, DAG);
7663   case ISD::BRCOND:             return LowerBRCOND(Op, DAG);
7664   case ISD::JumpTable:          return LowerJumpTable(Op, DAG);
7665   case ISD::VASTART:            return LowerVASTART(Op, DAG);
7666   case ISD::VAARG:              return LowerVAARG(Op, DAG);
7667   case ISD::VACOPY:             return LowerVACOPY(Op, DAG);
7668   case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
7669   case ISD::RETURNADDR:         return LowerRETURNADDR(Op, DAG);
7670   case ISD::FRAMEADDR:          return LowerFRAMEADDR(Op, DAG);
7671   case ISD::FRAME_TO_ARGS_OFFSET:
7672                                 return LowerFRAME_TO_ARGS_OFFSET(Op, DAG);
7673   case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG);
7674   case ISD::EH_RETURN:          return LowerEH_RETURN(Op, DAG);
7675   case ISD::TRAMPOLINE:         return LowerTRAMPOLINE(Op, DAG);
7676   case ISD::FLT_ROUNDS_:        return LowerFLT_ROUNDS_(Op, DAG);
7677   case ISD::CTLZ:               return LowerCTLZ(Op, DAG);
7678   case ISD::CTTZ:               return LowerCTTZ(Op, DAG);
7679   case ISD::MUL:                return LowerMUL_V2I64(Op, DAG);
7680   case ISD::SADDO:
7681   case ISD::UADDO:
7682   case ISD::SSUBO:
7683   case ISD::USUBO:
7684   case ISD::SMULO:
7685   case ISD::UMULO:              return LowerXALUO(Op, DAG);
7686   case ISD::READCYCLECOUNTER:   return LowerREADCYCLECOUNTER(Op, DAG);
7687   }
7688 }
7689
7690 void X86TargetLowering::
7691 ReplaceATOMIC_BINARY_64(SDNode *Node, SmallVectorImpl<SDValue>&Results,
7692                         SelectionDAG &DAG, unsigned NewOp) const {
7693   EVT T = Node->getValueType(0);
7694   DebugLoc dl = Node->getDebugLoc();
7695   assert (T == MVT::i64 && "Only know how to expand i64 atomics");
7696
7697   SDValue Chain = Node->getOperand(0);
7698   SDValue In1 = Node->getOperand(1);
7699   SDValue In2L = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
7700                              Node->getOperand(2), DAG.getIntPtrConstant(0));
7701   SDValue In2H = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
7702                              Node->getOperand(2), DAG.getIntPtrConstant(1));
7703   SDValue Ops[] = { Chain, In1, In2L, In2H };
7704   SDVTList Tys = DAG.getVTList(MVT::i32, MVT::i32, MVT::Other);
7705   SDValue Result =
7706     DAG.getMemIntrinsicNode(NewOp, dl, Tys, Ops, 4, MVT::i64,
7707                             cast<MemSDNode>(Node)->getMemOperand());
7708   SDValue OpsF[] = { Result.getValue(0), Result.getValue(1)};
7709   Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, OpsF, 2));
7710   Results.push_back(Result.getValue(2));
7711 }
7712
7713 /// ReplaceNodeResults - Replace a node with an illegal result type
7714 /// with a new node built out of custom code.
7715 void X86TargetLowering::ReplaceNodeResults(SDNode *N,
7716                                            SmallVectorImpl<SDValue>&Results,
7717                                            SelectionDAG &DAG) const {
7718   DebugLoc dl = N->getDebugLoc();
7719   switch (N->getOpcode()) {
7720   default:
7721     assert(false && "Do not know how to custom type legalize this operation!");
7722     return;
7723   case ISD::FP_TO_SINT: {
7724     std::pair<SDValue,SDValue> Vals =
7725         FP_TO_INTHelper(SDValue(N, 0), DAG, true);
7726     SDValue FIST = Vals.first, StackSlot = Vals.second;
7727     if (FIST.getNode() != 0) {
7728       EVT VT = N->getValueType(0);
7729       // Return a load from the stack slot.
7730       Results.push_back(DAG.getLoad(VT, dl, FIST, StackSlot, NULL, 0,
7731                                     false, false, 0));
7732     }
7733     return;
7734   }
7735   case ISD::READCYCLECOUNTER: {
7736     SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Flag);
7737     SDValue TheChain = N->getOperand(0);
7738     SDValue rd = DAG.getNode(X86ISD::RDTSC_DAG, dl, Tys, &TheChain, 1);
7739     SDValue eax = DAG.getCopyFromReg(rd, dl, X86::EAX, MVT::i32,
7740                                      rd.getValue(1));
7741     SDValue edx = DAG.getCopyFromReg(eax.getValue(1), dl, X86::EDX, MVT::i32,
7742                                      eax.getValue(2));
7743     // Use a buildpair to merge the two 32-bit values into a 64-bit one.
7744     SDValue Ops[] = { eax, edx };
7745     Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Ops, 2));
7746     Results.push_back(edx.getValue(1));
7747     return;
7748   }
7749   case ISD::ATOMIC_CMP_SWAP: {
7750     EVT T = N->getValueType(0);
7751     assert (T == MVT::i64 && "Only know how to expand i64 Cmp and Swap");
7752     SDValue cpInL, cpInH;
7753     cpInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(2),
7754                         DAG.getConstant(0, MVT::i32));
7755     cpInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(2),
7756                         DAG.getConstant(1, MVT::i32));
7757     cpInL = DAG.getCopyToReg(N->getOperand(0), dl, X86::EAX, cpInL, SDValue());
7758     cpInH = DAG.getCopyToReg(cpInL.getValue(0), dl, X86::EDX, cpInH,
7759                              cpInL.getValue(1));
7760     SDValue swapInL, swapInH;
7761     swapInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(3),
7762                           DAG.getConstant(0, MVT::i32));
7763     swapInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(3),
7764                           DAG.getConstant(1, MVT::i32));
7765     swapInL = DAG.getCopyToReg(cpInH.getValue(0), dl, X86::EBX, swapInL,
7766                                cpInH.getValue(1));
7767     swapInH = DAG.getCopyToReg(swapInL.getValue(0), dl, X86::ECX, swapInH,
7768                                swapInL.getValue(1));
7769     SDValue Ops[] = { swapInH.getValue(0),
7770                       N->getOperand(1),
7771                       swapInH.getValue(1) };
7772     SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Flag);
7773     SDValue Result = DAG.getNode(X86ISD::LCMPXCHG8_DAG, dl, Tys, Ops, 3);
7774     SDValue cpOutL = DAG.getCopyFromReg(Result.getValue(0), dl, X86::EAX,
7775                                         MVT::i32, Result.getValue(1));
7776     SDValue cpOutH = DAG.getCopyFromReg(cpOutL.getValue(1), dl, X86::EDX,
7777                                         MVT::i32, cpOutL.getValue(2));
7778     SDValue OpsF[] = { cpOutL.getValue(0), cpOutH.getValue(0)};
7779     Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, OpsF, 2));
7780     Results.push_back(cpOutH.getValue(1));
7781     return;
7782   }
7783   case ISD::ATOMIC_LOAD_ADD:
7784     ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMADD64_DAG);
7785     return;
7786   case ISD::ATOMIC_LOAD_AND:
7787     ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMAND64_DAG);
7788     return;
7789   case ISD::ATOMIC_LOAD_NAND:
7790     ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMNAND64_DAG);
7791     return;
7792   case ISD::ATOMIC_LOAD_OR:
7793     ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMOR64_DAG);
7794     return;
7795   case ISD::ATOMIC_LOAD_SUB:
7796     ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMSUB64_DAG);
7797     return;
7798   case ISD::ATOMIC_LOAD_XOR:
7799     ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMXOR64_DAG);
7800     return;
7801   case ISD::ATOMIC_SWAP:
7802     ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMSWAP64_DAG);
7803     return;
7804   }
7805 }
7806
7807 const char *X86TargetLowering::getTargetNodeName(unsigned Opcode) const {
7808   switch (Opcode) {
7809   default: return NULL;
7810   case X86ISD::BSF:                return "X86ISD::BSF";
7811   case X86ISD::BSR:                return "X86ISD::BSR";
7812   case X86ISD::SHLD:               return "X86ISD::SHLD";
7813   case X86ISD::SHRD:               return "X86ISD::SHRD";
7814   case X86ISD::FAND:               return "X86ISD::FAND";
7815   case X86ISD::FOR:                return "X86ISD::FOR";
7816   case X86ISD::FXOR:               return "X86ISD::FXOR";
7817   case X86ISD::FSRL:               return "X86ISD::FSRL";
7818   case X86ISD::FILD:               return "X86ISD::FILD";
7819   case X86ISD::FILD_FLAG:          return "X86ISD::FILD_FLAG";
7820   case X86ISD::FP_TO_INT16_IN_MEM: return "X86ISD::FP_TO_INT16_IN_MEM";
7821   case X86ISD::FP_TO_INT32_IN_MEM: return "X86ISD::FP_TO_INT32_IN_MEM";
7822   case X86ISD::FP_TO_INT64_IN_MEM: return "X86ISD::FP_TO_INT64_IN_MEM";
7823   case X86ISD::FLD:                return "X86ISD::FLD";
7824   case X86ISD::FST:                return "X86ISD::FST";
7825   case X86ISD::CALL:               return "X86ISD::CALL";
7826   case X86ISD::RDTSC_DAG:          return "X86ISD::RDTSC_DAG";
7827   case X86ISD::BT:                 return "X86ISD::BT";
7828   case X86ISD::CMP:                return "X86ISD::CMP";
7829   case X86ISD::COMI:               return "X86ISD::COMI";
7830   case X86ISD::UCOMI:              return "X86ISD::UCOMI";
7831   case X86ISD::SETCC:              return "X86ISD::SETCC";
7832   case X86ISD::SETCC_CARRY:        return "X86ISD::SETCC_CARRY";
7833   case X86ISD::CMOV:               return "X86ISD::CMOV";
7834   case X86ISD::BRCOND:             return "X86ISD::BRCOND";
7835   case X86ISD::RET_FLAG:           return "X86ISD::RET_FLAG";
7836   case X86ISD::REP_STOS:           return "X86ISD::REP_STOS";
7837   case X86ISD::REP_MOVS:           return "X86ISD::REP_MOVS";
7838   case X86ISD::GlobalBaseReg:      return "X86ISD::GlobalBaseReg";
7839   case X86ISD::Wrapper:            return "X86ISD::Wrapper";
7840   case X86ISD::WrapperRIP:         return "X86ISD::WrapperRIP";
7841   case X86ISD::PEXTRB:             return "X86ISD::PEXTRB";
7842   case X86ISD::PEXTRW:             return "X86ISD::PEXTRW";
7843   case X86ISD::INSERTPS:           return "X86ISD::INSERTPS";
7844   case X86ISD::PINSRB:             return "X86ISD::PINSRB";
7845   case X86ISD::PINSRW:             return "X86ISD::PINSRW";
7846   case X86ISD::MMX_PINSRW:         return "X86ISD::MMX_PINSRW";
7847   case X86ISD::PSHUFB:             return "X86ISD::PSHUFB";
7848   case X86ISD::FMAX:               return "X86ISD::FMAX";
7849   case X86ISD::FMIN:               return "X86ISD::FMIN";
7850   case X86ISD::FRSQRT:             return "X86ISD::FRSQRT";
7851   case X86ISD::FRCP:               return "X86ISD::FRCP";
7852   case X86ISD::TLSADDR:            return "X86ISD::TLSADDR";
7853   case X86ISD::SegmentBaseAddress: return "X86ISD::SegmentBaseAddress";
7854   case X86ISD::EH_RETURN:          return "X86ISD::EH_RETURN";
7855   case X86ISD::TC_RETURN:          return "X86ISD::TC_RETURN";
7856   case X86ISD::FNSTCW16m:          return "X86ISD::FNSTCW16m";
7857   case X86ISD::LCMPXCHG_DAG:       return "X86ISD::LCMPXCHG_DAG";
7858   case X86ISD::LCMPXCHG8_DAG:      return "X86ISD::LCMPXCHG8_DAG";
7859   case X86ISD::ATOMADD64_DAG:      return "X86ISD::ATOMADD64_DAG";
7860   case X86ISD::ATOMSUB64_DAG:      return "X86ISD::ATOMSUB64_DAG";
7861   case X86ISD::ATOMOR64_DAG:       return "X86ISD::ATOMOR64_DAG";
7862   case X86ISD::ATOMXOR64_DAG:      return "X86ISD::ATOMXOR64_DAG";
7863   case X86ISD::ATOMAND64_DAG:      return "X86ISD::ATOMAND64_DAG";
7864   case X86ISD::ATOMNAND64_DAG:     return "X86ISD::ATOMNAND64_DAG";
7865   case X86ISD::VZEXT_MOVL:         return "X86ISD::VZEXT_MOVL";
7866   case X86ISD::VZEXT_LOAD:         return "X86ISD::VZEXT_LOAD";
7867   case X86ISD::VSHL:               return "X86ISD::VSHL";
7868   case X86ISD::VSRL:               return "X86ISD::VSRL";
7869   case X86ISD::CMPPD:              return "X86ISD::CMPPD";
7870   case X86ISD::CMPPS:              return "X86ISD::CMPPS";
7871   case X86ISD::PCMPEQB:            return "X86ISD::PCMPEQB";
7872   case X86ISD::PCMPEQW:            return "X86ISD::PCMPEQW";
7873   case X86ISD::PCMPEQD:            return "X86ISD::PCMPEQD";
7874   case X86ISD::PCMPEQQ:            return "X86ISD::PCMPEQQ";
7875   case X86ISD::PCMPGTB:            return "X86ISD::PCMPGTB";
7876   case X86ISD::PCMPGTW:            return "X86ISD::PCMPGTW";
7877   case X86ISD::PCMPGTD:            return "X86ISD::PCMPGTD";
7878   case X86ISD::PCMPGTQ:            return "X86ISD::PCMPGTQ";
7879   case X86ISD::ADD:                return "X86ISD::ADD";
7880   case X86ISD::SUB:                return "X86ISD::SUB";
7881   case X86ISD::SMUL:               return "X86ISD::SMUL";
7882   case X86ISD::UMUL:               return "X86ISD::UMUL";
7883   case X86ISD::INC:                return "X86ISD::INC";
7884   case X86ISD::DEC:                return "X86ISD::DEC";
7885   case X86ISD::OR:                 return "X86ISD::OR";
7886   case X86ISD::XOR:                return "X86ISD::XOR";
7887   case X86ISD::AND:                return "X86ISD::AND";
7888   case X86ISD::MUL_IMM:            return "X86ISD::MUL_IMM";
7889   case X86ISD::PTEST:              return "X86ISD::PTEST";
7890   case X86ISD::VASTART_SAVE_XMM_REGS: return "X86ISD::VASTART_SAVE_XMM_REGS";
7891   case X86ISD::MINGW_ALLOCA:       return "X86ISD::MINGW_ALLOCA";
7892   }
7893 }
7894
7895 // isLegalAddressingMode - Return true if the addressing mode represented
7896 // by AM is legal for this target, for a load/store of the specified type.
7897 bool X86TargetLowering::isLegalAddressingMode(const AddrMode &AM,
7898                                               const Type *Ty) const {
7899   // X86 supports extremely general addressing modes.
7900   CodeModel::Model M = getTargetMachine().getCodeModel();
7901
7902   // X86 allows a sign-extended 32-bit immediate field as a displacement.
7903   if (!X86::isOffsetSuitableForCodeModel(AM.BaseOffs, M, AM.BaseGV != NULL))
7904     return false;
7905
7906   if (AM.BaseGV) {
7907     unsigned GVFlags =
7908       Subtarget->ClassifyGlobalReference(AM.BaseGV, getTargetMachine());
7909
7910     // If a reference to this global requires an extra load, we can't fold it.
7911     if (isGlobalStubReference(GVFlags))
7912       return false;
7913
7914     // If BaseGV requires a register for the PIC base, we cannot also have a
7915     // BaseReg specified.
7916     if (AM.HasBaseReg && isGlobalRelativeToPICBase(GVFlags))
7917       return false;
7918
7919     // If lower 4G is not available, then we must use rip-relative addressing.
7920     if (Subtarget->is64Bit() && (AM.BaseOffs || AM.Scale > 1))
7921       return false;
7922   }
7923
7924   switch (AM.Scale) {
7925   case 0:
7926   case 1:
7927   case 2:
7928   case 4:
7929   case 8:
7930     // These scales always work.
7931     break;
7932   case 3:
7933   case 5:
7934   case 9:
7935     // These scales are formed with basereg+scalereg.  Only accept if there is
7936     // no basereg yet.
7937     if (AM.HasBaseReg)
7938       return false;
7939     break;
7940   default:  // Other stuff never works.
7941     return false;
7942   }
7943
7944   return true;
7945 }
7946
7947
7948 bool X86TargetLowering::isTruncateFree(const Type *Ty1, const Type *Ty2) const {
7949   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
7950     return false;
7951   unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
7952   unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
7953   if (NumBits1 <= NumBits2)
7954     return false;
7955   return true;
7956 }
7957
7958 bool X86TargetLowering::isTruncateFree(EVT VT1, EVT VT2) const {
7959   if (!VT1.isInteger() || !VT2.isInteger())
7960     return false;
7961   unsigned NumBits1 = VT1.getSizeInBits();
7962   unsigned NumBits2 = VT2.getSizeInBits();
7963   if (NumBits1 <= NumBits2)
7964     return false;
7965   return true;
7966 }
7967
7968 bool X86TargetLowering::isZExtFree(const Type *Ty1, const Type *Ty2) const {
7969   // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
7970   return Ty1->isIntegerTy(32) && Ty2->isIntegerTy(64) && Subtarget->is64Bit();
7971 }
7972
7973 bool X86TargetLowering::isZExtFree(EVT VT1, EVT VT2) const {
7974   // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
7975   return VT1 == MVT::i32 && VT2 == MVT::i64 && Subtarget->is64Bit();
7976 }
7977
7978 bool X86TargetLowering::isNarrowingProfitable(EVT VT1, EVT VT2) const {
7979   // i16 instructions are longer (0x66 prefix) and potentially slower.
7980   return !(VT1 == MVT::i32 && VT2 == MVT::i16);
7981 }
7982
7983 /// isShuffleMaskLegal - Targets can use this to indicate that they only
7984 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
7985 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
7986 /// are assumed to be legal.
7987 bool
7988 X86TargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M,
7989                                       EVT VT) const {
7990   // Very little shuffling can be done for 64-bit vectors right now.
7991   if (VT.getSizeInBits() == 64)
7992     return isPALIGNRMask(M, VT, Subtarget->hasSSSE3());
7993
7994   // FIXME: pshufb, blends, shifts.
7995   return (VT.getVectorNumElements() == 2 ||
7996           ShuffleVectorSDNode::isSplatMask(&M[0], VT) ||
7997           isMOVLMask(M, VT) ||
7998           isSHUFPMask(M, VT) ||
7999           isPSHUFDMask(M, VT) ||
8000           isPSHUFHWMask(M, VT) ||
8001           isPSHUFLWMask(M, VT) ||
8002           isPALIGNRMask(M, VT, Subtarget->hasSSSE3()) ||
8003           isUNPCKLMask(M, VT) ||
8004           isUNPCKHMask(M, VT) ||
8005           isUNPCKL_v_undef_Mask(M, VT) ||
8006           isUNPCKH_v_undef_Mask(M, VT));
8007 }
8008
8009 bool
8010 X86TargetLowering::isVectorClearMaskLegal(const SmallVectorImpl<int> &Mask,
8011                                           EVT VT) const {
8012   unsigned NumElts = VT.getVectorNumElements();
8013   // FIXME: This collection of masks seems suspect.
8014   if (NumElts == 2)
8015     return true;
8016   if (NumElts == 4 && VT.getSizeInBits() == 128) {
8017     return (isMOVLMask(Mask, VT)  ||
8018             isCommutedMOVLMask(Mask, VT, true) ||
8019             isSHUFPMask(Mask, VT) ||
8020             isCommutedSHUFPMask(Mask, VT));
8021   }
8022   return false;
8023 }
8024
8025 //===----------------------------------------------------------------------===//
8026 //                           X86 Scheduler Hooks
8027 //===----------------------------------------------------------------------===//
8028
8029 // private utility function
8030 MachineBasicBlock *
8031 X86TargetLowering::EmitAtomicBitwiseWithCustomInserter(MachineInstr *bInstr,
8032                                                        MachineBasicBlock *MBB,
8033                                                        unsigned regOpc,
8034                                                        unsigned immOpc,
8035                                                        unsigned LoadOpc,
8036                                                        unsigned CXchgOpc,
8037                                                        unsigned copyOpc,
8038                                                        unsigned notOpc,
8039                                                        unsigned EAXreg,
8040                                                        TargetRegisterClass *RC,
8041                                                        bool invSrc) const {
8042   // For the atomic bitwise operator, we generate
8043   //   thisMBB:
8044   //   newMBB:
8045   //     ld  t1 = [bitinstr.addr]
8046   //     op  t2 = t1, [bitinstr.val]
8047   //     mov EAX = t1
8048   //     lcs dest = [bitinstr.addr], t2  [EAX is implicit]
8049   //     bz  newMBB
8050   //     fallthrough -->nextMBB
8051   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
8052   const BasicBlock *LLVM_BB = MBB->getBasicBlock();
8053   MachineFunction::iterator MBBIter = MBB;
8054   ++MBBIter;
8055
8056   /// First build the CFG
8057   MachineFunction *F = MBB->getParent();
8058   MachineBasicBlock *thisMBB = MBB;
8059   MachineBasicBlock *newMBB = F->CreateMachineBasicBlock(LLVM_BB);
8060   MachineBasicBlock *nextMBB = F->CreateMachineBasicBlock(LLVM_BB);
8061   F->insert(MBBIter, newMBB);
8062   F->insert(MBBIter, nextMBB);
8063
8064   // Move all successors to thisMBB to nextMBB
8065   nextMBB->transferSuccessors(thisMBB);
8066
8067   // Update thisMBB to fall through to newMBB
8068   thisMBB->addSuccessor(newMBB);
8069
8070   // newMBB jumps to itself and fall through to nextMBB
8071   newMBB->addSuccessor(nextMBB);
8072   newMBB->addSuccessor(newMBB);
8073
8074   // Insert instructions into newMBB based on incoming instruction
8075   assert(bInstr->getNumOperands() < X86AddrNumOperands + 4 &&
8076          "unexpected number of operands");
8077   DebugLoc dl = bInstr->getDebugLoc();
8078   MachineOperand& destOper = bInstr->getOperand(0);
8079   MachineOperand* argOpers[2 + X86AddrNumOperands];
8080   int numArgs = bInstr->getNumOperands() - 1;
8081   for (int i=0; i < numArgs; ++i)
8082     argOpers[i] = &bInstr->getOperand(i+1);
8083
8084   // x86 address has 4 operands: base, index, scale, and displacement
8085   int lastAddrIndx = X86AddrNumOperands - 1; // [0,3]
8086   int valArgIndx = lastAddrIndx + 1;
8087
8088   unsigned t1 = F->getRegInfo().createVirtualRegister(RC);
8089   MachineInstrBuilder MIB = BuildMI(newMBB, dl, TII->get(LoadOpc), t1);
8090   for (int i=0; i <= lastAddrIndx; ++i)
8091     (*MIB).addOperand(*argOpers[i]);
8092
8093   unsigned tt = F->getRegInfo().createVirtualRegister(RC);
8094   if (invSrc) {
8095     MIB = BuildMI(newMBB, dl, TII->get(notOpc), tt).addReg(t1);
8096   }
8097   else
8098     tt = t1;
8099
8100   unsigned t2 = F->getRegInfo().createVirtualRegister(RC);
8101   assert((argOpers[valArgIndx]->isReg() ||
8102           argOpers[valArgIndx]->isImm()) &&
8103          "invalid operand");
8104   if (argOpers[valArgIndx]->isReg())
8105     MIB = BuildMI(newMBB, dl, TII->get(regOpc), t2);
8106   else
8107     MIB = BuildMI(newMBB, dl, TII->get(immOpc), t2);
8108   MIB.addReg(tt);
8109   (*MIB).addOperand(*argOpers[valArgIndx]);
8110
8111   MIB = BuildMI(newMBB, dl, TII->get(copyOpc), EAXreg);
8112   MIB.addReg(t1);
8113
8114   MIB = BuildMI(newMBB, dl, TII->get(CXchgOpc));
8115   for (int i=0; i <= lastAddrIndx; ++i)
8116     (*MIB).addOperand(*argOpers[i]);
8117   MIB.addReg(t2);
8118   assert(bInstr->hasOneMemOperand() && "Unexpected number of memoperand");
8119   (*MIB).setMemRefs(bInstr->memoperands_begin(),
8120                     bInstr->memoperands_end());
8121
8122   MIB = BuildMI(newMBB, dl, TII->get(copyOpc), destOper.getReg());
8123   MIB.addReg(EAXreg);
8124
8125   // insert branch
8126   BuildMI(newMBB, dl, TII->get(X86::JNE_4)).addMBB(newMBB);
8127
8128   F->DeleteMachineInstr(bInstr);   // The pseudo instruction is gone now.
8129   return nextMBB;
8130 }
8131
8132 // private utility function:  64 bit atomics on 32 bit host.
8133 MachineBasicBlock *
8134 X86TargetLowering::EmitAtomicBit6432WithCustomInserter(MachineInstr *bInstr,
8135                                                        MachineBasicBlock *MBB,
8136                                                        unsigned regOpcL,
8137                                                        unsigned regOpcH,
8138                                                        unsigned immOpcL,
8139                                                        unsigned immOpcH,
8140                                                        bool invSrc) const {
8141   // For the atomic bitwise operator, we generate
8142   //   thisMBB (instructions are in pairs, except cmpxchg8b)
8143   //     ld t1,t2 = [bitinstr.addr]
8144   //   newMBB:
8145   //     out1, out2 = phi (thisMBB, t1/t2) (newMBB, t3/t4)
8146   //     op  t5, t6 <- out1, out2, [bitinstr.val]
8147   //      (for SWAP, substitute:  mov t5, t6 <- [bitinstr.val])
8148   //     mov ECX, EBX <- t5, t6
8149   //     mov EAX, EDX <- t1, t2
8150   //     cmpxchg8b [bitinstr.addr]  [EAX, EDX, EBX, ECX implicit]
8151   //     mov t3, t4 <- EAX, EDX
8152   //     bz  newMBB
8153   //     result in out1, out2
8154   //     fallthrough -->nextMBB
8155
8156   const TargetRegisterClass *RC = X86::GR32RegisterClass;
8157   const unsigned LoadOpc = X86::MOV32rm;
8158   const unsigned copyOpc = X86::MOV32rr;
8159   const unsigned NotOpc = X86::NOT32r;
8160   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
8161   const BasicBlock *LLVM_BB = MBB->getBasicBlock();
8162   MachineFunction::iterator MBBIter = MBB;
8163   ++MBBIter;
8164
8165   /// First build the CFG
8166   MachineFunction *F = MBB->getParent();
8167   MachineBasicBlock *thisMBB = MBB;
8168   MachineBasicBlock *newMBB = F->CreateMachineBasicBlock(LLVM_BB);
8169   MachineBasicBlock *nextMBB = F->CreateMachineBasicBlock(LLVM_BB);
8170   F->insert(MBBIter, newMBB);
8171   F->insert(MBBIter, nextMBB);
8172
8173   // Move all successors to thisMBB to nextMBB
8174   nextMBB->transferSuccessors(thisMBB);
8175
8176   // Update thisMBB to fall through to newMBB
8177   thisMBB->addSuccessor(newMBB);
8178
8179   // newMBB jumps to itself and fall through to nextMBB
8180   newMBB->addSuccessor(nextMBB);
8181   newMBB->addSuccessor(newMBB);
8182
8183   DebugLoc dl = bInstr->getDebugLoc();
8184   // Insert instructions into newMBB based on incoming instruction
8185   // There are 8 "real" operands plus 9 implicit def/uses, ignored here.
8186   assert(bInstr->getNumOperands() < X86AddrNumOperands + 14 &&
8187          "unexpected number of operands");
8188   MachineOperand& dest1Oper = bInstr->getOperand(0);
8189   MachineOperand& dest2Oper = bInstr->getOperand(1);
8190   MachineOperand* argOpers[2 + X86AddrNumOperands];
8191   for (int i=0; i < 2 + X86AddrNumOperands; ++i)
8192     argOpers[i] = &bInstr->getOperand(i+2);
8193
8194   // x86 address has 5 operands: base, index, scale, displacement, and segment.
8195   int lastAddrIndx = X86AddrNumOperands - 1; // [0,3]
8196
8197   unsigned t1 = F->getRegInfo().createVirtualRegister(RC);
8198   MachineInstrBuilder MIB = BuildMI(thisMBB, dl, TII->get(LoadOpc), t1);
8199   for (int i=0; i <= lastAddrIndx; ++i)
8200     (*MIB).addOperand(*argOpers[i]);
8201   unsigned t2 = F->getRegInfo().createVirtualRegister(RC);
8202   MIB = BuildMI(thisMBB, dl, TII->get(LoadOpc), t2);
8203   // add 4 to displacement.
8204   for (int i=0; i <= lastAddrIndx-2; ++i)
8205     (*MIB).addOperand(*argOpers[i]);
8206   MachineOperand newOp3 = *(argOpers[3]);
8207   if (newOp3.isImm())
8208     newOp3.setImm(newOp3.getImm()+4);
8209   else
8210     newOp3.setOffset(newOp3.getOffset()+4);
8211   (*MIB).addOperand(newOp3);
8212   (*MIB).addOperand(*argOpers[lastAddrIndx]);
8213
8214   // t3/4 are defined later, at the bottom of the loop
8215   unsigned t3 = F->getRegInfo().createVirtualRegister(RC);
8216   unsigned t4 = F->getRegInfo().createVirtualRegister(RC);
8217   BuildMI(newMBB, dl, TII->get(X86::PHI), dest1Oper.getReg())
8218     .addReg(t1).addMBB(thisMBB).addReg(t3).addMBB(newMBB);
8219   BuildMI(newMBB, dl, TII->get(X86::PHI), dest2Oper.getReg())
8220     .addReg(t2).addMBB(thisMBB).addReg(t4).addMBB(newMBB);
8221
8222   // The subsequent operations should be using the destination registers of
8223   //the PHI instructions.
8224   if (invSrc) {
8225     t1 = F->getRegInfo().createVirtualRegister(RC);
8226     t2 = F->getRegInfo().createVirtualRegister(RC);
8227     MIB = BuildMI(newMBB, dl, TII->get(NotOpc), t1).addReg(dest1Oper.getReg());
8228     MIB = BuildMI(newMBB, dl, TII->get(NotOpc), t2).addReg(dest2Oper.getReg());
8229   } else {
8230     t1 = dest1Oper.getReg();
8231     t2 = dest2Oper.getReg();
8232   }
8233
8234   int valArgIndx = lastAddrIndx + 1;
8235   assert((argOpers[valArgIndx]->isReg() ||
8236           argOpers[valArgIndx]->isImm()) &&
8237          "invalid operand");
8238   unsigned t5 = F->getRegInfo().createVirtualRegister(RC);
8239   unsigned t6 = F->getRegInfo().createVirtualRegister(RC);
8240   if (argOpers[valArgIndx]->isReg())
8241     MIB = BuildMI(newMBB, dl, TII->get(regOpcL), t5);
8242   else
8243     MIB = BuildMI(newMBB, dl, TII->get(immOpcL), t5);
8244   if (regOpcL != X86::MOV32rr)
8245     MIB.addReg(t1);
8246   (*MIB).addOperand(*argOpers[valArgIndx]);
8247   assert(argOpers[valArgIndx + 1]->isReg() ==
8248          argOpers[valArgIndx]->isReg());
8249   assert(argOpers[valArgIndx + 1]->isImm() ==
8250          argOpers[valArgIndx]->isImm());
8251   if (argOpers[valArgIndx + 1]->isReg())
8252     MIB = BuildMI(newMBB, dl, TII->get(regOpcH), t6);
8253   else
8254     MIB = BuildMI(newMBB, dl, TII->get(immOpcH), t6);
8255   if (regOpcH != X86::MOV32rr)
8256     MIB.addReg(t2);
8257   (*MIB).addOperand(*argOpers[valArgIndx + 1]);
8258
8259   MIB = BuildMI(newMBB, dl, TII->get(copyOpc), X86::EAX);
8260   MIB.addReg(t1);
8261   MIB = BuildMI(newMBB, dl, TII->get(copyOpc), X86::EDX);
8262   MIB.addReg(t2);
8263
8264   MIB = BuildMI(newMBB, dl, TII->get(copyOpc), X86::EBX);
8265   MIB.addReg(t5);
8266   MIB = BuildMI(newMBB, dl, TII->get(copyOpc), X86::ECX);
8267   MIB.addReg(t6);
8268
8269   MIB = BuildMI(newMBB, dl, TII->get(X86::LCMPXCHG8B));
8270   for (int i=0; i <= lastAddrIndx; ++i)
8271     (*MIB).addOperand(*argOpers[i]);
8272
8273   assert(bInstr->hasOneMemOperand() && "Unexpected number of memoperand");
8274   (*MIB).setMemRefs(bInstr->memoperands_begin(),
8275                     bInstr->memoperands_end());
8276
8277   MIB = BuildMI(newMBB, dl, TII->get(copyOpc), t3);
8278   MIB.addReg(X86::EAX);
8279   MIB = BuildMI(newMBB, dl, TII->get(copyOpc), t4);
8280   MIB.addReg(X86::EDX);
8281
8282   // insert branch
8283   BuildMI(newMBB, dl, TII->get(X86::JNE_4)).addMBB(newMBB);
8284
8285   F->DeleteMachineInstr(bInstr);   // The pseudo instruction is gone now.
8286   return nextMBB;
8287 }
8288
8289 // private utility function
8290 MachineBasicBlock *
8291 X86TargetLowering::EmitAtomicMinMaxWithCustomInserter(MachineInstr *mInstr,
8292                                                       MachineBasicBlock *MBB,
8293                                                       unsigned cmovOpc) const {
8294   // For the atomic min/max operator, we generate
8295   //   thisMBB:
8296   //   newMBB:
8297   //     ld t1 = [min/max.addr]
8298   //     mov t2 = [min/max.val]
8299   //     cmp  t1, t2
8300   //     cmov[cond] t2 = t1
8301   //     mov EAX = t1
8302   //     lcs dest = [bitinstr.addr], t2  [EAX is implicit]
8303   //     bz   newMBB
8304   //     fallthrough -->nextMBB
8305   //
8306   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
8307   const BasicBlock *LLVM_BB = MBB->getBasicBlock();
8308   MachineFunction::iterator MBBIter = MBB;
8309   ++MBBIter;
8310
8311   /// First build the CFG
8312   MachineFunction *F = MBB->getParent();
8313   MachineBasicBlock *thisMBB = MBB;
8314   MachineBasicBlock *newMBB = F->CreateMachineBasicBlock(LLVM_BB);
8315   MachineBasicBlock *nextMBB = F->CreateMachineBasicBlock(LLVM_BB);
8316   F->insert(MBBIter, newMBB);
8317   F->insert(MBBIter, nextMBB);
8318
8319   // Move all successors of thisMBB to nextMBB
8320   nextMBB->transferSuccessors(thisMBB);
8321
8322   // Update thisMBB to fall through to newMBB
8323   thisMBB->addSuccessor(newMBB);
8324
8325   // newMBB jumps to newMBB and fall through to nextMBB
8326   newMBB->addSuccessor(nextMBB);
8327   newMBB->addSuccessor(newMBB);
8328
8329   DebugLoc dl = mInstr->getDebugLoc();
8330   // Insert instructions into newMBB based on incoming instruction
8331   assert(mInstr->getNumOperands() < X86AddrNumOperands + 4 &&
8332          "unexpected number of operands");
8333   MachineOperand& destOper = mInstr->getOperand(0);
8334   MachineOperand* argOpers[2 + X86AddrNumOperands];
8335   int numArgs = mInstr->getNumOperands() - 1;
8336   for (int i=0; i < numArgs; ++i)
8337     argOpers[i] = &mInstr->getOperand(i+1);
8338
8339   // x86 address has 4 operands: base, index, scale, and displacement
8340   int lastAddrIndx = X86AddrNumOperands - 1; // [0,3]
8341   int valArgIndx = lastAddrIndx + 1;
8342
8343   unsigned t1 = F->getRegInfo().createVirtualRegister(X86::GR32RegisterClass);
8344   MachineInstrBuilder MIB = BuildMI(newMBB, dl, TII->get(X86::MOV32rm), t1);
8345   for (int i=0; i <= lastAddrIndx; ++i)
8346     (*MIB).addOperand(*argOpers[i]);
8347
8348   // We only support register and immediate values
8349   assert((argOpers[valArgIndx]->isReg() ||
8350           argOpers[valArgIndx]->isImm()) &&
8351          "invalid operand");
8352
8353   unsigned t2 = F->getRegInfo().createVirtualRegister(X86::GR32RegisterClass);
8354   if (argOpers[valArgIndx]->isReg())
8355     MIB = BuildMI(newMBB, dl, TII->get(X86::MOV32rr), t2);
8356   else
8357     MIB = BuildMI(newMBB, dl, TII->get(X86::MOV32rr), t2);
8358   (*MIB).addOperand(*argOpers[valArgIndx]);
8359
8360   MIB = BuildMI(newMBB, dl, TII->get(X86::MOV32rr), X86::EAX);
8361   MIB.addReg(t1);
8362
8363   MIB = BuildMI(newMBB, dl, TII->get(X86::CMP32rr));
8364   MIB.addReg(t1);
8365   MIB.addReg(t2);
8366
8367   // Generate movc
8368   unsigned t3 = F->getRegInfo().createVirtualRegister(X86::GR32RegisterClass);
8369   MIB = BuildMI(newMBB, dl, TII->get(cmovOpc),t3);
8370   MIB.addReg(t2);
8371   MIB.addReg(t1);
8372
8373   // Cmp and exchange if none has modified the memory location
8374   MIB = BuildMI(newMBB, dl, TII->get(X86::LCMPXCHG32));
8375   for (int i=0; i <= lastAddrIndx; ++i)
8376     (*MIB).addOperand(*argOpers[i]);
8377   MIB.addReg(t3);
8378   assert(mInstr->hasOneMemOperand() && "Unexpected number of memoperand");
8379   (*MIB).setMemRefs(mInstr->memoperands_begin(),
8380                     mInstr->memoperands_end());
8381
8382   MIB = BuildMI(newMBB, dl, TII->get(X86::MOV32rr), destOper.getReg());
8383   MIB.addReg(X86::EAX);
8384
8385   // insert branch
8386   BuildMI(newMBB, dl, TII->get(X86::JNE_4)).addMBB(newMBB);
8387
8388   F->DeleteMachineInstr(mInstr);   // The pseudo instruction is gone now.
8389   return nextMBB;
8390 }
8391
8392 // FIXME: When we get size specific XMM0 registers, i.e. XMM0_V16I8
8393 // all of this code can be replaced with that in the .td file.
8394 MachineBasicBlock *
8395 X86TargetLowering::EmitPCMP(MachineInstr *MI, MachineBasicBlock *BB,
8396                             unsigned numArgs, bool memArg) const {
8397
8398   MachineFunction *F = BB->getParent();
8399   DebugLoc dl = MI->getDebugLoc();
8400   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
8401
8402   unsigned Opc;
8403   if (memArg)
8404     Opc = numArgs == 3 ? X86::PCMPISTRM128rm : X86::PCMPESTRM128rm;
8405   else
8406     Opc = numArgs == 3 ? X86::PCMPISTRM128rr : X86::PCMPESTRM128rr;
8407
8408   MachineInstrBuilder MIB = BuildMI(BB, dl, TII->get(Opc));
8409
8410   for (unsigned i = 0; i < numArgs; ++i) {
8411     MachineOperand &Op = MI->getOperand(i+1);
8412
8413     if (!(Op.isReg() && Op.isImplicit()))
8414       MIB.addOperand(Op);
8415   }
8416
8417   BuildMI(BB, dl, TII->get(X86::MOVAPSrr), MI->getOperand(0).getReg())
8418     .addReg(X86::XMM0);
8419
8420   F->DeleteMachineInstr(MI);
8421
8422   return BB;
8423 }
8424
8425 MachineBasicBlock *
8426 X86TargetLowering::EmitVAStartSaveXMMRegsWithCustomInserter(
8427                                                  MachineInstr *MI,
8428                                                  MachineBasicBlock *MBB) const {
8429   // Emit code to save XMM registers to the stack. The ABI says that the
8430   // number of registers to save is given in %al, so it's theoretically
8431   // possible to do an indirect jump trick to avoid saving all of them,
8432   // however this code takes a simpler approach and just executes all
8433   // of the stores if %al is non-zero. It's less code, and it's probably
8434   // easier on the hardware branch predictor, and stores aren't all that
8435   // expensive anyway.
8436
8437   // Create the new basic blocks. One block contains all the XMM stores,
8438   // and one block is the final destination regardless of whether any
8439   // stores were performed.
8440   const BasicBlock *LLVM_BB = MBB->getBasicBlock();
8441   MachineFunction *F = MBB->getParent();
8442   MachineFunction::iterator MBBIter = MBB;
8443   ++MBBIter;
8444   MachineBasicBlock *XMMSaveMBB = F->CreateMachineBasicBlock(LLVM_BB);
8445   MachineBasicBlock *EndMBB = F->CreateMachineBasicBlock(LLVM_BB);
8446   F->insert(MBBIter, XMMSaveMBB);
8447   F->insert(MBBIter, EndMBB);
8448
8449   // Set up the CFG.
8450   // Move any original successors of MBB to the end block.
8451   EndMBB->transferSuccessors(MBB);
8452   // The original block will now fall through to the XMM save block.
8453   MBB->addSuccessor(XMMSaveMBB);
8454   // The XMMSaveMBB will fall through to the end block.
8455   XMMSaveMBB->addSuccessor(EndMBB);
8456
8457   // Now add the instructions.
8458   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
8459   DebugLoc DL = MI->getDebugLoc();
8460
8461   unsigned CountReg = MI->getOperand(0).getReg();
8462   int64_t RegSaveFrameIndex = MI->getOperand(1).getImm();
8463   int64_t VarArgsFPOffset = MI->getOperand(2).getImm();
8464
8465   if (!Subtarget->isTargetWin64()) {
8466     // If %al is 0, branch around the XMM save block.
8467     BuildMI(MBB, DL, TII->get(X86::TEST8rr)).addReg(CountReg).addReg(CountReg);
8468     BuildMI(MBB, DL, TII->get(X86::JE_4)).addMBB(EndMBB);
8469     MBB->addSuccessor(EndMBB);
8470   }
8471
8472   // In the XMM save block, save all the XMM argument registers.
8473   for (int i = 3, e = MI->getNumOperands(); i != e; ++i) {
8474     int64_t Offset = (i - 3) * 16 + VarArgsFPOffset;
8475     MachineMemOperand *MMO =
8476       F->getMachineMemOperand(
8477         PseudoSourceValue::getFixedStack(RegSaveFrameIndex),
8478         MachineMemOperand::MOStore, Offset,
8479         /*Size=*/16, /*Align=*/16);
8480     BuildMI(XMMSaveMBB, DL, TII->get(X86::MOVAPSmr))
8481       .addFrameIndex(RegSaveFrameIndex)
8482       .addImm(/*Scale=*/1)
8483       .addReg(/*IndexReg=*/0)
8484       .addImm(/*Disp=*/Offset)
8485       .addReg(/*Segment=*/0)
8486       .addReg(MI->getOperand(i).getReg())
8487       .addMemOperand(MMO);
8488   }
8489
8490   F->DeleteMachineInstr(MI);   // The pseudo instruction is gone now.
8491
8492   return EndMBB;
8493 }
8494
8495 MachineBasicBlock *
8496 X86TargetLowering::EmitLoweredSelect(MachineInstr *MI,
8497                                      MachineBasicBlock *BB,
8498                    DenseMap<MachineBasicBlock*, MachineBasicBlock*> *EM) const {
8499   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
8500   DebugLoc DL = MI->getDebugLoc();
8501
8502   // To "insert" a SELECT_CC instruction, we actually have to insert the
8503   // diamond control-flow pattern.  The incoming instruction knows the
8504   // destination vreg to set, the condition code register to branch on, the
8505   // true/false values to select between, and a branch opcode to use.
8506   const BasicBlock *LLVM_BB = BB->getBasicBlock();
8507   MachineFunction::iterator It = BB;
8508   ++It;
8509
8510   //  thisMBB:
8511   //  ...
8512   //   TrueVal = ...
8513   //   cmpTY ccX, r1, r2
8514   //   bCC copy1MBB
8515   //   fallthrough --> copy0MBB
8516   MachineBasicBlock *thisMBB = BB;
8517   MachineFunction *F = BB->getParent();
8518   MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
8519   MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
8520   unsigned Opc =
8521     X86::GetCondBranchFromCond((X86::CondCode)MI->getOperand(3).getImm());
8522   BuildMI(BB, DL, TII->get(Opc)).addMBB(sinkMBB);
8523   F->insert(It, copy0MBB);
8524   F->insert(It, sinkMBB);
8525   // Update machine-CFG edges by first adding all successors of the current
8526   // block to the new block which will contain the Phi node for the select.
8527   // Also inform sdisel of the edge changes.
8528   for (MachineBasicBlock::succ_iterator I = BB->succ_begin(),
8529          E = BB->succ_end(); I != E; ++I) {
8530     EM->insert(std::make_pair(*I, sinkMBB));
8531     sinkMBB->addSuccessor(*I);
8532   }
8533   // Next, remove all successors of the current block, and add the true
8534   // and fallthrough blocks as its successors.
8535   while (!BB->succ_empty())
8536     BB->removeSuccessor(BB->succ_begin());
8537   // Add the true and fallthrough blocks as its successors.
8538   BB->addSuccessor(copy0MBB);
8539   BB->addSuccessor(sinkMBB);
8540
8541   //  copy0MBB:
8542   //   %FalseValue = ...
8543   //   # fallthrough to sinkMBB
8544   BB = copy0MBB;
8545
8546   // Update machine-CFG edges
8547   BB->addSuccessor(sinkMBB);
8548
8549   //  sinkMBB:
8550   //   %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
8551   //  ...
8552   BB = sinkMBB;
8553   BuildMI(BB, DL, TII->get(X86::PHI), MI->getOperand(0).getReg())
8554     .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB)
8555     .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
8556
8557   F->DeleteMachineInstr(MI);   // The pseudo instruction is gone now.
8558   return BB;
8559 }
8560
8561 MachineBasicBlock *
8562 X86TargetLowering::EmitLoweredMingwAlloca(MachineInstr *MI,
8563                                           MachineBasicBlock *BB,
8564                    DenseMap<MachineBasicBlock*, MachineBasicBlock*> *EM) const {
8565   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
8566   DebugLoc DL = MI->getDebugLoc();
8567   MachineFunction *F = BB->getParent();
8568
8569   // The lowering is pretty easy: we're just emitting the call to _alloca.  The
8570   // non-trivial part is impdef of ESP.
8571   // FIXME: The code should be tweaked as soon as we'll try to do codegen for
8572   // mingw-w64.
8573
8574   BuildMI(BB, DL, TII->get(X86::CALLpcrel32))
8575     .addExternalSymbol("_alloca")
8576     .addReg(X86::EAX, RegState::Implicit)
8577     .addReg(X86::ESP, RegState::Implicit)
8578     .addReg(X86::EAX, RegState::Define | RegState::Implicit)
8579     .addReg(X86::ESP, RegState::Define | RegState::Implicit);
8580
8581   F->DeleteMachineInstr(MI);   // The pseudo instruction is gone now.
8582   return BB;
8583 }
8584
8585 MachineBasicBlock *
8586 X86TargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
8587                                                MachineBasicBlock *BB,
8588                    DenseMap<MachineBasicBlock*, MachineBasicBlock*> *EM) const {
8589   switch (MI->getOpcode()) {
8590   default: assert(false && "Unexpected instr type to insert");
8591   case X86::MINGW_ALLOCA:
8592     return EmitLoweredMingwAlloca(MI, BB, EM);
8593   case X86::CMOV_GR8:
8594   case X86::CMOV_V1I64:
8595   case X86::CMOV_FR32:
8596   case X86::CMOV_FR64:
8597   case X86::CMOV_V4F32:
8598   case X86::CMOV_V2F64:
8599   case X86::CMOV_V2I64:
8600   case X86::CMOV_GR16:
8601   case X86::CMOV_GR32:
8602   case X86::CMOV_RFP32:
8603   case X86::CMOV_RFP64:
8604   case X86::CMOV_RFP80:
8605     return EmitLoweredSelect(MI, BB, EM);
8606
8607   case X86::FP32_TO_INT16_IN_MEM:
8608   case X86::FP32_TO_INT32_IN_MEM:
8609   case X86::FP32_TO_INT64_IN_MEM:
8610   case X86::FP64_TO_INT16_IN_MEM:
8611   case X86::FP64_TO_INT32_IN_MEM:
8612   case X86::FP64_TO_INT64_IN_MEM:
8613   case X86::FP80_TO_INT16_IN_MEM:
8614   case X86::FP80_TO_INT32_IN_MEM:
8615   case X86::FP80_TO_INT64_IN_MEM: {
8616     const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
8617     DebugLoc DL = MI->getDebugLoc();
8618
8619     // Change the floating point control register to use "round towards zero"
8620     // mode when truncating to an integer value.
8621     MachineFunction *F = BB->getParent();
8622     int CWFrameIdx = F->getFrameInfo()->CreateStackObject(2, 2, false);
8623     addFrameReference(BuildMI(BB, DL, TII->get(X86::FNSTCW16m)), CWFrameIdx);
8624
8625     // Load the old value of the high byte of the control word...
8626     unsigned OldCW =
8627       F->getRegInfo().createVirtualRegister(X86::GR16RegisterClass);
8628     addFrameReference(BuildMI(BB, DL, TII->get(X86::MOV16rm), OldCW),
8629                       CWFrameIdx);
8630
8631     // Set the high part to be round to zero...
8632     addFrameReference(BuildMI(BB, DL, TII->get(X86::MOV16mi)), CWFrameIdx)
8633       .addImm(0xC7F);
8634
8635     // Reload the modified control word now...
8636     addFrameReference(BuildMI(BB, DL, TII->get(X86::FLDCW16m)), CWFrameIdx);
8637
8638     // Restore the memory image of control word to original value
8639     addFrameReference(BuildMI(BB, DL, TII->get(X86::MOV16mr)), CWFrameIdx)
8640       .addReg(OldCW);
8641
8642     // Get the X86 opcode to use.
8643     unsigned Opc;
8644     switch (MI->getOpcode()) {
8645     default: llvm_unreachable("illegal opcode!");
8646     case X86::FP32_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m32; break;
8647     case X86::FP32_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m32; break;
8648     case X86::FP32_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m32; break;
8649     case X86::FP64_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m64; break;
8650     case X86::FP64_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m64; break;
8651     case X86::FP64_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m64; break;
8652     case X86::FP80_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m80; break;
8653     case X86::FP80_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m80; break;
8654     case X86::FP80_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m80; break;
8655     }
8656
8657     X86AddressMode AM;
8658     MachineOperand &Op = MI->getOperand(0);
8659     if (Op.isReg()) {
8660       AM.BaseType = X86AddressMode::RegBase;
8661       AM.Base.Reg = Op.getReg();
8662     } else {
8663       AM.BaseType = X86AddressMode::FrameIndexBase;
8664       AM.Base.FrameIndex = Op.getIndex();
8665     }
8666     Op = MI->getOperand(1);
8667     if (Op.isImm())
8668       AM.Scale = Op.getImm();
8669     Op = MI->getOperand(2);
8670     if (Op.isImm())
8671       AM.IndexReg = Op.getImm();
8672     Op = MI->getOperand(3);
8673     if (Op.isGlobal()) {
8674       AM.GV = Op.getGlobal();
8675     } else {
8676       AM.Disp = Op.getImm();
8677     }
8678     addFullAddress(BuildMI(BB, DL, TII->get(Opc)), AM)
8679                       .addReg(MI->getOperand(X86AddrNumOperands).getReg());
8680
8681     // Reload the original control word now.
8682     addFrameReference(BuildMI(BB, DL, TII->get(X86::FLDCW16m)), CWFrameIdx);
8683
8684     F->DeleteMachineInstr(MI);   // The pseudo instruction is gone now.
8685     return BB;
8686   }
8687     // String/text processing lowering.
8688   case X86::PCMPISTRM128REG:
8689     return EmitPCMP(MI, BB, 3, false /* in-mem */);
8690   case X86::PCMPISTRM128MEM:
8691     return EmitPCMP(MI, BB, 3, true /* in-mem */);
8692   case X86::PCMPESTRM128REG:
8693     return EmitPCMP(MI, BB, 5, false /* in mem */);
8694   case X86::PCMPESTRM128MEM:
8695     return EmitPCMP(MI, BB, 5, true /* in mem */);
8696
8697     // Atomic Lowering.
8698   case X86::ATOMAND32:
8699     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND32rr,
8700                                                X86::AND32ri, X86::MOV32rm,
8701                                                X86::LCMPXCHG32, X86::MOV32rr,
8702                                                X86::NOT32r, X86::EAX,
8703                                                X86::GR32RegisterClass);
8704   case X86::ATOMOR32:
8705     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR32rr,
8706                                                X86::OR32ri, X86::MOV32rm,
8707                                                X86::LCMPXCHG32, X86::MOV32rr,
8708                                                X86::NOT32r, X86::EAX,
8709                                                X86::GR32RegisterClass);
8710   case X86::ATOMXOR32:
8711     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR32rr,
8712                                                X86::XOR32ri, X86::MOV32rm,
8713                                                X86::LCMPXCHG32, X86::MOV32rr,
8714                                                X86::NOT32r, X86::EAX,
8715                                                X86::GR32RegisterClass);
8716   case X86::ATOMNAND32:
8717     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND32rr,
8718                                                X86::AND32ri, X86::MOV32rm,
8719                                                X86::LCMPXCHG32, X86::MOV32rr,
8720                                                X86::NOT32r, X86::EAX,
8721                                                X86::GR32RegisterClass, true);
8722   case X86::ATOMMIN32:
8723     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVL32rr);
8724   case X86::ATOMMAX32:
8725     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVG32rr);
8726   case X86::ATOMUMIN32:
8727     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVB32rr);
8728   case X86::ATOMUMAX32:
8729     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVA32rr);
8730
8731   case X86::ATOMAND16:
8732     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND16rr,
8733                                                X86::AND16ri, X86::MOV16rm,
8734                                                X86::LCMPXCHG16, X86::MOV16rr,
8735                                                X86::NOT16r, X86::AX,
8736                                                X86::GR16RegisterClass);
8737   case X86::ATOMOR16:
8738     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR16rr,
8739                                                X86::OR16ri, X86::MOV16rm,
8740                                                X86::LCMPXCHG16, X86::MOV16rr,
8741                                                X86::NOT16r, X86::AX,
8742                                                X86::GR16RegisterClass);
8743   case X86::ATOMXOR16:
8744     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR16rr,
8745                                                X86::XOR16ri, X86::MOV16rm,
8746                                                X86::LCMPXCHG16, X86::MOV16rr,
8747                                                X86::NOT16r, X86::AX,
8748                                                X86::GR16RegisterClass);
8749   case X86::ATOMNAND16:
8750     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND16rr,
8751                                                X86::AND16ri, X86::MOV16rm,
8752                                                X86::LCMPXCHG16, X86::MOV16rr,
8753                                                X86::NOT16r, X86::AX,
8754                                                X86::GR16RegisterClass, true);
8755   case X86::ATOMMIN16:
8756     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVL16rr);
8757   case X86::ATOMMAX16:
8758     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVG16rr);
8759   case X86::ATOMUMIN16:
8760     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVB16rr);
8761   case X86::ATOMUMAX16:
8762     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVA16rr);
8763
8764   case X86::ATOMAND8:
8765     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND8rr,
8766                                                X86::AND8ri, X86::MOV8rm,
8767                                                X86::LCMPXCHG8, X86::MOV8rr,
8768                                                X86::NOT8r, X86::AL,
8769                                                X86::GR8RegisterClass);
8770   case X86::ATOMOR8:
8771     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR8rr,
8772                                                X86::OR8ri, X86::MOV8rm,
8773                                                X86::LCMPXCHG8, X86::MOV8rr,
8774                                                X86::NOT8r, X86::AL,
8775                                                X86::GR8RegisterClass);
8776   case X86::ATOMXOR8:
8777     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR8rr,
8778                                                X86::XOR8ri, X86::MOV8rm,
8779                                                X86::LCMPXCHG8, X86::MOV8rr,
8780                                                X86::NOT8r, X86::AL,
8781                                                X86::GR8RegisterClass);
8782   case X86::ATOMNAND8:
8783     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND8rr,
8784                                                X86::AND8ri, X86::MOV8rm,
8785                                                X86::LCMPXCHG8, X86::MOV8rr,
8786                                                X86::NOT8r, X86::AL,
8787                                                X86::GR8RegisterClass, true);
8788   // FIXME: There are no CMOV8 instructions; MIN/MAX need some other way.
8789   // This group is for 64-bit host.
8790   case X86::ATOMAND64:
8791     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND64rr,
8792                                                X86::AND64ri32, X86::MOV64rm,
8793                                                X86::LCMPXCHG64, X86::MOV64rr,
8794                                                X86::NOT64r, X86::RAX,
8795                                                X86::GR64RegisterClass);
8796   case X86::ATOMOR64:
8797     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR64rr,
8798                                                X86::OR64ri32, X86::MOV64rm,
8799                                                X86::LCMPXCHG64, X86::MOV64rr,
8800                                                X86::NOT64r, X86::RAX,
8801                                                X86::GR64RegisterClass);
8802   case X86::ATOMXOR64:
8803     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR64rr,
8804                                                X86::XOR64ri32, X86::MOV64rm,
8805                                                X86::LCMPXCHG64, X86::MOV64rr,
8806                                                X86::NOT64r, X86::RAX,
8807                                                X86::GR64RegisterClass);
8808   case X86::ATOMNAND64:
8809     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND64rr,
8810                                                X86::AND64ri32, X86::MOV64rm,
8811                                                X86::LCMPXCHG64, X86::MOV64rr,
8812                                                X86::NOT64r, X86::RAX,
8813                                                X86::GR64RegisterClass, true);
8814   case X86::ATOMMIN64:
8815     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVL64rr);
8816   case X86::ATOMMAX64:
8817     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVG64rr);
8818   case X86::ATOMUMIN64:
8819     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVB64rr);
8820   case X86::ATOMUMAX64:
8821     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVA64rr);
8822
8823   // This group does 64-bit operations on a 32-bit host.
8824   case X86::ATOMAND6432:
8825     return EmitAtomicBit6432WithCustomInserter(MI, BB,
8826                                                X86::AND32rr, X86::AND32rr,
8827                                                X86::AND32ri, X86::AND32ri,
8828                                                false);
8829   case X86::ATOMOR6432:
8830     return EmitAtomicBit6432WithCustomInserter(MI, BB,
8831                                                X86::OR32rr, X86::OR32rr,
8832                                                X86::OR32ri, X86::OR32ri,
8833                                                false);
8834   case X86::ATOMXOR6432:
8835     return EmitAtomicBit6432WithCustomInserter(MI, BB,
8836                                                X86::XOR32rr, X86::XOR32rr,
8837                                                X86::XOR32ri, X86::XOR32ri,
8838                                                false);
8839   case X86::ATOMNAND6432:
8840     return EmitAtomicBit6432WithCustomInserter(MI, BB,
8841                                                X86::AND32rr, X86::AND32rr,
8842                                                X86::AND32ri, X86::AND32ri,
8843                                                true);
8844   case X86::ATOMADD6432:
8845     return EmitAtomicBit6432WithCustomInserter(MI, BB,
8846                                                X86::ADD32rr, X86::ADC32rr,
8847                                                X86::ADD32ri, X86::ADC32ri,
8848                                                false);
8849   case X86::ATOMSUB6432:
8850     return EmitAtomicBit6432WithCustomInserter(MI, BB,
8851                                                X86::SUB32rr, X86::SBB32rr,
8852                                                X86::SUB32ri, X86::SBB32ri,
8853                                                false);
8854   case X86::ATOMSWAP6432:
8855     return EmitAtomicBit6432WithCustomInserter(MI, BB,
8856                                                X86::MOV32rr, X86::MOV32rr,
8857                                                X86::MOV32ri, X86::MOV32ri,
8858                                                false);
8859   case X86::VASTART_SAVE_XMM_REGS:
8860     return EmitVAStartSaveXMMRegsWithCustomInserter(MI, BB);
8861   }
8862 }
8863
8864 //===----------------------------------------------------------------------===//
8865 //                           X86 Optimization Hooks
8866 //===----------------------------------------------------------------------===//
8867
8868 void X86TargetLowering::computeMaskedBitsForTargetNode(const SDValue Op,
8869                                                        const APInt &Mask,
8870                                                        APInt &KnownZero,
8871                                                        APInt &KnownOne,
8872                                                        const SelectionDAG &DAG,
8873                                                        unsigned Depth) const {
8874   unsigned Opc = Op.getOpcode();
8875   assert((Opc >= ISD::BUILTIN_OP_END ||
8876           Opc == ISD::INTRINSIC_WO_CHAIN ||
8877           Opc == ISD::INTRINSIC_W_CHAIN ||
8878           Opc == ISD::INTRINSIC_VOID) &&
8879          "Should use MaskedValueIsZero if you don't know whether Op"
8880          " is a target node!");
8881
8882   KnownZero = KnownOne = APInt(Mask.getBitWidth(), 0);   // Don't know anything.
8883   switch (Opc) {
8884   default: break;
8885   case X86ISD::ADD:
8886   case X86ISD::SUB:
8887   case X86ISD::SMUL:
8888   case X86ISD::UMUL:
8889   case X86ISD::INC:
8890   case X86ISD::DEC:
8891   case X86ISD::OR:
8892   case X86ISD::XOR:
8893   case X86ISD::AND:
8894     // These nodes' second result is a boolean.
8895     if (Op.getResNo() == 0)
8896       break;
8897     // Fallthrough
8898   case X86ISD::SETCC:
8899     KnownZero |= APInt::getHighBitsSet(Mask.getBitWidth(),
8900                                        Mask.getBitWidth() - 1);
8901     break;
8902   }
8903 }
8904
8905 /// isGAPlusOffset - Returns true (and the GlobalValue and the offset) if the
8906 /// node is a GlobalAddress + offset.
8907 bool X86TargetLowering::isGAPlusOffset(SDNode *N,
8908                                        const GlobalValue* &GA,
8909                                        int64_t &Offset) const {
8910   if (N->getOpcode() == X86ISD::Wrapper) {
8911     if (isa<GlobalAddressSDNode>(N->getOperand(0))) {
8912       GA = cast<GlobalAddressSDNode>(N->getOperand(0))->getGlobal();
8913       Offset = cast<GlobalAddressSDNode>(N->getOperand(0))->getOffset();
8914       return true;
8915     }
8916   }
8917   return TargetLowering::isGAPlusOffset(N, GA, Offset);
8918 }
8919
8920 /// PerformShuffleCombine - Combine a vector_shuffle that is equal to
8921 /// build_vector load1, load2, load3, load4, <0, 1, 2, 3> into a 128-bit load
8922 /// if the load addresses are consecutive, non-overlapping, and in the right
8923 /// order.
8924 static SDValue PerformShuffleCombine(SDNode *N, SelectionDAG &DAG,
8925                                      const TargetLowering &TLI) {
8926   DebugLoc dl = N->getDebugLoc();
8927   EVT VT = N->getValueType(0);
8928   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
8929
8930   if (VT.getSizeInBits() != 128)
8931     return SDValue();
8932
8933   SmallVector<SDValue, 16> Elts;
8934   for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i)
8935     Elts.push_back(DAG.getShuffleScalarElt(SVN, i));
8936   
8937   return EltsFromConsecutiveLoads(VT, Elts, dl, DAG);
8938 }
8939
8940 /// PerformShuffleCombine - Detect vector gather/scatter index generation
8941 /// and convert it from being a bunch of shuffles and extracts to a simple
8942 /// store and scalar loads to extract the elements.
8943 static SDValue PerformEXTRACT_VECTOR_ELTCombine(SDNode *N, SelectionDAG &DAG,
8944                                                 const TargetLowering &TLI) {
8945   SDValue InputVector = N->getOperand(0);
8946
8947   // Only operate on vectors of 4 elements, where the alternative shuffling
8948   // gets to be more expensive.
8949   if (InputVector.getValueType() != MVT::v4i32)
8950     return SDValue();
8951
8952   // Check whether every use of InputVector is an EXTRACT_VECTOR_ELT with a
8953   // single use which is a sign-extend or zero-extend, and all elements are
8954   // used.
8955   SmallVector<SDNode *, 4> Uses;
8956   unsigned ExtractedElements = 0;
8957   for (SDNode::use_iterator UI = InputVector.getNode()->use_begin(),
8958        UE = InputVector.getNode()->use_end(); UI != UE; ++UI) {
8959     if (UI.getUse().getResNo() != InputVector.getResNo())
8960       return SDValue();
8961
8962     SDNode *Extract = *UI;
8963     if (Extract->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
8964       return SDValue();
8965
8966     if (Extract->getValueType(0) != MVT::i32)
8967       return SDValue();
8968     if (!Extract->hasOneUse())
8969       return SDValue();
8970     if (Extract->use_begin()->getOpcode() != ISD::SIGN_EXTEND &&
8971         Extract->use_begin()->getOpcode() != ISD::ZERO_EXTEND)
8972       return SDValue();
8973     if (!isa<ConstantSDNode>(Extract->getOperand(1)))
8974       return SDValue();
8975
8976     // Record which element was extracted.
8977     ExtractedElements |=
8978       1 << cast<ConstantSDNode>(Extract->getOperand(1))->getZExtValue();
8979
8980     Uses.push_back(Extract);
8981   }
8982
8983   // If not all the elements were used, this may not be worthwhile.
8984   if (ExtractedElements != 15)
8985     return SDValue();
8986
8987   // Ok, we've now decided to do the transformation.
8988   DebugLoc dl = InputVector.getDebugLoc();
8989
8990   // Store the value to a temporary stack slot.
8991   SDValue StackPtr = DAG.CreateStackTemporary(InputVector.getValueType());
8992   SDValue Ch = DAG.getStore(DAG.getEntryNode(), dl, InputVector, StackPtr, NULL, 0,
8993                             false, false, 0);
8994
8995   // Replace each use (extract) with a load of the appropriate element.
8996   for (SmallVectorImpl<SDNode *>::iterator UI = Uses.begin(),
8997        UE = Uses.end(); UI != UE; ++UI) {
8998     SDNode *Extract = *UI;
8999
9000     // Compute the element's address.
9001     SDValue Idx = Extract->getOperand(1);
9002     unsigned EltSize =
9003         InputVector.getValueType().getVectorElementType().getSizeInBits()/8;
9004     uint64_t Offset = EltSize * cast<ConstantSDNode>(Idx)->getZExtValue();
9005     SDValue OffsetVal = DAG.getConstant(Offset, TLI.getPointerTy());
9006
9007     SDValue ScalarAddr = DAG.getNode(ISD::ADD, dl, Idx.getValueType(), OffsetVal, StackPtr);
9008
9009     // Load the scalar.
9010     SDValue LoadScalar = DAG.getLoad(Extract->getValueType(0), dl, Ch, ScalarAddr,
9011                           NULL, 0, false, false, 0);
9012
9013     // Replace the exact with the load.
9014     DAG.ReplaceAllUsesOfValueWith(SDValue(Extract, 0), LoadScalar);
9015   }
9016
9017   // The replacement was made in place; don't return anything.
9018   return SDValue();
9019 }
9020
9021 /// PerformSELECTCombine - Do target-specific dag combines on SELECT nodes.
9022 static SDValue PerformSELECTCombine(SDNode *N, SelectionDAG &DAG,
9023                                     const X86Subtarget *Subtarget) {
9024   DebugLoc DL = N->getDebugLoc();
9025   SDValue Cond = N->getOperand(0);
9026   // Get the LHS/RHS of the select.
9027   SDValue LHS = N->getOperand(1);
9028   SDValue RHS = N->getOperand(2);
9029
9030   // If we have SSE[12] support, try to form min/max nodes. SSE min/max
9031   // instructions match the semantics of the common C idiom x<y?x:y but not
9032   // x<=y?x:y, because of how they handle negative zero (which can be
9033   // ignored in unsafe-math mode).
9034   if (Subtarget->hasSSE2() &&
9035       (LHS.getValueType() == MVT::f32 || LHS.getValueType() == MVT::f64) &&
9036       Cond.getOpcode() == ISD::SETCC) {
9037     ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
9038
9039     unsigned Opcode = 0;
9040     // Check for x CC y ? x : y.
9041     if (DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
9042         DAG.isEqualTo(RHS, Cond.getOperand(1))) {
9043       switch (CC) {
9044       default: break;
9045       case ISD::SETULT:
9046         // Converting this to a min would handle NaNs incorrectly, and swapping
9047         // the operands would cause it to handle comparisons between positive
9048         // and negative zero incorrectly.
9049         if (!FiniteOnlyFPMath() &&
9050             (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))) {
9051           if (!UnsafeFPMath &&
9052               !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
9053             break;
9054           std::swap(LHS, RHS);
9055         }
9056         Opcode = X86ISD::FMIN;
9057         break;
9058       case ISD::SETOLE:
9059         // Converting this to a min would handle comparisons between positive
9060         // and negative zero incorrectly.
9061         if (!UnsafeFPMath &&
9062             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
9063           break;
9064         Opcode = X86ISD::FMIN;
9065         break;
9066       case ISD::SETULE:
9067         // Converting this to a min would handle both negative zeros and NaNs
9068         // incorrectly, but we can swap the operands to fix both.
9069         std::swap(LHS, RHS);
9070       case ISD::SETOLT:
9071       case ISD::SETLT:
9072       case ISD::SETLE:
9073         Opcode = X86ISD::FMIN;
9074         break;
9075
9076       case ISD::SETOGE:
9077         // Converting this to a max would handle comparisons between positive
9078         // and negative zero incorrectly.
9079         if (!UnsafeFPMath &&
9080             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(LHS))
9081           break;
9082         Opcode = X86ISD::FMAX;
9083         break;
9084       case ISD::SETUGT:
9085         // Converting this to a max would handle NaNs incorrectly, and swapping
9086         // the operands would cause it to handle comparisons between positive
9087         // and negative zero incorrectly.
9088         if (!FiniteOnlyFPMath() &&
9089             (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))) {
9090           if (!UnsafeFPMath &&
9091               !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
9092             break;
9093           std::swap(LHS, RHS);
9094         }
9095         Opcode = X86ISD::FMAX;
9096         break;
9097       case ISD::SETUGE:
9098         // Converting this to a max would handle both negative zeros and NaNs
9099         // incorrectly, but we can swap the operands to fix both.
9100         std::swap(LHS, RHS);
9101       case ISD::SETOGT:
9102       case ISD::SETGT:
9103       case ISD::SETGE:
9104         Opcode = X86ISD::FMAX;
9105         break;
9106       }
9107     // Check for x CC y ? y : x -- a min/max with reversed arms.
9108     } else if (DAG.isEqualTo(LHS, Cond.getOperand(1)) &&
9109                DAG.isEqualTo(RHS, Cond.getOperand(0))) {
9110       switch (CC) {
9111       default: break;
9112       case ISD::SETOGE:
9113         // Converting this to a min would handle comparisons between positive
9114         // and negative zero incorrectly, and swapping the operands would
9115         // cause it to handle NaNs incorrectly.
9116         if (!UnsafeFPMath &&
9117             !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS))) {
9118           if (!FiniteOnlyFPMath() &&
9119               (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)))
9120             break;
9121           std::swap(LHS, RHS);
9122         }
9123         Opcode = X86ISD::FMIN;
9124         break;
9125       case ISD::SETUGT:
9126         // Converting this to a min would handle NaNs incorrectly.
9127         if (!UnsafeFPMath &&
9128             (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)))
9129           break;
9130         Opcode = X86ISD::FMIN;
9131         break;
9132       case ISD::SETUGE:
9133         // Converting this to a min would handle both negative zeros and NaNs
9134         // incorrectly, but we can swap the operands to fix both.
9135         std::swap(LHS, RHS);
9136       case ISD::SETOGT:
9137       case ISD::SETGT:
9138       case ISD::SETGE:
9139         Opcode = X86ISD::FMIN;
9140         break;
9141
9142       case ISD::SETULT:
9143         // Converting this to a max would handle NaNs incorrectly.
9144         if (!FiniteOnlyFPMath() &&
9145             (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)))
9146           break;
9147         Opcode = X86ISD::FMAX;
9148         break;
9149       case ISD::SETOLE:
9150         // Converting this to a max would handle comparisons between positive
9151         // and negative zero incorrectly, and swapping the operands would
9152         // cause it to handle NaNs incorrectly.
9153         if (!UnsafeFPMath &&
9154             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS)) {
9155           if (!FiniteOnlyFPMath() &&
9156               (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)))
9157             break;
9158           std::swap(LHS, RHS);
9159         }
9160         Opcode = X86ISD::FMAX;
9161         break;
9162       case ISD::SETULE:
9163         // Converting this to a max would handle both negative zeros and NaNs
9164         // incorrectly, but we can swap the operands to fix both.
9165         std::swap(LHS, RHS);
9166       case ISD::SETOLT:
9167       case ISD::SETLT:
9168       case ISD::SETLE:
9169         Opcode = X86ISD::FMAX;
9170         break;
9171       }
9172     }
9173
9174     if (Opcode)
9175       return DAG.getNode(Opcode, DL, N->getValueType(0), LHS, RHS);
9176   }
9177
9178   // If this is a select between two integer constants, try to do some
9179   // optimizations.
9180   if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(LHS)) {
9181     if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(RHS))
9182       // Don't do this for crazy integer types.
9183       if (DAG.getTargetLoweringInfo().isTypeLegal(LHS.getValueType())) {
9184         // If this is efficiently invertible, canonicalize the LHSC/RHSC values
9185         // so that TrueC (the true value) is larger than FalseC.
9186         bool NeedsCondInvert = false;
9187
9188         if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue()) &&
9189             // Efficiently invertible.
9190             (Cond.getOpcode() == ISD::SETCC ||  // setcc -> invertible.
9191              (Cond.getOpcode() == ISD::XOR &&   // xor(X, C) -> invertible.
9192               isa<ConstantSDNode>(Cond.getOperand(1))))) {
9193           NeedsCondInvert = true;
9194           std::swap(TrueC, FalseC);
9195         }
9196
9197         // Optimize C ? 8 : 0 -> zext(C) << 3.  Likewise for any pow2/0.
9198         if (FalseC->getAPIntValue() == 0 &&
9199             TrueC->getAPIntValue().isPowerOf2()) {
9200           if (NeedsCondInvert) // Invert the condition if needed.
9201             Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
9202                                DAG.getConstant(1, Cond.getValueType()));
9203
9204           // Zero extend the condition if needed.
9205           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, LHS.getValueType(), Cond);
9206
9207           unsigned ShAmt = TrueC->getAPIntValue().logBase2();
9208           return DAG.getNode(ISD::SHL, DL, LHS.getValueType(), Cond,
9209                              DAG.getConstant(ShAmt, MVT::i8));
9210         }
9211
9212         // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.
9213         if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
9214           if (NeedsCondInvert) // Invert the condition if needed.
9215             Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
9216                                DAG.getConstant(1, Cond.getValueType()));
9217
9218           // Zero extend the condition if needed.
9219           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
9220                              FalseC->getValueType(0), Cond);
9221           return DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
9222                              SDValue(FalseC, 0));
9223         }
9224
9225         // Optimize cases that will turn into an LEA instruction.  This requires
9226         // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
9227         if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
9228           uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
9229           if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
9230
9231           bool isFastMultiplier = false;
9232           if (Diff < 10) {
9233             switch ((unsigned char)Diff) {
9234               default: break;
9235               case 1:  // result = add base, cond
9236               case 2:  // result = lea base(    , cond*2)
9237               case 3:  // result = lea base(cond, cond*2)
9238               case 4:  // result = lea base(    , cond*4)
9239               case 5:  // result = lea base(cond, cond*4)
9240               case 8:  // result = lea base(    , cond*8)
9241               case 9:  // result = lea base(cond, cond*8)
9242                 isFastMultiplier = true;
9243                 break;
9244             }
9245           }
9246
9247           if (isFastMultiplier) {
9248             APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
9249             if (NeedsCondInvert) // Invert the condition if needed.
9250               Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
9251                                  DAG.getConstant(1, Cond.getValueType()));
9252
9253             // Zero extend the condition if needed.
9254             Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
9255                                Cond);
9256             // Scale the condition by the difference.
9257             if (Diff != 1)
9258               Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
9259                                  DAG.getConstant(Diff, Cond.getValueType()));
9260
9261             // Add the base if non-zero.
9262             if (FalseC->getAPIntValue() != 0)
9263               Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
9264                                  SDValue(FalseC, 0));
9265             return Cond;
9266           }
9267         }
9268       }
9269   }
9270
9271   return SDValue();
9272 }
9273
9274 /// Optimize X86ISD::CMOV [LHS, RHS, CONDCODE (e.g. X86::COND_NE), CONDVAL]
9275 static SDValue PerformCMOVCombine(SDNode *N, SelectionDAG &DAG,
9276                                   TargetLowering::DAGCombinerInfo &DCI) {
9277   DebugLoc DL = N->getDebugLoc();
9278
9279   // If the flag operand isn't dead, don't touch this CMOV.
9280   if (N->getNumValues() == 2 && !SDValue(N, 1).use_empty())
9281     return SDValue();
9282
9283   // If this is a select between two integer constants, try to do some
9284   // optimizations.  Note that the operands are ordered the opposite of SELECT
9285   // operands.
9286   if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(N->getOperand(1))) {
9287     if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(N->getOperand(0))) {
9288       // Canonicalize the TrueC/FalseC values so that TrueC (the true value) is
9289       // larger than FalseC (the false value).
9290       X86::CondCode CC = (X86::CondCode)N->getConstantOperandVal(2);
9291
9292       if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue())) {
9293         CC = X86::GetOppositeBranchCondition(CC);
9294         std::swap(TrueC, FalseC);
9295       }
9296
9297       // Optimize C ? 8 : 0 -> zext(setcc(C)) << 3.  Likewise for any pow2/0.
9298       // This is efficient for any integer data type (including i8/i16) and
9299       // shift amount.
9300       if (FalseC->getAPIntValue() == 0 && TrueC->getAPIntValue().isPowerOf2()) {
9301         SDValue Cond = N->getOperand(3);
9302         Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
9303                            DAG.getConstant(CC, MVT::i8), Cond);
9304
9305         // Zero extend the condition if needed.
9306         Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, TrueC->getValueType(0), Cond);
9307
9308         unsigned ShAmt = TrueC->getAPIntValue().logBase2();
9309         Cond = DAG.getNode(ISD::SHL, DL, Cond.getValueType(), Cond,
9310                            DAG.getConstant(ShAmt, MVT::i8));
9311         if (N->getNumValues() == 2)  // Dead flag value?
9312           return DCI.CombineTo(N, Cond, SDValue());
9313         return Cond;
9314       }
9315
9316       // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.  This is efficient
9317       // for any integer data type, including i8/i16.
9318       if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
9319         SDValue Cond = N->getOperand(3);
9320         Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
9321                            DAG.getConstant(CC, MVT::i8), Cond);
9322
9323         // Zero extend the condition if needed.
9324         Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
9325                            FalseC->getValueType(0), Cond);
9326         Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
9327                            SDValue(FalseC, 0));
9328
9329         if (N->getNumValues() == 2)  // Dead flag value?
9330           return DCI.CombineTo(N, Cond, SDValue());
9331         return Cond;
9332       }
9333
9334       // Optimize cases that will turn into an LEA instruction.  This requires
9335       // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
9336       if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
9337         uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
9338         if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
9339
9340         bool isFastMultiplier = false;
9341         if (Diff < 10) {
9342           switch ((unsigned char)Diff) {
9343           default: break;
9344           case 1:  // result = add base, cond
9345           case 2:  // result = lea base(    , cond*2)
9346           case 3:  // result = lea base(cond, cond*2)
9347           case 4:  // result = lea base(    , cond*4)
9348           case 5:  // result = lea base(cond, cond*4)
9349           case 8:  // result = lea base(    , cond*8)
9350           case 9:  // result = lea base(cond, cond*8)
9351             isFastMultiplier = true;
9352             break;
9353           }
9354         }
9355
9356         if (isFastMultiplier) {
9357           APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
9358           SDValue Cond = N->getOperand(3);
9359           Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
9360                              DAG.getConstant(CC, MVT::i8), Cond);
9361           // Zero extend the condition if needed.
9362           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
9363                              Cond);
9364           // Scale the condition by the difference.
9365           if (Diff != 1)
9366             Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
9367                                DAG.getConstant(Diff, Cond.getValueType()));
9368
9369           // Add the base if non-zero.
9370           if (FalseC->getAPIntValue() != 0)
9371             Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
9372                                SDValue(FalseC, 0));
9373           if (N->getNumValues() == 2)  // Dead flag value?
9374             return DCI.CombineTo(N, Cond, SDValue());
9375           return Cond;
9376         }
9377       }
9378     }
9379   }
9380   return SDValue();
9381 }
9382
9383
9384 /// PerformMulCombine - Optimize a single multiply with constant into two
9385 /// in order to implement it with two cheaper instructions, e.g.
9386 /// LEA + SHL, LEA + LEA.
9387 static SDValue PerformMulCombine(SDNode *N, SelectionDAG &DAG,
9388                                  TargetLowering::DAGCombinerInfo &DCI) {
9389   if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
9390     return SDValue();
9391
9392   EVT VT = N->getValueType(0);
9393   if (VT != MVT::i64)
9394     return SDValue();
9395
9396   ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
9397   if (!C)
9398     return SDValue();
9399   uint64_t MulAmt = C->getZExtValue();
9400   if (isPowerOf2_64(MulAmt) || MulAmt == 3 || MulAmt == 5 || MulAmt == 9)
9401     return SDValue();
9402
9403   uint64_t MulAmt1 = 0;
9404   uint64_t MulAmt2 = 0;
9405   if ((MulAmt % 9) == 0) {
9406     MulAmt1 = 9;
9407     MulAmt2 = MulAmt / 9;
9408   } else if ((MulAmt % 5) == 0) {
9409     MulAmt1 = 5;
9410     MulAmt2 = MulAmt / 5;
9411   } else if ((MulAmt % 3) == 0) {
9412     MulAmt1 = 3;
9413     MulAmt2 = MulAmt / 3;
9414   }
9415   if (MulAmt2 &&
9416       (isPowerOf2_64(MulAmt2) || MulAmt2 == 3 || MulAmt2 == 5 || MulAmt2 == 9)){
9417     DebugLoc DL = N->getDebugLoc();
9418
9419     if (isPowerOf2_64(MulAmt2) &&
9420         !(N->hasOneUse() && N->use_begin()->getOpcode() == ISD::ADD))
9421       // If second multiplifer is pow2, issue it first. We want the multiply by
9422       // 3, 5, or 9 to be folded into the addressing mode unless the lone use
9423       // is an add.
9424       std::swap(MulAmt1, MulAmt2);
9425
9426     SDValue NewMul;
9427     if (isPowerOf2_64(MulAmt1))
9428       NewMul = DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
9429                            DAG.getConstant(Log2_64(MulAmt1), MVT::i8));
9430     else
9431       NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, N->getOperand(0),
9432                            DAG.getConstant(MulAmt1, VT));
9433
9434     if (isPowerOf2_64(MulAmt2))
9435       NewMul = DAG.getNode(ISD::SHL, DL, VT, NewMul,
9436                            DAG.getConstant(Log2_64(MulAmt2), MVT::i8));
9437     else
9438       NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, NewMul,
9439                            DAG.getConstant(MulAmt2, VT));
9440
9441     // Do not add new nodes to DAG combiner worklist.
9442     DCI.CombineTo(N, NewMul, false);
9443   }
9444   return SDValue();
9445 }
9446
9447 static SDValue PerformSHLCombine(SDNode *N, SelectionDAG &DAG) {
9448   SDValue N0 = N->getOperand(0);
9449   SDValue N1 = N->getOperand(1);
9450   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
9451   EVT VT = N0.getValueType();
9452
9453   // fold (shl (and (setcc_c), c1), c2) -> (and setcc_c, (c1 << c2))
9454   // since the result of setcc_c is all zero's or all ones.
9455   if (N1C && N0.getOpcode() == ISD::AND &&
9456       N0.getOperand(1).getOpcode() == ISD::Constant) {
9457     SDValue N00 = N0.getOperand(0);
9458     if (N00.getOpcode() == X86ISD::SETCC_CARRY ||
9459         ((N00.getOpcode() == ISD::ANY_EXTEND ||
9460           N00.getOpcode() == ISD::ZERO_EXTEND) &&
9461          N00.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY)) {
9462       APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
9463       APInt ShAmt = N1C->getAPIntValue();
9464       Mask = Mask.shl(ShAmt);
9465       if (Mask != 0)
9466         return DAG.getNode(ISD::AND, N->getDebugLoc(), VT,
9467                            N00, DAG.getConstant(Mask, VT));
9468     }
9469   }
9470
9471   return SDValue();
9472 }
9473
9474 /// PerformShiftCombine - Transforms vector shift nodes to use vector shifts
9475 ///                       when possible.
9476 static SDValue PerformShiftCombine(SDNode* N, SelectionDAG &DAG,
9477                                    const X86Subtarget *Subtarget) {
9478   EVT VT = N->getValueType(0);
9479   if (!VT.isVector() && VT.isInteger() &&
9480       N->getOpcode() == ISD::SHL)
9481     return PerformSHLCombine(N, DAG);
9482
9483   // On X86 with SSE2 support, we can transform this to a vector shift if
9484   // all elements are shifted by the same amount.  We can't do this in legalize
9485   // because the a constant vector is typically transformed to a constant pool
9486   // so we have no knowledge of the shift amount.
9487   if (!Subtarget->hasSSE2())
9488     return SDValue();
9489
9490   if (VT != MVT::v2i64 && VT != MVT::v4i32 && VT != MVT::v8i16)
9491     return SDValue();
9492
9493   SDValue ShAmtOp = N->getOperand(1);
9494   EVT EltVT = VT.getVectorElementType();
9495   DebugLoc DL = N->getDebugLoc();
9496   SDValue BaseShAmt = SDValue();
9497   if (ShAmtOp.getOpcode() == ISD::BUILD_VECTOR) {
9498     unsigned NumElts = VT.getVectorNumElements();
9499     unsigned i = 0;
9500     for (; i != NumElts; ++i) {
9501       SDValue Arg = ShAmtOp.getOperand(i);
9502       if (Arg.getOpcode() == ISD::UNDEF) continue;
9503       BaseShAmt = Arg;
9504       break;
9505     }
9506     for (; i != NumElts; ++i) {
9507       SDValue Arg = ShAmtOp.getOperand(i);
9508       if (Arg.getOpcode() == ISD::UNDEF) continue;
9509       if (Arg != BaseShAmt) {
9510         return SDValue();
9511       }
9512     }
9513   } else if (ShAmtOp.getOpcode() == ISD::VECTOR_SHUFFLE &&
9514              cast<ShuffleVectorSDNode>(ShAmtOp)->isSplat()) {
9515     SDValue InVec = ShAmtOp.getOperand(0);
9516     if (InVec.getOpcode() == ISD::BUILD_VECTOR) {
9517       unsigned NumElts = InVec.getValueType().getVectorNumElements();
9518       unsigned i = 0;
9519       for (; i != NumElts; ++i) {
9520         SDValue Arg = InVec.getOperand(i);
9521         if (Arg.getOpcode() == ISD::UNDEF) continue;
9522         BaseShAmt = Arg;
9523         break;
9524       }
9525     } else if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT) {
9526        if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(InVec.getOperand(2))) {
9527          unsigned SplatIdx= cast<ShuffleVectorSDNode>(ShAmtOp)->getSplatIndex();
9528          if (C->getZExtValue() == SplatIdx)
9529            BaseShAmt = InVec.getOperand(1);
9530        }
9531     }
9532     if (BaseShAmt.getNode() == 0)
9533       BaseShAmt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, EltVT, ShAmtOp,
9534                               DAG.getIntPtrConstant(0));
9535   } else
9536     return SDValue();
9537
9538   // The shift amount is an i32.
9539   if (EltVT.bitsGT(MVT::i32))
9540     BaseShAmt = DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, BaseShAmt);
9541   else if (EltVT.bitsLT(MVT::i32))
9542     BaseShAmt = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, BaseShAmt);
9543
9544   // The shift amount is identical so we can do a vector shift.
9545   SDValue  ValOp = N->getOperand(0);
9546   switch (N->getOpcode()) {
9547   default:
9548     llvm_unreachable("Unknown shift opcode!");
9549     break;
9550   case ISD::SHL:
9551     if (VT == MVT::v2i64)
9552       return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
9553                          DAG.getConstant(Intrinsic::x86_sse2_pslli_q, MVT::i32),
9554                          ValOp, BaseShAmt);
9555     if (VT == MVT::v4i32)
9556       return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
9557                          DAG.getConstant(Intrinsic::x86_sse2_pslli_d, MVT::i32),
9558                          ValOp, BaseShAmt);
9559     if (VT == MVT::v8i16)
9560       return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
9561                          DAG.getConstant(Intrinsic::x86_sse2_pslli_w, MVT::i32),
9562                          ValOp, BaseShAmt);
9563     break;
9564   case ISD::SRA:
9565     if (VT == MVT::v4i32)
9566       return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
9567                          DAG.getConstant(Intrinsic::x86_sse2_psrai_d, MVT::i32),
9568                          ValOp, BaseShAmt);
9569     if (VT == MVT::v8i16)
9570       return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
9571                          DAG.getConstant(Intrinsic::x86_sse2_psrai_w, MVT::i32),
9572                          ValOp, BaseShAmt);
9573     break;
9574   case ISD::SRL:
9575     if (VT == MVT::v2i64)
9576       return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
9577                          DAG.getConstant(Intrinsic::x86_sse2_psrli_q, MVT::i32),
9578                          ValOp, BaseShAmt);
9579     if (VT == MVT::v4i32)
9580       return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
9581                          DAG.getConstant(Intrinsic::x86_sse2_psrli_d, MVT::i32),
9582                          ValOp, BaseShAmt);
9583     if (VT ==  MVT::v8i16)
9584       return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
9585                          DAG.getConstant(Intrinsic::x86_sse2_psrli_w, MVT::i32),
9586                          ValOp, BaseShAmt);
9587     break;
9588   }
9589   return SDValue();
9590 }
9591
9592 static SDValue PerformOrCombine(SDNode *N, SelectionDAG &DAG,
9593                                 const X86Subtarget *Subtarget) {
9594   EVT VT = N->getValueType(0);
9595   if (VT != MVT::i64 || !Subtarget->is64Bit())
9596     return SDValue();
9597
9598   // fold (or (x << c) | (y >> (64 - c))) ==> (shld64 x, y, c)
9599   SDValue N0 = N->getOperand(0);
9600   SDValue N1 = N->getOperand(1);
9601   if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL)
9602     std::swap(N0, N1);
9603   if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL)
9604     return SDValue();
9605
9606   SDValue ShAmt0 = N0.getOperand(1);
9607   if (ShAmt0.getValueType() != MVT::i8)
9608     return SDValue();
9609   SDValue ShAmt1 = N1.getOperand(1);
9610   if (ShAmt1.getValueType() != MVT::i8)
9611     return SDValue();
9612   if (ShAmt0.getOpcode() == ISD::TRUNCATE)
9613     ShAmt0 = ShAmt0.getOperand(0);
9614   if (ShAmt1.getOpcode() == ISD::TRUNCATE)
9615     ShAmt1 = ShAmt1.getOperand(0);
9616
9617   DebugLoc DL = N->getDebugLoc();
9618   unsigned Opc = X86ISD::SHLD;
9619   SDValue Op0 = N0.getOperand(0);
9620   SDValue Op1 = N1.getOperand(0);
9621   if (ShAmt0.getOpcode() == ISD::SUB) {
9622     Opc = X86ISD::SHRD;
9623     std::swap(Op0, Op1);
9624     std::swap(ShAmt0, ShAmt1);
9625   }
9626
9627   if (ShAmt1.getOpcode() == ISD::SUB) {
9628     SDValue Sum = ShAmt1.getOperand(0);
9629     if (ConstantSDNode *SumC = dyn_cast<ConstantSDNode>(Sum)) {
9630       if (SumC->getSExtValue() == 64 &&
9631           ShAmt1.getOperand(1) == ShAmt0)
9632         return DAG.getNode(Opc, DL, VT,
9633                            Op0, Op1,
9634                            DAG.getNode(ISD::TRUNCATE, DL,
9635                                        MVT::i8, ShAmt0));
9636     }
9637   } else if (ConstantSDNode *ShAmt1C = dyn_cast<ConstantSDNode>(ShAmt1)) {
9638     ConstantSDNode *ShAmt0C = dyn_cast<ConstantSDNode>(ShAmt0);
9639     if (ShAmt0C &&
9640         ShAmt0C->getSExtValue() + ShAmt1C->getSExtValue() == 64)
9641       return DAG.getNode(Opc, DL, VT,
9642                          N0.getOperand(0), N1.getOperand(0),
9643                          DAG.getNode(ISD::TRUNCATE, DL,
9644                                        MVT::i8, ShAmt0));
9645   }
9646
9647   return SDValue();
9648 }
9649
9650 /// PerformSTORECombine - Do target-specific dag combines on STORE nodes.
9651 static SDValue PerformSTORECombine(SDNode *N, SelectionDAG &DAG,
9652                                    const X86Subtarget *Subtarget) {
9653   // Turn load->store of MMX types into GPR load/stores.  This avoids clobbering
9654   // the FP state in cases where an emms may be missing.
9655   // A preferable solution to the general problem is to figure out the right
9656   // places to insert EMMS.  This qualifies as a quick hack.
9657
9658   // Similarly, turn load->store of i64 into double load/stores in 32-bit mode.
9659   StoreSDNode *St = cast<StoreSDNode>(N);
9660   EVT VT = St->getValue().getValueType();
9661   if (VT.getSizeInBits() != 64)
9662     return SDValue();
9663
9664   const Function *F = DAG.getMachineFunction().getFunction();
9665   bool NoImplicitFloatOps = F->hasFnAttr(Attribute::NoImplicitFloat);
9666   bool F64IsLegal = !UseSoftFloat && !NoImplicitFloatOps
9667     && Subtarget->hasSSE2();
9668   if ((VT.isVector() ||
9669        (VT == MVT::i64 && F64IsLegal && !Subtarget->is64Bit())) &&
9670       isa<LoadSDNode>(St->getValue()) &&
9671       !cast<LoadSDNode>(St->getValue())->isVolatile() &&
9672       St->getChain().hasOneUse() && !St->isVolatile()) {
9673     SDNode* LdVal = St->getValue().getNode();
9674     LoadSDNode *Ld = 0;
9675     int TokenFactorIndex = -1;
9676     SmallVector<SDValue, 8> Ops;
9677     SDNode* ChainVal = St->getChain().getNode();
9678     // Must be a store of a load.  We currently handle two cases:  the load
9679     // is a direct child, and it's under an intervening TokenFactor.  It is
9680     // possible to dig deeper under nested TokenFactors.
9681     if (ChainVal == LdVal)
9682       Ld = cast<LoadSDNode>(St->getChain());
9683     else if (St->getValue().hasOneUse() &&
9684              ChainVal->getOpcode() == ISD::TokenFactor) {
9685       for (unsigned i=0, e = ChainVal->getNumOperands(); i != e; ++i) {
9686         if (ChainVal->getOperand(i).getNode() == LdVal) {
9687           TokenFactorIndex = i;
9688           Ld = cast<LoadSDNode>(St->getValue());
9689         } else
9690           Ops.push_back(ChainVal->getOperand(i));
9691       }
9692     }
9693
9694     if (!Ld || !ISD::isNormalLoad(Ld))
9695       return SDValue();
9696
9697     // If this is not the MMX case, i.e. we are just turning i64 load/store
9698     // into f64 load/store, avoid the transformation if there are multiple
9699     // uses of the loaded value.
9700     if (!VT.isVector() && !Ld->hasNUsesOfValue(1, 0))
9701       return SDValue();
9702
9703     DebugLoc LdDL = Ld->getDebugLoc();
9704     DebugLoc StDL = N->getDebugLoc();
9705     // If we are a 64-bit capable x86, lower to a single movq load/store pair.
9706     // Otherwise, if it's legal to use f64 SSE instructions, use f64 load/store
9707     // pair instead.
9708     if (Subtarget->is64Bit() || F64IsLegal) {
9709       EVT LdVT = Subtarget->is64Bit() ? MVT::i64 : MVT::f64;
9710       SDValue NewLd = DAG.getLoad(LdVT, LdDL, Ld->getChain(),
9711                                   Ld->getBasePtr(), Ld->getSrcValue(),
9712                                   Ld->getSrcValueOffset(), Ld->isVolatile(),
9713                                   Ld->isNonTemporal(), Ld->getAlignment());
9714       SDValue NewChain = NewLd.getValue(1);
9715       if (TokenFactorIndex != -1) {
9716         Ops.push_back(NewChain);
9717         NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, &Ops[0],
9718                                Ops.size());
9719       }
9720       return DAG.getStore(NewChain, StDL, NewLd, St->getBasePtr(),
9721                           St->getSrcValue(), St->getSrcValueOffset(),
9722                           St->isVolatile(), St->isNonTemporal(),
9723                           St->getAlignment());
9724     }
9725
9726     // Otherwise, lower to two pairs of 32-bit loads / stores.
9727     SDValue LoAddr = Ld->getBasePtr();
9728     SDValue HiAddr = DAG.getNode(ISD::ADD, LdDL, MVT::i32, LoAddr,
9729                                  DAG.getConstant(4, MVT::i32));
9730
9731     SDValue LoLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), LoAddr,
9732                                Ld->getSrcValue(), Ld->getSrcValueOffset(),
9733                                Ld->isVolatile(), Ld->isNonTemporal(),
9734                                Ld->getAlignment());
9735     SDValue HiLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), HiAddr,
9736                                Ld->getSrcValue(), Ld->getSrcValueOffset()+4,
9737                                Ld->isVolatile(), Ld->isNonTemporal(),
9738                                MinAlign(Ld->getAlignment(), 4));
9739
9740     SDValue NewChain = LoLd.getValue(1);
9741     if (TokenFactorIndex != -1) {
9742       Ops.push_back(LoLd);
9743       Ops.push_back(HiLd);
9744       NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, &Ops[0],
9745                              Ops.size());
9746     }
9747
9748     LoAddr = St->getBasePtr();
9749     HiAddr = DAG.getNode(ISD::ADD, StDL, MVT::i32, LoAddr,
9750                          DAG.getConstant(4, MVT::i32));
9751
9752     SDValue LoSt = DAG.getStore(NewChain, StDL, LoLd, LoAddr,
9753                                 St->getSrcValue(), St->getSrcValueOffset(),
9754                                 St->isVolatile(), St->isNonTemporal(),
9755                                 St->getAlignment());
9756     SDValue HiSt = DAG.getStore(NewChain, StDL, HiLd, HiAddr,
9757                                 St->getSrcValue(),
9758                                 St->getSrcValueOffset() + 4,
9759                                 St->isVolatile(),
9760                                 St->isNonTemporal(),
9761                                 MinAlign(St->getAlignment(), 4));
9762     return DAG.getNode(ISD::TokenFactor, StDL, MVT::Other, LoSt, HiSt);
9763   }
9764   return SDValue();
9765 }
9766
9767 /// PerformFORCombine - Do target-specific dag combines on X86ISD::FOR and
9768 /// X86ISD::FXOR nodes.
9769 static SDValue PerformFORCombine(SDNode *N, SelectionDAG &DAG) {
9770   assert(N->getOpcode() == X86ISD::FOR || N->getOpcode() == X86ISD::FXOR);
9771   // F[X]OR(0.0, x) -> x
9772   // F[X]OR(x, 0.0) -> x
9773   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
9774     if (C->getValueAPF().isPosZero())
9775       return N->getOperand(1);
9776   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
9777     if (C->getValueAPF().isPosZero())
9778       return N->getOperand(0);
9779   return SDValue();
9780 }
9781
9782 /// PerformFANDCombine - Do target-specific dag combines on X86ISD::FAND nodes.
9783 static SDValue PerformFANDCombine(SDNode *N, SelectionDAG &DAG) {
9784   // FAND(0.0, x) -> 0.0
9785   // FAND(x, 0.0) -> 0.0
9786   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
9787     if (C->getValueAPF().isPosZero())
9788       return N->getOperand(0);
9789   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
9790     if (C->getValueAPF().isPosZero())
9791       return N->getOperand(1);
9792   return SDValue();
9793 }
9794
9795 static SDValue PerformBTCombine(SDNode *N,
9796                                 SelectionDAG &DAG,
9797                                 TargetLowering::DAGCombinerInfo &DCI) {
9798   // BT ignores high bits in the bit index operand.
9799   SDValue Op1 = N->getOperand(1);
9800   if (Op1.hasOneUse()) {
9801     unsigned BitWidth = Op1.getValueSizeInBits();
9802     APInt DemandedMask = APInt::getLowBitsSet(BitWidth, Log2_32(BitWidth));
9803     APInt KnownZero, KnownOne;
9804     TargetLowering::TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(),
9805                                           !DCI.isBeforeLegalizeOps());
9806     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9807     if (TLO.ShrinkDemandedConstant(Op1, DemandedMask) ||
9808         TLI.SimplifyDemandedBits(Op1, DemandedMask, KnownZero, KnownOne, TLO))
9809       DCI.CommitTargetLoweringOpt(TLO);
9810   }
9811   return SDValue();
9812 }
9813
9814 static SDValue PerformVZEXT_MOVLCombine(SDNode *N, SelectionDAG &DAG) {
9815   SDValue Op = N->getOperand(0);
9816   if (Op.getOpcode() == ISD::BIT_CONVERT)
9817     Op = Op.getOperand(0);
9818   EVT VT = N->getValueType(0), OpVT = Op.getValueType();
9819   if (Op.getOpcode() == X86ISD::VZEXT_LOAD &&
9820       VT.getVectorElementType().getSizeInBits() ==
9821       OpVT.getVectorElementType().getSizeInBits()) {
9822     return DAG.getNode(ISD::BIT_CONVERT, N->getDebugLoc(), VT, Op);
9823   }
9824   return SDValue();
9825 }
9826
9827 // On X86 and X86-64, atomic operations are lowered to locked instructions.
9828 // Locked instructions, in turn, have implicit fence semantics (all memory
9829 // operations are flushed before issuing the locked instruction, and the
9830 // are not buffered), so we can fold away the common pattern of
9831 // fence-atomic-fence.
9832 static SDValue PerformMEMBARRIERCombine(SDNode* N, SelectionDAG &DAG) {
9833   SDValue atomic = N->getOperand(0);
9834   switch (atomic.getOpcode()) {
9835     case ISD::ATOMIC_CMP_SWAP:
9836     case ISD::ATOMIC_SWAP:
9837     case ISD::ATOMIC_LOAD_ADD:
9838     case ISD::ATOMIC_LOAD_SUB:
9839     case ISD::ATOMIC_LOAD_AND:
9840     case ISD::ATOMIC_LOAD_OR:
9841     case ISD::ATOMIC_LOAD_XOR:
9842     case ISD::ATOMIC_LOAD_NAND:
9843     case ISD::ATOMIC_LOAD_MIN:
9844     case ISD::ATOMIC_LOAD_MAX:
9845     case ISD::ATOMIC_LOAD_UMIN:
9846     case ISD::ATOMIC_LOAD_UMAX:
9847       break;
9848     default:
9849       return SDValue();
9850   }
9851
9852   SDValue fence = atomic.getOperand(0);
9853   if (fence.getOpcode() != ISD::MEMBARRIER)
9854     return SDValue();
9855
9856   switch (atomic.getOpcode()) {
9857     case ISD::ATOMIC_CMP_SWAP:
9858       return DAG.UpdateNodeOperands(atomic, fence.getOperand(0),
9859                                     atomic.getOperand(1), atomic.getOperand(2),
9860                                     atomic.getOperand(3));
9861     case ISD::ATOMIC_SWAP:
9862     case ISD::ATOMIC_LOAD_ADD:
9863     case ISD::ATOMIC_LOAD_SUB:
9864     case ISD::ATOMIC_LOAD_AND:
9865     case ISD::ATOMIC_LOAD_OR:
9866     case ISD::ATOMIC_LOAD_XOR:
9867     case ISD::ATOMIC_LOAD_NAND:
9868     case ISD::ATOMIC_LOAD_MIN:
9869     case ISD::ATOMIC_LOAD_MAX:
9870     case ISD::ATOMIC_LOAD_UMIN:
9871     case ISD::ATOMIC_LOAD_UMAX:
9872       return DAG.UpdateNodeOperands(atomic, fence.getOperand(0),
9873                                     atomic.getOperand(1), atomic.getOperand(2));
9874     default:
9875       return SDValue();
9876   }
9877 }
9878
9879 static SDValue PerformZExtCombine(SDNode *N, SelectionDAG &DAG) {
9880   // (i32 zext (and (i8  x86isd::setcc_carry), 1)) ->
9881   //           (and (i32 x86isd::setcc_carry), 1)
9882   // This eliminates the zext. This transformation is necessary because
9883   // ISD::SETCC is always legalized to i8.
9884   DebugLoc dl = N->getDebugLoc();
9885   SDValue N0 = N->getOperand(0);
9886   EVT VT = N->getValueType(0);
9887   if (N0.getOpcode() == ISD::AND &&
9888       N0.hasOneUse() &&
9889       N0.getOperand(0).hasOneUse()) {
9890     SDValue N00 = N0.getOperand(0);
9891     if (N00.getOpcode() != X86ISD::SETCC_CARRY)
9892       return SDValue();
9893     ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
9894     if (!C || C->getZExtValue() != 1)
9895       return SDValue();
9896     return DAG.getNode(ISD::AND, dl, VT,
9897                        DAG.getNode(X86ISD::SETCC_CARRY, dl, VT,
9898                                    N00.getOperand(0), N00.getOperand(1)),
9899                        DAG.getConstant(1, VT));
9900   }
9901
9902   return SDValue();
9903 }
9904
9905 SDValue X86TargetLowering::PerformDAGCombine(SDNode *N,
9906                                              DAGCombinerInfo &DCI) const {
9907   SelectionDAG &DAG = DCI.DAG;
9908   switch (N->getOpcode()) {
9909   default: break;
9910   case ISD::VECTOR_SHUFFLE: return PerformShuffleCombine(N, DAG, *this);
9911   case ISD::EXTRACT_VECTOR_ELT:
9912                         return PerformEXTRACT_VECTOR_ELTCombine(N, DAG, *this);
9913   case ISD::SELECT:         return PerformSELECTCombine(N, DAG, Subtarget);
9914   case X86ISD::CMOV:        return PerformCMOVCombine(N, DAG, DCI);
9915   case ISD::MUL:            return PerformMulCombine(N, DAG, DCI);
9916   case ISD::SHL:
9917   case ISD::SRA:
9918   case ISD::SRL:            return PerformShiftCombine(N, DAG, Subtarget);
9919   case ISD::OR:             return PerformOrCombine(N, DAG, Subtarget);
9920   case ISD::STORE:          return PerformSTORECombine(N, DAG, Subtarget);
9921   case X86ISD::FXOR:
9922   case X86ISD::FOR:         return PerformFORCombine(N, DAG);
9923   case X86ISD::FAND:        return PerformFANDCombine(N, DAG);
9924   case X86ISD::BT:          return PerformBTCombine(N, DAG, DCI);
9925   case X86ISD::VZEXT_MOVL:  return PerformVZEXT_MOVLCombine(N, DAG);
9926   case ISD::MEMBARRIER:     return PerformMEMBARRIERCombine(N, DAG);
9927   case ISD::ZERO_EXTEND:    return PerformZExtCombine(N, DAG);
9928   }
9929
9930   return SDValue();
9931 }
9932
9933 /// isTypeDesirableForOp - Return true if the target has native support for
9934 /// the specified value type and it is 'desirable' to use the type for the
9935 /// given node type. e.g. On x86 i16 is legal, but undesirable since i16
9936 /// instruction encodings are longer and some i16 instructions are slow.
9937 bool X86TargetLowering::isTypeDesirableForOp(unsigned Opc, EVT VT) const {
9938   if (!isTypeLegal(VT))
9939     return false;
9940   if (!Subtarget->shouldPromote16Bit() || VT != MVT::i16)
9941     return true;
9942
9943   switch (Opc) {
9944   default:
9945     return true;
9946   case ISD::LOAD:
9947   case ISD::SIGN_EXTEND:
9948   case ISD::ZERO_EXTEND:
9949   case ISD::ANY_EXTEND:
9950   case ISD::SHL:
9951   case ISD::SRA:
9952   case ISD::SRL:
9953   case ISD::SUB:
9954   case ISD::ADD:
9955   case ISD::MUL:
9956   case ISD::AND:
9957   case ISD::OR:
9958   case ISD::XOR:
9959     return false;
9960   }
9961 }
9962
9963 static bool MayFoldLoad(SDValue Op) {
9964   return Op.hasOneUse() && ISD::isNormalLoad(Op.getNode());
9965 }
9966
9967 static bool MayFoldIntoStore(SDValue Op) {
9968   return Op.hasOneUse() && ISD::isNormalStore(*Op.getNode()->use_begin());
9969 }
9970
9971 /// IsDesirableToPromoteOp - This method query the target whether it is
9972 /// beneficial for dag combiner to promote the specified node. If true, it
9973 /// should return the desired promotion type by reference.
9974 bool X86TargetLowering::IsDesirableToPromoteOp(SDValue Op, EVT &PVT) const {
9975   if (!Subtarget->shouldPromote16Bit())
9976     return false;
9977
9978   EVT VT = Op.getValueType();
9979   if (VT != MVT::i16)
9980     return false;
9981
9982   bool Promote = false;
9983   bool Commute = false;
9984   switch (Op.getOpcode()) {
9985   default: break;
9986   case ISD::LOAD: {
9987     LoadSDNode *LD = cast<LoadSDNode>(Op);
9988     // If the non-extending load has a single use and it's not live out, then it
9989     // might be folded.
9990     if (LD->getExtensionType() == ISD::NON_EXTLOAD &&
9991         Op.hasOneUse() &&
9992         Op.getNode()->use_begin()->getOpcode() != ISD::CopyToReg)
9993       return false;
9994     Promote = true;
9995     break;
9996   }
9997   case ISD::SIGN_EXTEND:
9998   case ISD::ZERO_EXTEND:
9999   case ISD::ANY_EXTEND:
10000     Promote = true;
10001     break;
10002   case ISD::SHL:
10003   case ISD::SRA:
10004   case ISD::SRL: {
10005     SDValue N0 = Op.getOperand(0);
10006     // Look out for (store (shl (load), x)).
10007     if (MayFoldLoad(N0) && MayFoldIntoStore(Op))
10008       return false;
10009     Promote = true;
10010     break;
10011   }
10012   case ISD::ADD:
10013   case ISD::MUL:
10014   case ISD::AND:
10015   case ISD::OR:
10016   case ISD::XOR:
10017     Commute = true;
10018     // fallthrough
10019   case ISD::SUB: {
10020     SDValue N0 = Op.getOperand(0);
10021     SDValue N1 = Op.getOperand(1);
10022     if (!Commute && MayFoldLoad(N1))
10023       return false;
10024     // Avoid disabling potential load folding opportunities.
10025     if (MayFoldLoad(N0) && (!isa<ConstantSDNode>(N1) || MayFoldIntoStore(Op)))
10026       return false;
10027     if (MayFoldLoad(N1) && (!isa<ConstantSDNode>(N0) || MayFoldIntoStore(Op)))
10028       return false;
10029     Promote = true;
10030   }
10031   }
10032
10033   PVT = MVT::i32;
10034   return Promote;
10035 }
10036
10037 //===----------------------------------------------------------------------===//
10038 //                           X86 Inline Assembly Support
10039 //===----------------------------------------------------------------------===//
10040
10041 static bool LowerToBSwap(CallInst *CI) {
10042   // FIXME: this should verify that we are targetting a 486 or better.  If not,
10043   // we will turn this bswap into something that will be lowered to logical ops
10044   // instead of emitting the bswap asm.  For now, we don't support 486 or lower
10045   // so don't worry about this.
10046
10047   // Verify this is a simple bswap.
10048   if (CI->getNumOperands() != 2 ||
10049       CI->getType() != CI->getOperand(1)->getType() ||
10050       !CI->getType()->isIntegerTy())
10051     return false;
10052
10053   const IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
10054   if (!Ty || Ty->getBitWidth() % 16 != 0)
10055     return false;
10056
10057   // Okay, we can do this xform, do so now.
10058   const Type *Tys[] = { Ty };
10059   Module *M = CI->getParent()->getParent()->getParent();
10060   Constant *Int = Intrinsic::getDeclaration(M, Intrinsic::bswap, Tys, 1);
10061
10062   Value *Op = CI->getOperand(1);
10063   Op = CallInst::Create(Int, Op, CI->getName(), CI);
10064
10065   CI->replaceAllUsesWith(Op);
10066   CI->eraseFromParent();
10067   return true;
10068 }
10069
10070 bool X86TargetLowering::ExpandInlineAsm(CallInst *CI) const {
10071   InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue());
10072   std::vector<InlineAsm::ConstraintInfo> Constraints = IA->ParseConstraints();
10073
10074   std::string AsmStr = IA->getAsmString();
10075
10076   // TODO: should remove alternatives from the asmstring: "foo {a|b}" -> "foo a"
10077   SmallVector<StringRef, 4> AsmPieces;
10078   SplitString(AsmStr, AsmPieces, "\n");  // ; as separator?
10079
10080   switch (AsmPieces.size()) {
10081   default: return false;
10082   case 1:
10083     AsmStr = AsmPieces[0];
10084     AsmPieces.clear();
10085     SplitString(AsmStr, AsmPieces, " \t");  // Split with whitespace.
10086
10087     // bswap $0
10088     if (AsmPieces.size() == 2 &&
10089         (AsmPieces[0] == "bswap" ||
10090          AsmPieces[0] == "bswapq" ||
10091          AsmPieces[0] == "bswapl") &&
10092         (AsmPieces[1] == "$0" ||
10093          AsmPieces[1] == "${0:q}")) {
10094       // No need to check constraints, nothing other than the equivalent of
10095       // "=r,0" would be valid here.
10096       return LowerToBSwap(CI);
10097     }
10098     // rorw $$8, ${0:w}  -->  llvm.bswap.i16
10099     if (CI->getType()->isIntegerTy(16) &&
10100         AsmPieces.size() == 3 &&
10101         (AsmPieces[0] == "rorw" || AsmPieces[0] == "rolw") &&
10102         AsmPieces[1] == "$$8," &&
10103         AsmPieces[2] == "${0:w}" &&
10104         IA->getConstraintString().compare(0, 5, "=r,0,") == 0) {
10105       AsmPieces.clear();
10106       const std::string &Constraints = IA->getConstraintString();
10107       SplitString(StringRef(Constraints).substr(5), AsmPieces, ",");
10108       std::sort(AsmPieces.begin(), AsmPieces.end());
10109       if (AsmPieces.size() == 4 &&
10110           AsmPieces[0] == "~{cc}" &&
10111           AsmPieces[1] == "~{dirflag}" &&
10112           AsmPieces[2] == "~{flags}" &&
10113           AsmPieces[3] == "~{fpsr}") {
10114         return LowerToBSwap(CI);
10115       }
10116     }
10117     break;
10118   case 3:
10119     if (CI->getType()->isIntegerTy(64) &&
10120         Constraints.size() >= 2 &&
10121         Constraints[0].Codes.size() == 1 && Constraints[0].Codes[0] == "A" &&
10122         Constraints[1].Codes.size() == 1 && Constraints[1].Codes[0] == "0") {
10123       // bswap %eax / bswap %edx / xchgl %eax, %edx  -> llvm.bswap.i64
10124       SmallVector<StringRef, 4> Words;
10125       SplitString(AsmPieces[0], Words, " \t");
10126       if (Words.size() == 2 && Words[0] == "bswap" && Words[1] == "%eax") {
10127         Words.clear();
10128         SplitString(AsmPieces[1], Words, " \t");
10129         if (Words.size() == 2 && Words[0] == "bswap" && Words[1] == "%edx") {
10130           Words.clear();
10131           SplitString(AsmPieces[2], Words, " \t,");
10132           if (Words.size() == 3 && Words[0] == "xchgl" && Words[1] == "%eax" &&
10133               Words[2] == "%edx") {
10134             return LowerToBSwap(CI);
10135           }
10136         }
10137       }
10138     }
10139     break;
10140   }
10141   return false;
10142 }
10143
10144
10145
10146 /// getConstraintType - Given a constraint letter, return the type of
10147 /// constraint it is for this target.
10148 X86TargetLowering::ConstraintType
10149 X86TargetLowering::getConstraintType(const std::string &Constraint) const {
10150   if (Constraint.size() == 1) {
10151     switch (Constraint[0]) {
10152     case 'A':
10153       return C_Register;
10154     case 'f':
10155     case 'r':
10156     case 'R':
10157     case 'l':
10158     case 'q':
10159     case 'Q':
10160     case 'x':
10161     case 'y':
10162     case 'Y':
10163       return C_RegisterClass;
10164     case 'e':
10165     case 'Z':
10166       return C_Other;
10167     default:
10168       break;
10169     }
10170   }
10171   return TargetLowering::getConstraintType(Constraint);
10172 }
10173
10174 /// LowerXConstraint - try to replace an X constraint, which matches anything,
10175 /// with another that has more specific requirements based on the type of the
10176 /// corresponding operand.
10177 const char *X86TargetLowering::
10178 LowerXConstraint(EVT ConstraintVT) const {
10179   // FP X constraints get lowered to SSE1/2 registers if available, otherwise
10180   // 'f' like normal targets.
10181   if (ConstraintVT.isFloatingPoint()) {
10182     if (Subtarget->hasSSE2())
10183       return "Y";
10184     if (Subtarget->hasSSE1())
10185       return "x";
10186   }
10187
10188   return TargetLowering::LowerXConstraint(ConstraintVT);
10189 }
10190
10191 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
10192 /// vector.  If it is invalid, don't add anything to Ops.
10193 void X86TargetLowering::LowerAsmOperandForConstraint(SDValue Op,
10194                                                      char Constraint,
10195                                                      bool hasMemory,
10196                                                      std::vector<SDValue>&Ops,
10197                                                      SelectionDAG &DAG) const {
10198   SDValue Result(0, 0);
10199
10200   switch (Constraint) {
10201   default: break;
10202   case 'I':
10203     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
10204       if (C->getZExtValue() <= 31) {
10205         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
10206         break;
10207       }
10208     }
10209     return;
10210   case 'J':
10211     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
10212       if (C->getZExtValue() <= 63) {
10213         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
10214         break;
10215       }
10216     }
10217     return;
10218   case 'K':
10219     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
10220       if ((int8_t)C->getSExtValue() == C->getSExtValue()) {
10221         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
10222         break;
10223       }
10224     }
10225     return;
10226   case 'N':
10227     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
10228       if (C->getZExtValue() <= 255) {
10229         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
10230         break;
10231       }
10232     }
10233     return;
10234   case 'e': {
10235     // 32-bit signed value
10236     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
10237       const ConstantInt *CI = C->getConstantIntValue();
10238       if (CI->isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
10239                                   C->getSExtValue())) {
10240         // Widen to 64 bits here to get it sign extended.
10241         Result = DAG.getTargetConstant(C->getSExtValue(), MVT::i64);
10242         break;
10243       }
10244     // FIXME gcc accepts some relocatable values here too, but only in certain
10245     // memory models; it's complicated.
10246     }
10247     return;
10248   }
10249   case 'Z': {
10250     // 32-bit unsigned value
10251     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
10252       const ConstantInt *CI = C->getConstantIntValue();
10253       if (CI->isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
10254                                   C->getZExtValue())) {
10255         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
10256         break;
10257       }
10258     }
10259     // FIXME gcc accepts some relocatable values here too, but only in certain
10260     // memory models; it's complicated.
10261     return;
10262   }
10263   case 'i': {
10264     // Literal immediates are always ok.
10265     if (ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op)) {
10266       // Widen to 64 bits here to get it sign extended.
10267       Result = DAG.getTargetConstant(CST->getSExtValue(), MVT::i64);
10268       break;
10269     }
10270
10271     // If we are in non-pic codegen mode, we allow the address of a global (with
10272     // an optional displacement) to be used with 'i'.
10273     GlobalAddressSDNode *GA = 0;
10274     int64_t Offset = 0;
10275
10276     // Match either (GA), (GA+C), (GA+C1+C2), etc.
10277     while (1) {
10278       if ((GA = dyn_cast<GlobalAddressSDNode>(Op))) {
10279         Offset += GA->getOffset();
10280         break;
10281       } else if (Op.getOpcode() == ISD::ADD) {
10282         if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
10283           Offset += C->getZExtValue();
10284           Op = Op.getOperand(0);
10285           continue;
10286         }
10287       } else if (Op.getOpcode() == ISD::SUB) {
10288         if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
10289           Offset += -C->getZExtValue();
10290           Op = Op.getOperand(0);
10291           continue;
10292         }
10293       }
10294
10295       // Otherwise, this isn't something we can handle, reject it.
10296       return;
10297     }
10298
10299     const GlobalValue *GV = GA->getGlobal();
10300     // If we require an extra load to get this address, as in PIC mode, we
10301     // can't accept it.
10302     if (isGlobalStubReference(Subtarget->ClassifyGlobalReference(GV,
10303                                                         getTargetMachine())))
10304       return;
10305
10306     if (hasMemory)
10307       Op = LowerGlobalAddress(GV, Op.getDebugLoc(), Offset, DAG);
10308     else
10309       Op = DAG.getTargetGlobalAddress(GV, GA->getValueType(0), Offset);
10310     Result = Op;
10311     break;
10312   }
10313   }
10314
10315   if (Result.getNode()) {
10316     Ops.push_back(Result);
10317     return;
10318   }
10319   return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, hasMemory,
10320                                                       Ops, DAG);
10321 }
10322
10323 std::vector<unsigned> X86TargetLowering::
10324 getRegClassForInlineAsmConstraint(const std::string &Constraint,
10325                                   EVT VT) const {
10326   if (Constraint.size() == 1) {
10327     // FIXME: not handling fp-stack yet!
10328     switch (Constraint[0]) {      // GCC X86 Constraint Letters
10329     default: break;  // Unknown constraint letter
10330     case 'q':   // GENERAL_REGS in 64-bit mode, Q_REGS in 32-bit mode.
10331       if (Subtarget->is64Bit()) {
10332         if (VT == MVT::i32)
10333           return make_vector<unsigned>(X86::EAX, X86::EDX, X86::ECX, X86::EBX,
10334                                        X86::ESI, X86::EDI, X86::R8D, X86::R9D,
10335                                        X86::R10D,X86::R11D,X86::R12D,
10336                                        X86::R13D,X86::R14D,X86::R15D,
10337                                        X86::EBP, X86::ESP, 0);
10338         else if (VT == MVT::i16)
10339           return make_vector<unsigned>(X86::AX,  X86::DX,  X86::CX, X86::BX,
10340                                        X86::SI,  X86::DI,  X86::R8W,X86::R9W,
10341                                        X86::R10W,X86::R11W,X86::R12W,
10342                                        X86::R13W,X86::R14W,X86::R15W,
10343                                        X86::BP,  X86::SP, 0);
10344         else if (VT == MVT::i8)
10345           return make_vector<unsigned>(X86::AL,  X86::DL,  X86::CL, X86::BL,
10346                                        X86::SIL, X86::DIL, X86::R8B,X86::R9B,
10347                                        X86::R10B,X86::R11B,X86::R12B,
10348                                        X86::R13B,X86::R14B,X86::R15B,
10349                                        X86::BPL, X86::SPL, 0);
10350
10351         else if (VT == MVT::i64)
10352           return make_vector<unsigned>(X86::RAX, X86::RDX, X86::RCX, X86::RBX,
10353                                        X86::RSI, X86::RDI, X86::R8,  X86::R9,
10354                                        X86::R10, X86::R11, X86::R12,
10355                                        X86::R13, X86::R14, X86::R15,
10356                                        X86::RBP, X86::RSP, 0);
10357
10358         break;
10359       }
10360       // 32-bit fallthrough
10361     case 'Q':   // Q_REGS
10362       if (VT == MVT::i32)
10363         return make_vector<unsigned>(X86::EAX, X86::EDX, X86::ECX, X86::EBX, 0);
10364       else if (VT == MVT::i16)
10365         return make_vector<unsigned>(X86::AX, X86::DX, X86::CX, X86::BX, 0);
10366       else if (VT == MVT::i8)
10367         return make_vector<unsigned>(X86::AL, X86::DL, X86::CL, X86::BL, 0);
10368       else if (VT == MVT::i64)
10369         return make_vector<unsigned>(X86::RAX, X86::RDX, X86::RCX, X86::RBX, 0);
10370       break;
10371     }
10372   }
10373
10374   return std::vector<unsigned>();
10375 }
10376
10377 std::pair<unsigned, const TargetRegisterClass*>
10378 X86TargetLowering::getRegForInlineAsmConstraint(const std::string &Constraint,
10379                                                 EVT VT) const {
10380   // First, see if this is a constraint that directly corresponds to an LLVM
10381   // register class.
10382   if (Constraint.size() == 1) {
10383     // GCC Constraint Letters
10384     switch (Constraint[0]) {
10385     default: break;
10386     case 'r':   // GENERAL_REGS
10387     case 'l':   // INDEX_REGS
10388       if (VT == MVT::i8)
10389         return std::make_pair(0U, X86::GR8RegisterClass);
10390       if (VT == MVT::i16)
10391         return std::make_pair(0U, X86::GR16RegisterClass);
10392       if (VT == MVT::i32 || !Subtarget->is64Bit())
10393         return std::make_pair(0U, X86::GR32RegisterClass);
10394       return std::make_pair(0U, X86::GR64RegisterClass);
10395     case 'R':   // LEGACY_REGS
10396       if (VT == MVT::i8)
10397         return std::make_pair(0U, X86::GR8_NOREXRegisterClass);
10398       if (VT == MVT::i16)
10399         return std::make_pair(0U, X86::GR16_NOREXRegisterClass);
10400       if (VT == MVT::i32 || !Subtarget->is64Bit())
10401         return std::make_pair(0U, X86::GR32_NOREXRegisterClass);
10402       return std::make_pair(0U, X86::GR64_NOREXRegisterClass);
10403     case 'f':  // FP Stack registers.
10404       // If SSE is enabled for this VT, use f80 to ensure the isel moves the
10405       // value to the correct fpstack register class.
10406       if (VT == MVT::f32 && !isScalarFPTypeInSSEReg(VT))
10407         return std::make_pair(0U, X86::RFP32RegisterClass);
10408       if (VT == MVT::f64 && !isScalarFPTypeInSSEReg(VT))
10409         return std::make_pair(0U, X86::RFP64RegisterClass);
10410       return std::make_pair(0U, X86::RFP80RegisterClass);
10411     case 'y':   // MMX_REGS if MMX allowed.
10412       if (!Subtarget->hasMMX()) break;
10413       return std::make_pair(0U, X86::VR64RegisterClass);
10414     case 'Y':   // SSE_REGS if SSE2 allowed
10415       if (!Subtarget->hasSSE2()) break;
10416       // FALL THROUGH.
10417     case 'x':   // SSE_REGS if SSE1 allowed
10418       if (!Subtarget->hasSSE1()) break;
10419
10420       switch (VT.getSimpleVT().SimpleTy) {
10421       default: break;
10422       // Scalar SSE types.
10423       case MVT::f32:
10424       case MVT::i32:
10425         return std::make_pair(0U, X86::FR32RegisterClass);
10426       case MVT::f64:
10427       case MVT::i64:
10428         return std::make_pair(0U, X86::FR64RegisterClass);
10429       // Vector types.
10430       case MVT::v16i8:
10431       case MVT::v8i16:
10432       case MVT::v4i32:
10433       case MVT::v2i64:
10434       case MVT::v4f32:
10435       case MVT::v2f64:
10436         return std::make_pair(0U, X86::VR128RegisterClass);
10437       }
10438       break;
10439     }
10440   }
10441
10442   // Use the default implementation in TargetLowering to convert the register
10443   // constraint into a member of a register class.
10444   std::pair<unsigned, const TargetRegisterClass*> Res;
10445   Res = TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
10446
10447   // Not found as a standard register?
10448   if (Res.second == 0) {
10449     // Map st(0) -> st(7) -> ST0
10450     if (Constraint.size() == 7 && Constraint[0] == '{' &&
10451         tolower(Constraint[1]) == 's' &&
10452         tolower(Constraint[2]) == 't' &&
10453         Constraint[3] == '(' &&
10454         (Constraint[4] >= '0' && Constraint[4] <= '7') &&
10455         Constraint[5] == ')' &&
10456         Constraint[6] == '}') {
10457
10458       Res.first = X86::ST0+Constraint[4]-'0';
10459       Res.second = X86::RFP80RegisterClass;
10460       return Res;
10461     }
10462
10463     // GCC allows "st(0)" to be called just plain "st".
10464     if (StringRef("{st}").equals_lower(Constraint)) {
10465       Res.first = X86::ST0;
10466       Res.second = X86::RFP80RegisterClass;
10467       return Res;
10468     }
10469
10470     // flags -> EFLAGS
10471     if (StringRef("{flags}").equals_lower(Constraint)) {
10472       Res.first = X86::EFLAGS;
10473       Res.second = X86::CCRRegisterClass;
10474       return Res;
10475     }
10476
10477     // 'A' means EAX + EDX.
10478     if (Constraint == "A") {
10479       Res.first = X86::EAX;
10480       Res.second = X86::GR32_ADRegisterClass;
10481       return Res;
10482     }
10483     return Res;
10484   }
10485
10486   // Otherwise, check to see if this is a register class of the wrong value
10487   // type.  For example, we want to map "{ax},i32" -> {eax}, we don't want it to
10488   // turn into {ax},{dx}.
10489   if (Res.second->hasType(VT))
10490     return Res;   // Correct type already, nothing to do.
10491
10492   // All of the single-register GCC register classes map their values onto
10493   // 16-bit register pieces "ax","dx","cx","bx","si","di","bp","sp".  If we
10494   // really want an 8-bit or 32-bit register, map to the appropriate register
10495   // class and return the appropriate register.
10496   if (Res.second == X86::GR16RegisterClass) {
10497     if (VT == MVT::i8) {
10498       unsigned DestReg = 0;
10499       switch (Res.first) {
10500       default: break;
10501       case X86::AX: DestReg = X86::AL; break;
10502       case X86::DX: DestReg = X86::DL; break;
10503       case X86::CX: DestReg = X86::CL; break;
10504       case X86::BX: DestReg = X86::BL; break;
10505       }
10506       if (DestReg) {
10507         Res.first = DestReg;
10508         Res.second = X86::GR8RegisterClass;
10509       }
10510     } else if (VT == MVT::i32) {
10511       unsigned DestReg = 0;
10512       switch (Res.first) {
10513       default: break;
10514       case X86::AX: DestReg = X86::EAX; break;
10515       case X86::DX: DestReg = X86::EDX; break;
10516       case X86::CX: DestReg = X86::ECX; break;
10517       case X86::BX: DestReg = X86::EBX; break;
10518       case X86::SI: DestReg = X86::ESI; break;
10519       case X86::DI: DestReg = X86::EDI; break;
10520       case X86::BP: DestReg = X86::EBP; break;
10521       case X86::SP: DestReg = X86::ESP; break;
10522       }
10523       if (DestReg) {
10524         Res.first = DestReg;
10525         Res.second = X86::GR32RegisterClass;
10526       }
10527     } else if (VT == MVT::i64) {
10528       unsigned DestReg = 0;
10529       switch (Res.first) {
10530       default: break;
10531       case X86::AX: DestReg = X86::RAX; break;
10532       case X86::DX: DestReg = X86::RDX; break;
10533       case X86::CX: DestReg = X86::RCX; break;
10534       case X86::BX: DestReg = X86::RBX; break;
10535       case X86::SI: DestReg = X86::RSI; break;
10536       case X86::DI: DestReg = X86::RDI; break;
10537       case X86::BP: DestReg = X86::RBP; break;
10538       case X86::SP: DestReg = X86::RSP; break;
10539       }
10540       if (DestReg) {
10541         Res.first = DestReg;
10542         Res.second = X86::GR64RegisterClass;
10543       }
10544     }
10545   } else if (Res.second == X86::FR32RegisterClass ||
10546              Res.second == X86::FR64RegisterClass ||
10547              Res.second == X86::VR128RegisterClass) {
10548     // Handle references to XMM physical registers that got mapped into the
10549     // wrong class.  This can happen with constraints like {xmm0} where the
10550     // target independent register mapper will just pick the first match it can
10551     // find, ignoring the required type.
10552     if (VT == MVT::f32)
10553       Res.second = X86::FR32RegisterClass;
10554     else if (VT == MVT::f64)
10555       Res.second = X86::FR64RegisterClass;
10556     else if (X86::VR128RegisterClass->hasType(VT))
10557       Res.second = X86::VR128RegisterClass;
10558   }
10559
10560   return Res;
10561 }