X86 supports i8/i16 overflow ops (except i8 multiplies), we should
[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 "X86ShuffleDecode.h"
20 #include "X86TargetMachine.h"
21 #include "X86TargetObjectFile.h"
22 #include "llvm/CallingConv.h"
23 #include "llvm/Constants.h"
24 #include "llvm/DerivedTypes.h"
25 #include "llvm/GlobalAlias.h"
26 #include "llvm/GlobalVariable.h"
27 #include "llvm/Function.h"
28 #include "llvm/Instructions.h"
29 #include "llvm/Intrinsics.h"
30 #include "llvm/LLVMContext.h"
31 #include "llvm/CodeGen/MachineFrameInfo.h"
32 #include "llvm/CodeGen/MachineFunction.h"
33 #include "llvm/CodeGen/MachineInstrBuilder.h"
34 #include "llvm/CodeGen/MachineJumpTableInfo.h"
35 #include "llvm/CodeGen/MachineModuleInfo.h"
36 #include "llvm/CodeGen/MachineRegisterInfo.h"
37 #include "llvm/CodeGen/PseudoSourceValue.h"
38 #include "llvm/MC/MCAsmInfo.h"
39 #include "llvm/MC/MCContext.h"
40 #include "llvm/MC/MCExpr.h"
41 #include "llvm/MC/MCSymbol.h"
42 #include "llvm/ADT/BitVector.h"
43 #include "llvm/ADT/SmallSet.h"
44 #include "llvm/ADT/Statistic.h"
45 #include "llvm/ADT/StringExtras.h"
46 #include "llvm/ADT/VectorExtras.h"
47 #include "llvm/Support/CommandLine.h"
48 #include "llvm/Support/Debug.h"
49 #include "llvm/Support/Dwarf.h"
50 #include "llvm/Support/ErrorHandling.h"
51 #include "llvm/Support/MathExtras.h"
52 #include "llvm/Support/raw_ostream.h"
53 using namespace llvm;
54 using namespace dwarf;
55
56 STATISTIC(NumTailCalls, "Number of tail calls");
57
58 static cl::opt<bool>
59 DisableMMX("disable-mmx", cl::Hidden, cl::desc("Disable use of MMX"));
60
61 // Forward declarations.
62 static SDValue getMOVL(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
63                        SDValue V2);
64
65 static TargetLoweringObjectFile *createTLOF(X86TargetMachine &TM) {
66
67   bool is64Bit = TM.getSubtarget<X86Subtarget>().is64Bit();
68
69   if (TM.getSubtarget<X86Subtarget>().isTargetDarwin()) {
70     if (is64Bit) return new X8664_MachoTargetObjectFile();
71     return new TargetLoweringObjectFileMachO();
72   } else if (TM.getSubtarget<X86Subtarget>().isTargetELF() ){
73     if (is64Bit) return new X8664_ELFTargetObjectFile(TM);
74     return new X8632_ELFTargetObjectFile(TM);
75   } else if (TM.getSubtarget<X86Subtarget>().isTargetCOFF()) {
76     return new TargetLoweringObjectFileCOFF();
77   }
78   llvm_unreachable("unknown subtarget type");
79 }
80
81 X86TargetLowering::X86TargetLowering(X86TargetMachine &TM)
82   : TargetLowering(TM, createTLOF(TM)) {
83   Subtarget = &TM.getSubtarget<X86Subtarget>();
84   X86ScalarSSEf64 = Subtarget->hasXMMInt();
85   X86ScalarSSEf32 = Subtarget->hasXMM();
86   X86StackPtr = Subtarget->is64Bit() ? X86::RSP : X86::ESP;
87
88   RegInfo = TM.getRegisterInfo();
89   TD = getTargetData();
90
91   // Set up the TargetLowering object.
92   static MVT IntVTs[] = { MVT::i8, MVT::i16, MVT::i32, MVT::i64 };
93
94   // X86 is weird, it always uses i8 for shift amounts and setcc results.
95   setShiftAmountType(MVT::i8);
96   setBooleanContents(ZeroOrOneBooleanContent);
97   setSchedulingPreference(Sched::RegPressure);
98   setStackPointerRegisterToSaveRestore(X86StackPtr);
99
100   if (Subtarget->isTargetWindows() && !Subtarget->isTargetCygMing()) {
101     // Setup Windows compiler runtime calls.
102     setLibcallName(RTLIB::SDIV_I64, "_alldiv");
103     setLibcallName(RTLIB::UDIV_I64, "_aulldiv");
104     setLibcallName(RTLIB::FPTOUINT_F64_I64, "_ftol2");
105     setLibcallName(RTLIB::FPTOUINT_F32_I64, "_ftol2");
106     setLibcallCallingConv(RTLIB::SDIV_I64, CallingConv::X86_StdCall);
107     setLibcallCallingConv(RTLIB::UDIV_I64, CallingConv::X86_StdCall);
108     setLibcallCallingConv(RTLIB::FPTOUINT_F64_I64, CallingConv::C);
109     setLibcallCallingConv(RTLIB::FPTOUINT_F32_I64, CallingConv::C);
110   }
111
112   if (Subtarget->isTargetDarwin()) {
113     // Darwin should use _setjmp/_longjmp instead of setjmp/longjmp.
114     setUseUnderscoreSetJmp(false);
115     setUseUnderscoreLongJmp(false);
116   } else if (Subtarget->isTargetMingw()) {
117     // MS runtime is weird: it exports _setjmp, but longjmp!
118     setUseUnderscoreSetJmp(true);
119     setUseUnderscoreLongJmp(false);
120   } else {
121     setUseUnderscoreSetJmp(true);
122     setUseUnderscoreLongJmp(true);
123   }
124
125   // Set up the register classes.
126   addRegisterClass(MVT::i8, X86::GR8RegisterClass);
127   addRegisterClass(MVT::i16, X86::GR16RegisterClass);
128   addRegisterClass(MVT::i32, X86::GR32RegisterClass);
129   if (Subtarget->is64Bit())
130     addRegisterClass(MVT::i64, X86::GR64RegisterClass);
131
132   setLoadExtAction(ISD::SEXTLOAD, MVT::i1, Promote);
133
134   // We don't accept any truncstore of integer registers.
135   setTruncStoreAction(MVT::i64, MVT::i32, Expand);
136   setTruncStoreAction(MVT::i64, MVT::i16, Expand);
137   setTruncStoreAction(MVT::i64, MVT::i8 , Expand);
138   setTruncStoreAction(MVT::i32, MVT::i16, Expand);
139   setTruncStoreAction(MVT::i32, MVT::i8 , Expand);
140   setTruncStoreAction(MVT::i16, MVT::i8,  Expand);
141
142   // SETOEQ and SETUNE require checking two conditions.
143   setCondCodeAction(ISD::SETOEQ, MVT::f32, Expand);
144   setCondCodeAction(ISD::SETOEQ, MVT::f64, Expand);
145   setCondCodeAction(ISD::SETOEQ, MVT::f80, Expand);
146   setCondCodeAction(ISD::SETUNE, MVT::f32, Expand);
147   setCondCodeAction(ISD::SETUNE, MVT::f64, Expand);
148   setCondCodeAction(ISD::SETUNE, MVT::f80, Expand);
149
150   // Promote all UINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have this
151   // operation.
152   setOperationAction(ISD::UINT_TO_FP       , MVT::i1   , Promote);
153   setOperationAction(ISD::UINT_TO_FP       , MVT::i8   , Promote);
154   setOperationAction(ISD::UINT_TO_FP       , MVT::i16  , Promote);
155
156   if (Subtarget->is64Bit()) {
157     setOperationAction(ISD::UINT_TO_FP     , MVT::i32  , Promote);
158     setOperationAction(ISD::UINT_TO_FP     , MVT::i64  , Expand);
159   } else if (!UseSoftFloat) {
160     // We have an algorithm for SSE2->double, and we turn this into a
161     // 64-bit FILD followed by conditional FADD for other targets.
162     setOperationAction(ISD::UINT_TO_FP     , MVT::i64  , Custom);
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::BITCAST        , MVT::f32  , Expand);
231     setOperationAction(ISD::BITCAST        , MVT::i32  , Expand);
232     if (Subtarget->is64Bit()) {
233       setOperationAction(ISD::BITCAST      , MVT::f64  , Expand);
234       // Without SSE, i64->f64 goes through memory.
235       setOperationAction(ISD::BITCAST      , MVT::i64  , Expand);
236     }
237   }
238
239   // Scalar integer divide and remainder are lowered to use operations that
240   // produce two results, to match the available instructions. This exposes
241   // the two-result form to trivial CSE, which is able to combine x/y and x%y
242   // into a single instruction.
243   //
244   // Scalar integer multiply-high is also lowered to use two-result
245   // operations, to match the available instructions. However, plain multiply
246   // (low) operations are left as Legal, as there are single-result
247   // instructions for this in x86. Using the two-result multiply instructions
248   // when both high and low results are needed must be arranged by dagcombine.
249   setOperationAction(ISD::MULHS           , MVT::i8    , Expand);
250   setOperationAction(ISD::MULHU           , MVT::i8    , Expand);
251   setOperationAction(ISD::SDIV            , MVT::i8    , Expand);
252   setOperationAction(ISD::UDIV            , MVT::i8    , Expand);
253   setOperationAction(ISD::SREM            , MVT::i8    , Expand);
254   setOperationAction(ISD::UREM            , MVT::i8    , Expand);
255   setOperationAction(ISD::MULHS           , MVT::i16   , Expand);
256   setOperationAction(ISD::MULHU           , MVT::i16   , Expand);
257   setOperationAction(ISD::SDIV            , MVT::i16   , Expand);
258   setOperationAction(ISD::UDIV            , MVT::i16   , Expand);
259   setOperationAction(ISD::SREM            , MVT::i16   , Expand);
260   setOperationAction(ISD::UREM            , MVT::i16   , Expand);
261   setOperationAction(ISD::MULHS           , MVT::i32   , Expand);
262   setOperationAction(ISD::MULHU           , MVT::i32   , Expand);
263   setOperationAction(ISD::SDIV            , MVT::i32   , Expand);
264   setOperationAction(ISD::UDIV            , MVT::i32   , Expand);
265   setOperationAction(ISD::SREM            , MVT::i32   , Expand);
266   setOperationAction(ISD::UREM            , MVT::i32   , Expand);
267   setOperationAction(ISD::MULHS           , MVT::i64   , Expand);
268   setOperationAction(ISD::MULHU           , MVT::i64   , Expand);
269   setOperationAction(ISD::SDIV            , MVT::i64   , Expand);
270   setOperationAction(ISD::UDIV            , MVT::i64   , Expand);
271   setOperationAction(ISD::SREM            , MVT::i64   , Expand);
272   setOperationAction(ISD::UREM            , MVT::i64   , Expand);
273
274   setOperationAction(ISD::BR_JT            , MVT::Other, Expand);
275   setOperationAction(ISD::BRCOND           , MVT::Other, Custom);
276   setOperationAction(ISD::BR_CC            , MVT::Other, Expand);
277   setOperationAction(ISD::SELECT_CC        , MVT::Other, Expand);
278   if (Subtarget->is64Bit())
279     setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i32, Legal);
280   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16  , Legal);
281   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8   , Legal);
282   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1   , Expand);
283   setOperationAction(ISD::FP_ROUND_INREG   , MVT::f32  , Expand);
284   setOperationAction(ISD::FREM             , MVT::f32  , Expand);
285   setOperationAction(ISD::FREM             , MVT::f64  , Expand);
286   setOperationAction(ISD::FREM             , MVT::f80  , Expand);
287   setOperationAction(ISD::FLT_ROUNDS_      , MVT::i32  , Custom);
288
289   setOperationAction(ISD::CTTZ             , MVT::i8   , Custom);
290   setOperationAction(ISD::CTLZ             , MVT::i8   , Custom);
291   setOperationAction(ISD::CTTZ             , MVT::i16  , Custom);
292   setOperationAction(ISD::CTLZ             , MVT::i16  , Custom);
293   setOperationAction(ISD::CTTZ             , MVT::i32  , Custom);
294   setOperationAction(ISD::CTLZ             , MVT::i32  , Custom);
295   if (Subtarget->is64Bit()) {
296     setOperationAction(ISD::CTTZ           , MVT::i64  , Custom);
297     setOperationAction(ISD::CTLZ           , MVT::i64  , Custom);
298   }
299
300   if (Subtarget->hasPOPCNT()) {
301     setOperationAction(ISD::CTPOP          , MVT::i8   , Promote);
302   } else {
303     setOperationAction(ISD::CTPOP          , MVT::i8   , Expand);
304     setOperationAction(ISD::CTPOP          , MVT::i16  , Expand);
305     setOperationAction(ISD::CTPOP          , MVT::i32  , Expand);
306     if (Subtarget->is64Bit())
307       setOperationAction(ISD::CTPOP        , MVT::i64  , Expand);
308   }
309
310   setOperationAction(ISD::READCYCLECOUNTER , MVT::i64  , Custom);
311   setOperationAction(ISD::BSWAP            , MVT::i16  , Expand);
312
313   // These should be promoted to a larger select which is supported.
314   setOperationAction(ISD::SELECT          , MVT::i1   , Promote);
315   // X86 wants to expand cmov itself.
316   setOperationAction(ISD::SELECT          , MVT::i8   , Custom);
317   setOperationAction(ISD::SELECT        , MVT::i16  , Custom);
318   setOperationAction(ISD::SELECT          , MVT::i32  , Custom);
319   setOperationAction(ISD::SELECT          , MVT::f32  , Custom);
320   setOperationAction(ISD::SELECT          , MVT::f64  , Custom);
321   setOperationAction(ISD::SELECT          , MVT::f80  , Custom);
322   setOperationAction(ISD::SETCC           , MVT::i8   , Custom);
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->hasXMM())
361     setOperationAction(ISD::PREFETCH      , MVT::Other, Legal);
362
363   // We may not have a libcall for MEMBARRIER so we should lower this.
364   setOperationAction(ISD::MEMBARRIER    , MVT::Other, Custom);
365
366   // On X86 and X86-64, atomic operations are lowered to locked instructions.
367   // Locked instructions, in turn, have implicit fence semantics (all memory
368   // operations are flushed before issuing the locked instruction, and they
369   // are not buffered), so we can fold away the common pattern of
370   // fence-atomic-fence.
371   setShouldFoldAtomicFences(true);
372
373   // Expand certain atomics
374   setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i8, Custom);
375   setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i16, Custom);
376   setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i32, Custom);
377   setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i64, Custom);
378
379   setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i8, Custom);
380   setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i16, Custom);
381   setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i32, Custom);
382   setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i64, Custom);
383
384   if (!Subtarget->is64Bit()) {
385     setOperationAction(ISD::ATOMIC_LOAD_ADD, MVT::i64, Custom);
386     setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i64, Custom);
387     setOperationAction(ISD::ATOMIC_LOAD_AND, MVT::i64, Custom);
388     setOperationAction(ISD::ATOMIC_LOAD_OR, MVT::i64, Custom);
389     setOperationAction(ISD::ATOMIC_LOAD_XOR, MVT::i64, Custom);
390     setOperationAction(ISD::ATOMIC_LOAD_NAND, MVT::i64, Custom);
391     setOperationAction(ISD::ATOMIC_SWAP, MVT::i64, Custom);
392   }
393
394   // FIXME - use subtarget debug flags
395   if (!Subtarget->isTargetDarwin() &&
396       !Subtarget->isTargetELF() &&
397       !Subtarget->isTargetCygMing()) {
398     setOperationAction(ISD::EH_LABEL, MVT::Other, Expand);
399   }
400
401   setOperationAction(ISD::EXCEPTIONADDR, MVT::i64, Expand);
402   setOperationAction(ISD::EHSELECTION,   MVT::i64, Expand);
403   setOperationAction(ISD::EXCEPTIONADDR, MVT::i32, Expand);
404   setOperationAction(ISD::EHSELECTION,   MVT::i32, Expand);
405   if (Subtarget->is64Bit()) {
406     setExceptionPointerRegister(X86::RAX);
407     setExceptionSelectorRegister(X86::RDX);
408   } else {
409     setExceptionPointerRegister(X86::EAX);
410     setExceptionSelectorRegister(X86::EDX);
411   }
412   setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i32, Custom);
413   setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i64, Custom);
414
415   setOperationAction(ISD::TRAMPOLINE, MVT::Other, Custom);
416
417   setOperationAction(ISD::TRAP, MVT::Other, Legal);
418
419   // VASTART needs to be custom lowered to use the VarArgsFrameIndex
420   setOperationAction(ISD::VASTART           , MVT::Other, Custom);
421   setOperationAction(ISD::VAEND             , MVT::Other, Expand);
422   if (Subtarget->is64Bit()) {
423     setOperationAction(ISD::VAARG           , MVT::Other, Custom);
424     setOperationAction(ISD::VACOPY          , MVT::Other, Custom);
425   } else {
426     setOperationAction(ISD::VAARG           , MVT::Other, Expand);
427     setOperationAction(ISD::VACOPY          , MVT::Other, Expand);
428   }
429
430   setOperationAction(ISD::STACKSAVE,          MVT::Other, Expand);
431   setOperationAction(ISD::STACKRESTORE,       MVT::Other, Expand);
432   if (Subtarget->is64Bit())
433     setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i64, Expand);
434   if (Subtarget->isTargetCygMing() || Subtarget->isTargetWindows())
435     setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Custom);
436   else
437     setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Expand);
438
439   if (!UseSoftFloat && X86ScalarSSEf64) {
440     // f32 and f64 use SSE.
441     // Set up the FP register classes.
442     addRegisterClass(MVT::f32, X86::FR32RegisterClass);
443     addRegisterClass(MVT::f64, X86::FR64RegisterClass);
444
445     // Use ANDPD to simulate FABS.
446     setOperationAction(ISD::FABS , MVT::f64, Custom);
447     setOperationAction(ISD::FABS , MVT::f32, Custom);
448
449     // Use XORP to simulate FNEG.
450     setOperationAction(ISD::FNEG , MVT::f64, Custom);
451     setOperationAction(ISD::FNEG , MVT::f32, Custom);
452
453     // Use ANDPD and ORPD to simulate FCOPYSIGN.
454     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
455     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
456
457     // We don't support sin/cos/fmod
458     setOperationAction(ISD::FSIN , MVT::f64, Expand);
459     setOperationAction(ISD::FCOS , MVT::f64, Expand);
460     setOperationAction(ISD::FSIN , MVT::f32, Expand);
461     setOperationAction(ISD::FCOS , MVT::f32, Expand);
462
463     // Expand FP immediates into loads from the stack, except for the special
464     // cases we handle.
465     addLegalFPImmediate(APFloat(+0.0)); // xorpd
466     addLegalFPImmediate(APFloat(+0.0f)); // xorps
467   } else if (!UseSoftFloat && X86ScalarSSEf32) {
468     // Use SSE for f32, x87 for f64.
469     // Set up the FP register classes.
470     addRegisterClass(MVT::f32, X86::FR32RegisterClass);
471     addRegisterClass(MVT::f64, X86::RFP64RegisterClass);
472
473     // Use ANDPS to simulate FABS.
474     setOperationAction(ISD::FABS , MVT::f32, Custom);
475
476     // Use XORP to simulate FNEG.
477     setOperationAction(ISD::FNEG , MVT::f32, Custom);
478
479     setOperationAction(ISD::UNDEF,     MVT::f64, Expand);
480
481     // Use ANDPS and ORPS to simulate FCOPYSIGN.
482     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
483     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
484
485     // We don't support sin/cos/fmod
486     setOperationAction(ISD::FSIN , MVT::f32, Expand);
487     setOperationAction(ISD::FCOS , MVT::f32, Expand);
488
489     // Special cases we handle for FP constants.
490     addLegalFPImmediate(APFloat(+0.0f)); // xorps
491     addLegalFPImmediate(APFloat(+0.0)); // FLD0
492     addLegalFPImmediate(APFloat(+1.0)); // FLD1
493     addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
494     addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
495
496     if (!UnsafeFPMath) {
497       setOperationAction(ISD::FSIN           , MVT::f64  , Expand);
498       setOperationAction(ISD::FCOS           , MVT::f64  , Expand);
499     }
500   } else if (!UseSoftFloat) {
501     // f32 and f64 in x87.
502     // Set up the FP register classes.
503     addRegisterClass(MVT::f64, X86::RFP64RegisterClass);
504     addRegisterClass(MVT::f32, X86::RFP32RegisterClass);
505
506     setOperationAction(ISD::UNDEF,     MVT::f64, Expand);
507     setOperationAction(ISD::UNDEF,     MVT::f32, Expand);
508     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
509     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand);
510
511     if (!UnsafeFPMath) {
512       setOperationAction(ISD::FSIN           , MVT::f64  , Expand);
513       setOperationAction(ISD::FCOS           , MVT::f64  , Expand);
514     }
515     addLegalFPImmediate(APFloat(+0.0)); // FLD0
516     addLegalFPImmediate(APFloat(+1.0)); // FLD1
517     addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
518     addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
519     addLegalFPImmediate(APFloat(+0.0f)); // FLD0
520     addLegalFPImmediate(APFloat(+1.0f)); // FLD1
521     addLegalFPImmediate(APFloat(-0.0f)); // FLD0/FCHS
522     addLegalFPImmediate(APFloat(-1.0f)); // FLD1/FCHS
523   }
524
525   // Long double always uses X87.
526   if (!UseSoftFloat) {
527     addRegisterClass(MVT::f80, X86::RFP80RegisterClass);
528     setOperationAction(ISD::UNDEF,     MVT::f80, Expand);
529     setOperationAction(ISD::FCOPYSIGN, MVT::f80, Expand);
530     {
531       APFloat TmpFlt = APFloat::getZero(APFloat::x87DoubleExtended);
532       addLegalFPImmediate(TmpFlt);  // FLD0
533       TmpFlt.changeSign();
534       addLegalFPImmediate(TmpFlt);  // FLD0/FCHS
535
536       bool ignored;
537       APFloat TmpFlt2(+1.0);
538       TmpFlt2.convert(APFloat::x87DoubleExtended, APFloat::rmNearestTiesToEven,
539                       &ignored);
540       addLegalFPImmediate(TmpFlt2);  // FLD1
541       TmpFlt2.changeSign();
542       addLegalFPImmediate(TmpFlt2);  // FLD1/FCHS
543     }
544
545     if (!UnsafeFPMath) {
546       setOperationAction(ISD::FSIN           , MVT::f80  , Expand);
547       setOperationAction(ISD::FCOS           , MVT::f80  , Expand);
548     }
549   }
550
551   // Always use a library call for pow.
552   setOperationAction(ISD::FPOW             , MVT::f32  , Expand);
553   setOperationAction(ISD::FPOW             , MVT::f64  , Expand);
554   setOperationAction(ISD::FPOW             , MVT::f80  , Expand);
555
556   setOperationAction(ISD::FLOG, MVT::f80, Expand);
557   setOperationAction(ISD::FLOG2, MVT::f80, Expand);
558   setOperationAction(ISD::FLOG10, MVT::f80, Expand);
559   setOperationAction(ISD::FEXP, MVT::f80, Expand);
560   setOperationAction(ISD::FEXP2, MVT::f80, Expand);
561
562   // First set operation action for all vector types to either promote
563   // (for widening) or expand (for scalarization). Then we will selectively
564   // turn on ones that can be effectively codegen'd.
565   for (unsigned VT = (unsigned)MVT::FIRST_VECTOR_VALUETYPE;
566        VT <= (unsigned)MVT::LAST_VECTOR_VALUETYPE; ++VT) {
567     setOperationAction(ISD::ADD , (MVT::SimpleValueType)VT, Expand);
568     setOperationAction(ISD::SUB , (MVT::SimpleValueType)VT, Expand);
569     setOperationAction(ISD::FADD, (MVT::SimpleValueType)VT, Expand);
570     setOperationAction(ISD::FNEG, (MVT::SimpleValueType)VT, Expand);
571     setOperationAction(ISD::FSUB, (MVT::SimpleValueType)VT, Expand);
572     setOperationAction(ISD::MUL , (MVT::SimpleValueType)VT, Expand);
573     setOperationAction(ISD::FMUL, (MVT::SimpleValueType)VT, Expand);
574     setOperationAction(ISD::SDIV, (MVT::SimpleValueType)VT, Expand);
575     setOperationAction(ISD::UDIV, (MVT::SimpleValueType)VT, Expand);
576     setOperationAction(ISD::FDIV, (MVT::SimpleValueType)VT, Expand);
577     setOperationAction(ISD::SREM, (MVT::SimpleValueType)VT, Expand);
578     setOperationAction(ISD::UREM, (MVT::SimpleValueType)VT, Expand);
579     setOperationAction(ISD::LOAD, (MVT::SimpleValueType)VT, Expand);
580     setOperationAction(ISD::VECTOR_SHUFFLE, (MVT::SimpleValueType)VT, Expand);
581     setOperationAction(ISD::EXTRACT_VECTOR_ELT,(MVT::SimpleValueType)VT,Expand);
582     setOperationAction(ISD::EXTRACT_SUBVECTOR,(MVT::SimpleValueType)VT,Expand);
583     setOperationAction(ISD::INSERT_VECTOR_ELT,(MVT::SimpleValueType)VT, Expand);
584     setOperationAction(ISD::FABS, (MVT::SimpleValueType)VT, Expand);
585     setOperationAction(ISD::FSIN, (MVT::SimpleValueType)VT, Expand);
586     setOperationAction(ISD::FCOS, (MVT::SimpleValueType)VT, Expand);
587     setOperationAction(ISD::FREM, (MVT::SimpleValueType)VT, Expand);
588     setOperationAction(ISD::FPOWI, (MVT::SimpleValueType)VT, Expand);
589     setOperationAction(ISD::FSQRT, (MVT::SimpleValueType)VT, Expand);
590     setOperationAction(ISD::FCOPYSIGN, (MVT::SimpleValueType)VT, Expand);
591     setOperationAction(ISD::SMUL_LOHI, (MVT::SimpleValueType)VT, Expand);
592     setOperationAction(ISD::UMUL_LOHI, (MVT::SimpleValueType)VT, Expand);
593     setOperationAction(ISD::SDIVREM, (MVT::SimpleValueType)VT, Expand);
594     setOperationAction(ISD::UDIVREM, (MVT::SimpleValueType)VT, Expand);
595     setOperationAction(ISD::FPOW, (MVT::SimpleValueType)VT, Expand);
596     setOperationAction(ISD::CTPOP, (MVT::SimpleValueType)VT, Expand);
597     setOperationAction(ISD::CTTZ, (MVT::SimpleValueType)VT, Expand);
598     setOperationAction(ISD::CTLZ, (MVT::SimpleValueType)VT, Expand);
599     setOperationAction(ISD::SHL, (MVT::SimpleValueType)VT, Expand);
600     setOperationAction(ISD::SRA, (MVT::SimpleValueType)VT, Expand);
601     setOperationAction(ISD::SRL, (MVT::SimpleValueType)VT, Expand);
602     setOperationAction(ISD::ROTL, (MVT::SimpleValueType)VT, Expand);
603     setOperationAction(ISD::ROTR, (MVT::SimpleValueType)VT, Expand);
604     setOperationAction(ISD::BSWAP, (MVT::SimpleValueType)VT, Expand);
605     setOperationAction(ISD::VSETCC, (MVT::SimpleValueType)VT, Expand);
606     setOperationAction(ISD::FLOG, (MVT::SimpleValueType)VT, Expand);
607     setOperationAction(ISD::FLOG2, (MVT::SimpleValueType)VT, Expand);
608     setOperationAction(ISD::FLOG10, (MVT::SimpleValueType)VT, Expand);
609     setOperationAction(ISD::FEXP, (MVT::SimpleValueType)VT, Expand);
610     setOperationAction(ISD::FEXP2, (MVT::SimpleValueType)VT, Expand);
611     setOperationAction(ISD::FP_TO_UINT, (MVT::SimpleValueType)VT, Expand);
612     setOperationAction(ISD::FP_TO_SINT, (MVT::SimpleValueType)VT, Expand);
613     setOperationAction(ISD::UINT_TO_FP, (MVT::SimpleValueType)VT, Expand);
614     setOperationAction(ISD::SINT_TO_FP, (MVT::SimpleValueType)VT, Expand);
615     setOperationAction(ISD::SIGN_EXTEND_INREG, (MVT::SimpleValueType)VT,Expand);
616     setOperationAction(ISD::TRUNCATE,  (MVT::SimpleValueType)VT, Expand);
617     setOperationAction(ISD::SIGN_EXTEND,  (MVT::SimpleValueType)VT, Expand);
618     setOperationAction(ISD::ZERO_EXTEND,  (MVT::SimpleValueType)VT, Expand);
619     setOperationAction(ISD::ANY_EXTEND,  (MVT::SimpleValueType)VT, Expand);
620     for (unsigned InnerVT = (unsigned)MVT::FIRST_VECTOR_VALUETYPE;
621          InnerVT <= (unsigned)MVT::LAST_VECTOR_VALUETYPE; ++InnerVT)
622       setTruncStoreAction((MVT::SimpleValueType)VT,
623                           (MVT::SimpleValueType)InnerVT, Expand);
624     setLoadExtAction(ISD::SEXTLOAD, (MVT::SimpleValueType)VT, Expand);
625     setLoadExtAction(ISD::ZEXTLOAD, (MVT::SimpleValueType)VT, Expand);
626     setLoadExtAction(ISD::EXTLOAD, (MVT::SimpleValueType)VT, Expand);
627   }
628
629   // FIXME: In order to prevent SSE instructions being expanded to MMX ones
630   // with -msoft-float, disable use of MMX as well.
631   if (!UseSoftFloat && !DisableMMX && Subtarget->hasMMX()) {
632     addRegisterClass(MVT::x86mmx, X86::VR64RegisterClass);
633     // No operations on x86mmx supported, everything uses intrinsics.
634   }
635
636   // MMX-sized vectors (other than x86mmx) are expected to be expanded
637   // into smaller operations.
638   setOperationAction(ISD::MULHS,              MVT::v8i8,  Expand);
639   setOperationAction(ISD::MULHS,              MVT::v4i16, Expand);
640   setOperationAction(ISD::MULHS,              MVT::v2i32, Expand);
641   setOperationAction(ISD::MULHS,              MVT::v1i64, Expand);
642   setOperationAction(ISD::AND,                MVT::v8i8,  Expand);
643   setOperationAction(ISD::AND,                MVT::v4i16, Expand);
644   setOperationAction(ISD::AND,                MVT::v2i32, Expand);
645   setOperationAction(ISD::AND,                MVT::v1i64, Expand);
646   setOperationAction(ISD::OR,                 MVT::v8i8,  Expand);
647   setOperationAction(ISD::OR,                 MVT::v4i16, Expand);
648   setOperationAction(ISD::OR,                 MVT::v2i32, Expand);
649   setOperationAction(ISD::OR,                 MVT::v1i64, Expand);
650   setOperationAction(ISD::XOR,                MVT::v8i8,  Expand);
651   setOperationAction(ISD::XOR,                MVT::v4i16, Expand);
652   setOperationAction(ISD::XOR,                MVT::v2i32, Expand);
653   setOperationAction(ISD::XOR,                MVT::v1i64, Expand);
654   setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v8i8,  Expand);
655   setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v4i16, Expand);
656   setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v2i32, Expand);
657   setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v1i64, Expand);
658   setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v1i64, Expand);
659   setOperationAction(ISD::SELECT,             MVT::v8i8,  Expand);
660   setOperationAction(ISD::SELECT,             MVT::v4i16, Expand);
661   setOperationAction(ISD::SELECT,             MVT::v2i32, Expand);
662   setOperationAction(ISD::SELECT,             MVT::v1i64, Expand);
663   setOperationAction(ISD::BITCAST,            MVT::v8i8,  Expand);
664   setOperationAction(ISD::BITCAST,            MVT::v4i16, Expand);
665   setOperationAction(ISD::BITCAST,            MVT::v2i32, Expand);
666   setOperationAction(ISD::BITCAST,            MVT::v1i64, Expand);
667
668   if (!UseSoftFloat && Subtarget->hasXMM()) {
669     addRegisterClass(MVT::v4f32, X86::VR128RegisterClass);
670
671     setOperationAction(ISD::FADD,               MVT::v4f32, Legal);
672     setOperationAction(ISD::FSUB,               MVT::v4f32, Legal);
673     setOperationAction(ISD::FMUL,               MVT::v4f32, Legal);
674     setOperationAction(ISD::FDIV,               MVT::v4f32, Legal);
675     setOperationAction(ISD::FSQRT,              MVT::v4f32, Legal);
676     setOperationAction(ISD::FNEG,               MVT::v4f32, Custom);
677     setOperationAction(ISD::LOAD,               MVT::v4f32, Legal);
678     setOperationAction(ISD::BUILD_VECTOR,       MVT::v4f32, Custom);
679     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v4f32, Custom);
680     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
681     setOperationAction(ISD::SELECT,             MVT::v4f32, Custom);
682     setOperationAction(ISD::VSETCC,             MVT::v4f32, Custom);
683   }
684
685   if (!UseSoftFloat && Subtarget->hasXMMInt()) {
686     addRegisterClass(MVT::v2f64, X86::VR128RegisterClass);
687
688     // FIXME: Unfortunately -soft-float and -no-implicit-float means XMM
689     // registers cannot be used even for integer operations.
690     addRegisterClass(MVT::v16i8, X86::VR128RegisterClass);
691     addRegisterClass(MVT::v8i16, X86::VR128RegisterClass);
692     addRegisterClass(MVT::v4i32, X86::VR128RegisterClass);
693     addRegisterClass(MVT::v2i64, X86::VR128RegisterClass);
694
695     setOperationAction(ISD::ADD,                MVT::v16i8, Legal);
696     setOperationAction(ISD::ADD,                MVT::v8i16, Legal);
697     setOperationAction(ISD::ADD,                MVT::v4i32, Legal);
698     setOperationAction(ISD::ADD,                MVT::v2i64, Legal);
699     setOperationAction(ISD::MUL,                MVT::v2i64, Custom);
700     setOperationAction(ISD::SUB,                MVT::v16i8, Legal);
701     setOperationAction(ISD::SUB,                MVT::v8i16, Legal);
702     setOperationAction(ISD::SUB,                MVT::v4i32, Legal);
703     setOperationAction(ISD::SUB,                MVT::v2i64, Legal);
704     setOperationAction(ISD::MUL,                MVT::v8i16, Legal);
705     setOperationAction(ISD::FADD,               MVT::v2f64, Legal);
706     setOperationAction(ISD::FSUB,               MVT::v2f64, Legal);
707     setOperationAction(ISD::FMUL,               MVT::v2f64, Legal);
708     setOperationAction(ISD::FDIV,               MVT::v2f64, Legal);
709     setOperationAction(ISD::FSQRT,              MVT::v2f64, Legal);
710     setOperationAction(ISD::FNEG,               MVT::v2f64, Custom);
711
712     setOperationAction(ISD::VSETCC,             MVT::v2f64, Custom);
713     setOperationAction(ISD::VSETCC,             MVT::v16i8, Custom);
714     setOperationAction(ISD::VSETCC,             MVT::v8i16, Custom);
715     setOperationAction(ISD::VSETCC,             MVT::v4i32, Custom);
716
717     setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v16i8, Custom);
718     setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v8i16, Custom);
719     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v8i16, Custom);
720     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4i32, Custom);
721     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4f32, Custom);
722
723     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v2f64, Custom);
724     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v2i64, Custom);
725     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v16i8, Custom);
726     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v8i16, Custom);
727     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v4i32, Custom);
728
729     // Custom lower build_vector, vector_shuffle, and extract_vector_elt.
730     for (unsigned i = (unsigned)MVT::v16i8; i != (unsigned)MVT::v2i64; ++i) {
731       EVT VT = (MVT::SimpleValueType)i;
732       // Do not attempt to custom lower non-power-of-2 vectors
733       if (!isPowerOf2_32(VT.getVectorNumElements()))
734         continue;
735       // Do not attempt to custom lower non-128-bit vectors
736       if (!VT.is128BitVector())
737         continue;
738       setOperationAction(ISD::BUILD_VECTOR,
739                          VT.getSimpleVT().SimpleTy, Custom);
740       setOperationAction(ISD::VECTOR_SHUFFLE,
741                          VT.getSimpleVT().SimpleTy, Custom);
742       setOperationAction(ISD::EXTRACT_VECTOR_ELT,
743                          VT.getSimpleVT().SimpleTy, Custom);
744     }
745
746     setOperationAction(ISD::BUILD_VECTOR,       MVT::v2f64, Custom);
747     setOperationAction(ISD::BUILD_VECTOR,       MVT::v2i64, Custom);
748     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v2f64, Custom);
749     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v2i64, Custom);
750     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2f64, Custom);
751     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Custom);
752
753     if (Subtarget->is64Bit()) {
754       setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2i64, Custom);
755       setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
756     }
757
758     // Promote v16i8, v8i16, v4i32 load, select, and, or, xor to v2i64.
759     for (unsigned i = (unsigned)MVT::v16i8; i != (unsigned)MVT::v2i64; i++) {
760       MVT::SimpleValueType SVT = (MVT::SimpleValueType)i;
761       EVT VT = SVT;
762
763       // Do not attempt to promote non-128-bit vectors
764       if (!VT.is128BitVector())
765         continue;
766
767       setOperationAction(ISD::AND,    SVT, Promote);
768       AddPromotedToType (ISD::AND,    SVT, MVT::v2i64);
769       setOperationAction(ISD::OR,     SVT, Promote);
770       AddPromotedToType (ISD::OR,     SVT, MVT::v2i64);
771       setOperationAction(ISD::XOR,    SVT, Promote);
772       AddPromotedToType (ISD::XOR,    SVT, MVT::v2i64);
773       setOperationAction(ISD::LOAD,   SVT, Promote);
774       AddPromotedToType (ISD::LOAD,   SVT, MVT::v2i64);
775       setOperationAction(ISD::SELECT, SVT, Promote);
776       AddPromotedToType (ISD::SELECT, SVT, MVT::v2i64);
777     }
778
779     setTruncStoreAction(MVT::f64, MVT::f32, Expand);
780
781     // Custom lower v2i64 and v2f64 selects.
782     setOperationAction(ISD::LOAD,               MVT::v2f64, Legal);
783     setOperationAction(ISD::LOAD,               MVT::v2i64, Legal);
784     setOperationAction(ISD::SELECT,             MVT::v2f64, Custom);
785     setOperationAction(ISD::SELECT,             MVT::v2i64, Custom);
786
787     setOperationAction(ISD::FP_TO_SINT,         MVT::v4i32, Legal);
788     setOperationAction(ISD::SINT_TO_FP,         MVT::v4i32, Legal);
789   }
790
791   if (Subtarget->hasSSE41()) {
792     setOperationAction(ISD::FFLOOR,             MVT::f32,   Legal);
793     setOperationAction(ISD::FCEIL,              MVT::f32,   Legal);
794     setOperationAction(ISD::FTRUNC,             MVT::f32,   Legal);
795     setOperationAction(ISD::FRINT,              MVT::f32,   Legal);
796     setOperationAction(ISD::FNEARBYINT,         MVT::f32,   Legal);
797     setOperationAction(ISD::FFLOOR,             MVT::f64,   Legal);
798     setOperationAction(ISD::FCEIL,              MVT::f64,   Legal);
799     setOperationAction(ISD::FTRUNC,             MVT::f64,   Legal);
800     setOperationAction(ISD::FRINT,              MVT::f64,   Legal);
801     setOperationAction(ISD::FNEARBYINT,         MVT::f64,   Legal);
802
803     // FIXME: Do we need to handle scalar-to-vector here?
804     setOperationAction(ISD::MUL,                MVT::v4i32, Legal);
805
806     // Can turn SHL into an integer multiply.
807     setOperationAction(ISD::SHL,                MVT::v4i32, Custom);
808     setOperationAction(ISD::SHL,                MVT::v16i8, Custom);
809
810     // i8 and i16 vectors are custom , because the source register and source
811     // source memory operand types are not the same width.  f32 vectors are
812     // custom since the immediate controlling the insert encodes additional
813     // information.
814     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v16i8, Custom);
815     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v8i16, Custom);
816     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4i32, Custom);
817     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4f32, Custom);
818
819     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i8, Custom);
820     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i16, Custom);
821     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i32, Custom);
822     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
823
824     if (Subtarget->is64Bit()) {
825       setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2i64, Legal);
826       setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Legal);
827     }
828   }
829
830   if (Subtarget->hasSSE42())
831     setOperationAction(ISD::VSETCC,             MVT::v2i64, Custom);
832
833   if (!UseSoftFloat && Subtarget->hasAVX()) {
834     addRegisterClass(MVT::v8f32, X86::VR256RegisterClass);
835     addRegisterClass(MVT::v4f64, X86::VR256RegisterClass);
836     addRegisterClass(MVT::v8i32, X86::VR256RegisterClass);
837     addRegisterClass(MVT::v4i64, X86::VR256RegisterClass);
838     addRegisterClass(MVT::v32i8, X86::VR256RegisterClass);
839
840     setOperationAction(ISD::LOAD,               MVT::v8f32, Legal);
841     setOperationAction(ISD::LOAD,               MVT::v8i32, Legal);
842     setOperationAction(ISD::LOAD,               MVT::v4f64, Legal);
843     setOperationAction(ISD::LOAD,               MVT::v4i64, Legal);
844     setOperationAction(ISD::FADD,               MVT::v8f32, Legal);
845     setOperationAction(ISD::FSUB,               MVT::v8f32, Legal);
846     setOperationAction(ISD::FMUL,               MVT::v8f32, Legal);
847     setOperationAction(ISD::FDIV,               MVT::v8f32, Legal);
848     setOperationAction(ISD::FSQRT,              MVT::v8f32, Legal);
849     setOperationAction(ISD::FNEG,               MVT::v8f32, Custom);
850     setOperationAction(ISD::BUILD_VECTOR,       MVT::v8f32, Custom);
851     //setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v8f32, Custom);
852     //setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8f32, Custom);
853     //setOperationAction(ISD::SELECT,             MVT::v8f32, Custom);
854     //setOperationAction(ISD::VSETCC,             MVT::v8f32, Custom);
855
856     // Operations to consider commented out -v16i16 v32i8
857     //setOperationAction(ISD::ADD,                MVT::v16i16, Legal);
858     setOperationAction(ISD::ADD,                MVT::v8i32, Custom);
859     setOperationAction(ISD::ADD,                MVT::v4i64, Custom);
860     //setOperationAction(ISD::SUB,                MVT::v32i8, Legal);
861     //setOperationAction(ISD::SUB,                MVT::v16i16, Legal);
862     setOperationAction(ISD::SUB,                MVT::v8i32, Custom);
863     setOperationAction(ISD::SUB,                MVT::v4i64, Custom);
864     //setOperationAction(ISD::MUL,                MVT::v16i16, Legal);
865     setOperationAction(ISD::FADD,               MVT::v4f64, Legal);
866     setOperationAction(ISD::FSUB,               MVT::v4f64, Legal);
867     setOperationAction(ISD::FMUL,               MVT::v4f64, Legal);
868     setOperationAction(ISD::FDIV,               MVT::v4f64, Legal);
869     setOperationAction(ISD::FSQRT,              MVT::v4f64, Legal);
870     setOperationAction(ISD::FNEG,               MVT::v4f64, Custom);
871
872     setOperationAction(ISD::VSETCC,             MVT::v4f64, Custom);
873     // setOperationAction(ISD::VSETCC,             MVT::v32i8, Custom);
874     // setOperationAction(ISD::VSETCC,             MVT::v16i16, Custom);
875     setOperationAction(ISD::VSETCC,             MVT::v8i32, Custom);
876
877     // setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v32i8, Custom);
878     // setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v16i16, Custom);
879     // setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v16i16, Custom);
880     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v8i32, Custom);
881     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v8f32, Custom);
882
883     setOperationAction(ISD::BUILD_VECTOR,       MVT::v4f64, Custom);
884     setOperationAction(ISD::BUILD_VECTOR,       MVT::v4i64, Custom);
885     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v4f64, Custom);
886     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v4i64, Custom);
887     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4f64, Custom);
888     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f64, Custom);
889
890 #if 0
891     // Not sure we want to do this since there are no 256-bit integer
892     // operations in AVX
893
894     // Custom lower build_vector, vector_shuffle, and extract_vector_elt.
895     // This includes 256-bit vectors
896     for (unsigned i = (unsigned)MVT::v16i8; i != (unsigned)MVT::v4i64; ++i) {
897       EVT VT = (MVT::SimpleValueType)i;
898
899       // Do not attempt to custom lower non-power-of-2 vectors
900       if (!isPowerOf2_32(VT.getVectorNumElements()))
901         continue;
902
903       setOperationAction(ISD::BUILD_VECTOR,       VT, Custom);
904       setOperationAction(ISD::VECTOR_SHUFFLE,     VT, Custom);
905       setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
906     }
907
908     if (Subtarget->is64Bit()) {
909       setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4i64, Custom);
910       setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i64, Custom);
911     }
912 #endif
913
914 #if 0
915     // Not sure we want to do this since there are no 256-bit integer
916     // operations in AVX
917
918     // Promote v32i8, v16i16, v8i32 load, select, and, or, xor to v4i64.
919     // Including 256-bit vectors
920     for (unsigned i = (unsigned)MVT::v16i8; i != (unsigned)MVT::v4i64; i++) {
921       EVT VT = (MVT::SimpleValueType)i;
922
923       if (!VT.is256BitVector()) {
924         continue;
925       }
926       setOperationAction(ISD::AND,    VT, Promote);
927       AddPromotedToType (ISD::AND,    VT, MVT::v4i64);
928       setOperationAction(ISD::OR,     VT, Promote);
929       AddPromotedToType (ISD::OR,     VT, MVT::v4i64);
930       setOperationAction(ISD::XOR,    VT, Promote);
931       AddPromotedToType (ISD::XOR,    VT, MVT::v4i64);
932       setOperationAction(ISD::LOAD,   VT, Promote);
933       AddPromotedToType (ISD::LOAD,   VT, MVT::v4i64);
934       setOperationAction(ISD::SELECT, VT, Promote);
935       AddPromotedToType (ISD::SELECT, VT, MVT::v4i64);
936     }
937
938     setTruncStoreAction(MVT::f64, MVT::f32, Expand);
939 #endif
940   }
941
942   // We want to custom lower some of our intrinsics.
943   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
944
945     
946   // Only custom-lower 64-bit SADDO and friends on 64-bit because we don't
947   // handle type legalization for these operations here.
948   //
949   // FIXME: We really should do custom legalization for addition and
950   // subtraction on x86-32 once PR3203 is fixed.  We really can't do much better
951   // than generic legalization for 64-bit multiplication-with-overflow, though.
952   for (unsigned i = 0, e = 3+Subtarget->is64Bit(); i != e; ++i) {
953     // Add/Sub/Mul with overflow operations are custom lowered.
954     MVT VT = IntVTs[i];
955     setOperationAction(ISD::SADDO, VT, Custom);
956     setOperationAction(ISD::UADDO, VT, Custom);
957     setOperationAction(ISD::SSUBO, VT, Custom);
958     setOperationAction(ISD::USUBO, VT, Custom);
959     setOperationAction(ISD::SMULO, VT, Custom);
960     setOperationAction(ISD::UMULO, VT, Custom);
961   }
962     
963   // There are no 8-bit 3-address imul/mul instructions
964   setOperationAction(ISD::SMULO, MVT::i8, Expand);
965   setOperationAction(ISD::UMULO, MVT::i8, Expand);
966
967   if (!Subtarget->is64Bit()) {
968     // These libcalls are not available in 32-bit.
969     setLibcallName(RTLIB::SHL_I128, 0);
970     setLibcallName(RTLIB::SRL_I128, 0);
971     setLibcallName(RTLIB::SRA_I128, 0);
972   }
973
974   // We have target-specific dag combine patterns for the following nodes:
975   setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
976   setTargetDAGCombine(ISD::EXTRACT_VECTOR_ELT);
977   setTargetDAGCombine(ISD::BUILD_VECTOR);
978   setTargetDAGCombine(ISD::SELECT);
979   setTargetDAGCombine(ISD::SHL);
980   setTargetDAGCombine(ISD::SRA);
981   setTargetDAGCombine(ISD::SRL);
982   setTargetDAGCombine(ISD::OR);
983   setTargetDAGCombine(ISD::AND);
984   setTargetDAGCombine(ISD::STORE);
985   setTargetDAGCombine(ISD::ZERO_EXTEND);
986   if (Subtarget->is64Bit())
987     setTargetDAGCombine(ISD::MUL);
988
989   computeRegisterProperties();
990
991   // FIXME: These should be based on subtarget info. Plus, the values should
992   // be smaller when we are in optimizing for size mode.
993   maxStoresPerMemset = 16; // For @llvm.memset -> sequence of stores
994   maxStoresPerMemcpy = 8; // For @llvm.memcpy -> sequence of stores
995   maxStoresPerMemmove = 3; // For @llvm.memmove -> sequence of stores
996   setPrefLoopAlignment(16);
997   benefitFromCodePlacementOpt = true;
998 }
999
1000
1001 MVT::SimpleValueType X86TargetLowering::getSetCCResultType(EVT VT) const {
1002   return MVT::i8;
1003 }
1004
1005
1006 /// getMaxByValAlign - Helper for getByValTypeAlignment to determine
1007 /// the desired ByVal argument alignment.
1008 static void getMaxByValAlign(const Type *Ty, unsigned &MaxAlign) {
1009   if (MaxAlign == 16)
1010     return;
1011   if (const VectorType *VTy = dyn_cast<VectorType>(Ty)) {
1012     if (VTy->getBitWidth() == 128)
1013       MaxAlign = 16;
1014   } else if (const ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
1015     unsigned EltAlign = 0;
1016     getMaxByValAlign(ATy->getElementType(), EltAlign);
1017     if (EltAlign > MaxAlign)
1018       MaxAlign = EltAlign;
1019   } else if (const StructType *STy = dyn_cast<StructType>(Ty)) {
1020     for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
1021       unsigned EltAlign = 0;
1022       getMaxByValAlign(STy->getElementType(i), EltAlign);
1023       if (EltAlign > MaxAlign)
1024         MaxAlign = EltAlign;
1025       if (MaxAlign == 16)
1026         break;
1027     }
1028   }
1029   return;
1030 }
1031
1032 /// getByValTypeAlignment - Return the desired alignment for ByVal aggregate
1033 /// function arguments in the caller parameter area. For X86, aggregates
1034 /// that contain SSE vectors are placed at 16-byte boundaries while the rest
1035 /// are at 4-byte boundaries.
1036 unsigned X86TargetLowering::getByValTypeAlignment(const Type *Ty) const {
1037   if (Subtarget->is64Bit()) {
1038     // Max of 8 and alignment of type.
1039     unsigned TyAlign = TD->getABITypeAlignment(Ty);
1040     if (TyAlign > 8)
1041       return TyAlign;
1042     return 8;
1043   }
1044
1045   unsigned Align = 4;
1046   if (Subtarget->hasXMM())
1047     getMaxByValAlign(Ty, Align);
1048   return Align;
1049 }
1050
1051 /// getOptimalMemOpType - Returns the target specific optimal type for load
1052 /// and store operations as a result of memset, memcpy, and memmove
1053 /// lowering. If DstAlign is zero that means it's safe to destination
1054 /// alignment can satisfy any constraint. Similarly if SrcAlign is zero it
1055 /// means there isn't a need to check it against alignment requirement,
1056 /// probably because the source does not need to be loaded. If
1057 /// 'NonScalarIntSafe' is true, that means it's safe to return a
1058 /// non-scalar-integer type, e.g. empty string source, constant, or loaded
1059 /// from memory. 'MemcpyStrSrc' indicates whether the memcpy source is
1060 /// constant so it does not need to be loaded.
1061 /// It returns EVT::Other if the type should be determined using generic
1062 /// target-independent logic.
1063 EVT
1064 X86TargetLowering::getOptimalMemOpType(uint64_t Size,
1065                                        unsigned DstAlign, unsigned SrcAlign,
1066                                        bool NonScalarIntSafe,
1067                                        bool MemcpyStrSrc,
1068                                        MachineFunction &MF) const {
1069   // FIXME: This turns off use of xmm stores for memset/memcpy on targets like
1070   // linux.  This is because the stack realignment code can't handle certain
1071   // cases like PR2962.  This should be removed when PR2962 is fixed.
1072   const Function *F = MF.getFunction();
1073   if (NonScalarIntSafe &&
1074       !F->hasFnAttr(Attribute::NoImplicitFloat)) {
1075     if (Size >= 16 &&
1076         (Subtarget->isUnalignedMemAccessFast() ||
1077          ((DstAlign == 0 || DstAlign >= 16) &&
1078           (SrcAlign == 0 || SrcAlign >= 16))) &&
1079         Subtarget->getStackAlignment() >= 16) {
1080       if (Subtarget->hasSSE2())
1081         return MVT::v4i32;
1082       if (Subtarget->hasSSE1())
1083         return MVT::v4f32;
1084     } else if (!MemcpyStrSrc && Size >= 8 &&
1085                !Subtarget->is64Bit() &&
1086                Subtarget->getStackAlignment() >= 8 &&
1087                Subtarget->hasXMMInt()) {
1088       // Do not use f64 to lower memcpy if source is string constant. It's
1089       // better to use i32 to avoid the loads.
1090       return MVT::f64;
1091     }
1092   }
1093   if (Subtarget->is64Bit() && Size >= 8)
1094     return MVT::i64;
1095   return MVT::i32;
1096 }
1097
1098 /// getJumpTableEncoding - Return the entry encoding for a jump table in the
1099 /// current function.  The returned value is a member of the
1100 /// MachineJumpTableInfo::JTEntryKind enum.
1101 unsigned X86TargetLowering::getJumpTableEncoding() const {
1102   // In GOT pic mode, each entry in the jump table is emitted as a @GOTOFF
1103   // symbol.
1104   if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1105       Subtarget->isPICStyleGOT())
1106     return MachineJumpTableInfo::EK_Custom32;
1107
1108   // Otherwise, use the normal jump table encoding heuristics.
1109   return TargetLowering::getJumpTableEncoding();
1110 }
1111
1112 const MCExpr *
1113 X86TargetLowering::LowerCustomJumpTableEntry(const MachineJumpTableInfo *MJTI,
1114                                              const MachineBasicBlock *MBB,
1115                                              unsigned uid,MCContext &Ctx) const{
1116   assert(getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1117          Subtarget->isPICStyleGOT());
1118   // In 32-bit ELF systems, our jump table entries are formed with @GOTOFF
1119   // entries.
1120   return MCSymbolRefExpr::Create(MBB->getSymbol(),
1121                                  MCSymbolRefExpr::VK_GOTOFF, Ctx);
1122 }
1123
1124 /// getPICJumpTableRelocaBase - Returns relocation base for the given PIC
1125 /// jumptable.
1126 SDValue X86TargetLowering::getPICJumpTableRelocBase(SDValue Table,
1127                                                     SelectionDAG &DAG) const {
1128   if (!Subtarget->is64Bit())
1129     // This doesn't have DebugLoc associated with it, but is not really the
1130     // same as a Register.
1131     return DAG.getNode(X86ISD::GlobalBaseReg, DebugLoc(), getPointerTy());
1132   return Table;
1133 }
1134
1135 /// getPICJumpTableRelocBaseExpr - This returns the relocation base for the
1136 /// given PIC jumptable, the same as getPICJumpTableRelocBase, but as an
1137 /// MCExpr.
1138 const MCExpr *X86TargetLowering::
1139 getPICJumpTableRelocBaseExpr(const MachineFunction *MF, unsigned JTI,
1140                              MCContext &Ctx) const {
1141   // X86-64 uses RIP relative addressing based on the jump table label.
1142   if (Subtarget->isPICStyleRIPRel())
1143     return TargetLowering::getPICJumpTableRelocBaseExpr(MF, JTI, Ctx);
1144
1145   // Otherwise, the reference is relative to the PIC base.
1146   return MCSymbolRefExpr::Create(MF->getPICBaseSymbol(), Ctx);
1147 }
1148
1149 /// getFunctionAlignment - Return the Log2 alignment of this function.
1150 unsigned X86TargetLowering::getFunctionAlignment(const Function *F) const {
1151   return F->hasFnAttr(Attribute::OptimizeForSize) ? 0 : 4;
1152 }
1153
1154 std::pair<const TargetRegisterClass*, uint8_t>
1155 X86TargetLowering::findRepresentativeClass(EVT VT) const{
1156   const TargetRegisterClass *RRC = 0;
1157   uint8_t Cost = 1;
1158   switch (VT.getSimpleVT().SimpleTy) {
1159   default:
1160     return TargetLowering::findRepresentativeClass(VT);
1161   case MVT::i8: case MVT::i16: case MVT::i32: case MVT::i64:
1162     RRC = (Subtarget->is64Bit()
1163            ? X86::GR64RegisterClass : X86::GR32RegisterClass);
1164     break;
1165   case MVT::x86mmx:
1166     RRC = X86::VR64RegisterClass;
1167     break;
1168   case MVT::f32: case MVT::f64:
1169   case MVT::v16i8: case MVT::v8i16: case MVT::v4i32: case MVT::v2i64:
1170   case MVT::v4f32: case MVT::v2f64:
1171   case MVT::v32i8: case MVT::v8i32: case MVT::v4i64: case MVT::v8f32:
1172   case MVT::v4f64:
1173     RRC = X86::VR128RegisterClass;
1174     break;
1175   }
1176   return std::make_pair(RRC, Cost);
1177 }
1178
1179 unsigned
1180 X86TargetLowering::getRegPressureLimit(const TargetRegisterClass *RC,
1181                                        MachineFunction &MF) const {
1182   const TargetFrameInfo *TFI = MF.getTarget().getFrameInfo();
1183
1184   unsigned FPDiff = TFI->hasFP(MF) ? 1 : 0;
1185   switch (RC->getID()) {
1186   default:
1187     return 0;
1188   case X86::GR32RegClassID:
1189     return 4 - FPDiff;
1190   case X86::GR64RegClassID:
1191     return 8 - FPDiff;
1192   case X86::VR128RegClassID:
1193     return Subtarget->is64Bit() ? 10 : 4;
1194   case X86::VR64RegClassID:
1195     return 4;
1196   }
1197 }
1198
1199 bool X86TargetLowering::getStackCookieLocation(unsigned &AddressSpace,
1200                                                unsigned &Offset) const {
1201   if (!Subtarget->isTargetLinux())
1202     return false;
1203
1204   if (Subtarget->is64Bit()) {
1205     // %fs:0x28, unless we're using a Kernel code model, in which case it's %gs:
1206     Offset = 0x28;
1207     if (getTargetMachine().getCodeModel() == CodeModel::Kernel)
1208       AddressSpace = 256;
1209     else
1210       AddressSpace = 257;
1211   } else {
1212     // %gs:0x14 on i386
1213     Offset = 0x14;
1214     AddressSpace = 256;
1215   }
1216   return true;
1217 }
1218
1219
1220 //===----------------------------------------------------------------------===//
1221 //               Return Value Calling Convention Implementation
1222 //===----------------------------------------------------------------------===//
1223
1224 #include "X86GenCallingConv.inc"
1225
1226 bool
1227 X86TargetLowering::CanLowerReturn(CallingConv::ID CallConv, bool isVarArg,
1228                         const SmallVectorImpl<ISD::OutputArg> &Outs,
1229                         LLVMContext &Context) const {
1230   SmallVector<CCValAssign, 16> RVLocs;
1231   CCState CCInfo(CallConv, isVarArg, getTargetMachine(),
1232                  RVLocs, Context);
1233   return CCInfo.CheckReturn(Outs, RetCC_X86);
1234 }
1235
1236 SDValue
1237 X86TargetLowering::LowerReturn(SDValue Chain,
1238                                CallingConv::ID CallConv, bool isVarArg,
1239                                const SmallVectorImpl<ISD::OutputArg> &Outs,
1240                                const SmallVectorImpl<SDValue> &OutVals,
1241                                DebugLoc dl, SelectionDAG &DAG) const {
1242   MachineFunction &MF = DAG.getMachineFunction();
1243   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1244
1245   SmallVector<CCValAssign, 16> RVLocs;
1246   CCState CCInfo(CallConv, isVarArg, getTargetMachine(),
1247                  RVLocs, *DAG.getContext());
1248   CCInfo.AnalyzeReturn(Outs, RetCC_X86);
1249
1250   // Add the regs to the liveout set for the function.
1251   MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo();
1252   for (unsigned i = 0; i != RVLocs.size(); ++i)
1253     if (RVLocs[i].isRegLoc() && !MRI.isLiveOut(RVLocs[i].getLocReg()))
1254       MRI.addLiveOut(RVLocs[i].getLocReg());
1255
1256   SDValue Flag;
1257
1258   SmallVector<SDValue, 6> RetOps;
1259   RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
1260   // Operand #1 = Bytes To Pop
1261   RetOps.push_back(DAG.getTargetConstant(FuncInfo->getBytesToPopOnReturn(),
1262                    MVT::i16));
1263
1264   // Copy the result values into the output registers.
1265   for (unsigned i = 0; i != RVLocs.size(); ++i) {
1266     CCValAssign &VA = RVLocs[i];
1267     assert(VA.isRegLoc() && "Can only return in registers!");
1268     SDValue ValToCopy = OutVals[i];
1269     EVT ValVT = ValToCopy.getValueType();
1270
1271     // If this is x86-64, and we disabled SSE, we can't return FP values,
1272     // or SSE or MMX vectors.
1273     if ((ValVT == MVT::f32 || ValVT == MVT::f64 ||
1274          VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) &&
1275           (Subtarget->is64Bit() && !Subtarget->hasXMM())) {
1276       report_fatal_error("SSE register return with SSE disabled");
1277     }
1278     // Likewise we can't return F64 values with SSE1 only.  gcc does so, but
1279     // llvm-gcc has never done it right and no one has noticed, so this
1280     // should be OK for now.
1281     if (ValVT == MVT::f64 &&
1282         (Subtarget->is64Bit() && !Subtarget->hasXMMInt()))
1283       report_fatal_error("SSE2 register return with SSE2 disabled");
1284
1285     // Returns in ST0/ST1 are handled specially: these are pushed as operands to
1286     // the RET instruction and handled by the FP Stackifier.
1287     if (VA.getLocReg() == X86::ST0 ||
1288         VA.getLocReg() == X86::ST1) {
1289       // If this is a copy from an xmm register to ST(0), use an FPExtend to
1290       // change the value to the FP stack register class.
1291       if (isScalarFPTypeInSSEReg(VA.getValVT()))
1292         ValToCopy = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f80, ValToCopy);
1293       RetOps.push_back(ValToCopy);
1294       // Don't emit a copytoreg.
1295       continue;
1296     }
1297
1298     // 64-bit vector (MMX) values are returned in XMM0 / XMM1 except for v1i64
1299     // which is returned in RAX / RDX.
1300     if (Subtarget->is64Bit()) {
1301       if (ValVT == MVT::x86mmx) {
1302         if (VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) {
1303           ValToCopy = DAG.getNode(ISD::BITCAST, dl, MVT::i64, ValToCopy);
1304           ValToCopy = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
1305                                   ValToCopy);
1306           // If we don't have SSE2 available, convert to v4f32 so the generated
1307           // register is legal.
1308           if (!Subtarget->hasSSE2())
1309             ValToCopy = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32,ValToCopy);
1310         }
1311       }
1312     }
1313
1314     Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), ValToCopy, Flag);
1315     Flag = Chain.getValue(1);
1316   }
1317
1318   // The x86-64 ABI for returning structs by value requires that we copy
1319   // the sret argument into %rax for the return. We saved the argument into
1320   // a virtual register in the entry block, so now we copy the value out
1321   // and into %rax.
1322   if (Subtarget->is64Bit() &&
1323       DAG.getMachineFunction().getFunction()->hasStructRetAttr()) {
1324     MachineFunction &MF = DAG.getMachineFunction();
1325     X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1326     unsigned Reg = FuncInfo->getSRetReturnReg();
1327     assert(Reg &&
1328            "SRetReturnReg should have been set in LowerFormalArguments().");
1329     SDValue Val = DAG.getCopyFromReg(Chain, dl, Reg, getPointerTy());
1330
1331     Chain = DAG.getCopyToReg(Chain, dl, X86::RAX, Val, Flag);
1332     Flag = Chain.getValue(1);
1333
1334     // RAX now acts like a return value.
1335     MRI.addLiveOut(X86::RAX);
1336   }
1337
1338   RetOps[0] = Chain;  // Update chain.
1339
1340   // Add the flag if we have it.
1341   if (Flag.getNode())
1342     RetOps.push_back(Flag);
1343
1344   return DAG.getNode(X86ISD::RET_FLAG, dl,
1345                      MVT::Other, &RetOps[0], RetOps.size());
1346 }
1347
1348 bool X86TargetLowering::isUsedByReturnOnly(SDNode *N) const {
1349   if (N->getNumValues() != 1)
1350     return false;
1351   if (!N->hasNUsesOfValue(1, 0))
1352     return false;
1353
1354   SDNode *Copy = *N->use_begin();
1355   if (Copy->getOpcode() != ISD::CopyToReg &&
1356       Copy->getOpcode() != ISD::FP_EXTEND)
1357     return false;
1358
1359   bool HasRet = false;
1360   for (SDNode::use_iterator UI = Copy->use_begin(), UE = Copy->use_end();
1361        UI != UE; ++UI) {
1362     if (UI->getOpcode() != X86ISD::RET_FLAG)
1363       return false;
1364     HasRet = true;
1365   }
1366
1367   return HasRet;
1368 }
1369
1370 /// LowerCallResult - Lower the result values of a call into the
1371 /// appropriate copies out of appropriate physical registers.
1372 ///
1373 SDValue
1374 X86TargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
1375                                    CallingConv::ID CallConv, bool isVarArg,
1376                                    const SmallVectorImpl<ISD::InputArg> &Ins,
1377                                    DebugLoc dl, SelectionDAG &DAG,
1378                                    SmallVectorImpl<SDValue> &InVals) const {
1379
1380   // Assign locations to each value returned by this call.
1381   SmallVector<CCValAssign, 16> RVLocs;
1382   bool Is64Bit = Subtarget->is64Bit();
1383   CCState CCInfo(CallConv, isVarArg, getTargetMachine(),
1384                  RVLocs, *DAG.getContext());
1385   CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
1386
1387   // Copy all of the result registers out of their specified physreg.
1388   for (unsigned i = 0; i != RVLocs.size(); ++i) {
1389     CCValAssign &VA = RVLocs[i];
1390     EVT CopyVT = VA.getValVT();
1391
1392     // If this is x86-64, and we disabled SSE, we can't return FP values
1393     if ((CopyVT == MVT::f32 || CopyVT == MVT::f64) &&
1394         ((Is64Bit || Ins[i].Flags.isInReg()) && !Subtarget->hasXMM())) {
1395       report_fatal_error("SSE register return with SSE disabled");
1396     }
1397
1398     SDValue Val;
1399
1400     // If this is a call to a function that returns an fp value on the floating
1401     // point stack, we must guarantee the the value is popped from the stack, so
1402     // a CopyFromReg is not good enough - the copy instruction may be eliminated
1403     // if the return value is not used. We use the FpGET_ST0 instructions
1404     // instead.
1405     if (VA.getLocReg() == X86::ST0 || VA.getLocReg() == X86::ST1) {
1406       // If we prefer to use the value in xmm registers, copy it out as f80 and
1407       // use a truncate to move it from fp stack reg to xmm reg.
1408       if (isScalarFPTypeInSSEReg(VA.getValVT())) CopyVT = MVT::f80;
1409       bool isST0 = VA.getLocReg() == X86::ST0;
1410       unsigned Opc = 0;
1411       if (CopyVT == MVT::f32) Opc = isST0 ? X86::FpGET_ST0_32:X86::FpGET_ST1_32;
1412       if (CopyVT == MVT::f64) Opc = isST0 ? X86::FpGET_ST0_64:X86::FpGET_ST1_64;
1413       if (CopyVT == MVT::f80) Opc = isST0 ? X86::FpGET_ST0_80:X86::FpGET_ST1_80;
1414       SDValue Ops[] = { Chain, InFlag };
1415       Chain = SDValue(DAG.getMachineNode(Opc, dl, CopyVT, MVT::Other, MVT::Flag,
1416                                          Ops, 2), 1);
1417       Val = Chain.getValue(0);
1418
1419       // Round the f80 to the right size, which also moves it to the appropriate
1420       // xmm register.
1421       if (CopyVT != VA.getValVT())
1422         Val = DAG.getNode(ISD::FP_ROUND, dl, VA.getValVT(), Val,
1423                           // This truncation won't change the value.
1424                           DAG.getIntPtrConstant(1));
1425     } else if (Is64Bit && CopyVT.isVector() && CopyVT.getSizeInBits() == 64) {
1426       // For x86-64, MMX values are returned in XMM0 / XMM1 except for v1i64.
1427       if (VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) {
1428         Chain = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(),
1429                                    MVT::v2i64, InFlag).getValue(1);
1430         Val = Chain.getValue(0);
1431         Val = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i64,
1432                           Val, DAG.getConstant(0, MVT::i64));
1433       } else {
1434         Chain = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(),
1435                                    MVT::i64, InFlag).getValue(1);
1436         Val = Chain.getValue(0);
1437       }
1438       Val = DAG.getNode(ISD::BITCAST, dl, CopyVT, Val);
1439     } else {
1440       Chain = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(),
1441                                  CopyVT, InFlag).getValue(1);
1442       Val = Chain.getValue(0);
1443     }
1444     InFlag = Chain.getValue(2);
1445     InVals.push_back(Val);
1446   }
1447
1448   return Chain;
1449 }
1450
1451
1452 //===----------------------------------------------------------------------===//
1453 //                C & StdCall & Fast Calling Convention implementation
1454 //===----------------------------------------------------------------------===//
1455 //  StdCall calling convention seems to be standard for many Windows' API
1456 //  routines and around. It differs from C calling convention just a little:
1457 //  callee should clean up the stack, not caller. Symbols should be also
1458 //  decorated in some fancy way :) It doesn't support any vector arguments.
1459 //  For info on fast calling convention see Fast Calling Convention (tail call)
1460 //  implementation LowerX86_32FastCCCallTo.
1461
1462 /// CallIsStructReturn - Determines whether a call uses struct return
1463 /// semantics.
1464 static bool CallIsStructReturn(const SmallVectorImpl<ISD::OutputArg> &Outs) {
1465   if (Outs.empty())
1466     return false;
1467
1468   return Outs[0].Flags.isSRet();
1469 }
1470
1471 /// ArgsAreStructReturn - Determines whether a function uses struct
1472 /// return semantics.
1473 static bool
1474 ArgsAreStructReturn(const SmallVectorImpl<ISD::InputArg> &Ins) {
1475   if (Ins.empty())
1476     return false;
1477
1478   return Ins[0].Flags.isSRet();
1479 }
1480
1481 /// CreateCopyOfByValArgument - Make a copy of an aggregate at address specified
1482 /// by "Src" to address "Dst" with size and alignment information specified by
1483 /// the specific parameter attribute. The copy will be passed as a byval
1484 /// function parameter.
1485 static SDValue
1486 CreateCopyOfByValArgument(SDValue Src, SDValue Dst, SDValue Chain,
1487                           ISD::ArgFlagsTy Flags, SelectionDAG &DAG,
1488                           DebugLoc dl) {
1489   SDValue SizeNode = DAG.getConstant(Flags.getByValSize(), MVT::i32);
1490
1491   return DAG.getMemcpy(Chain, dl, Dst, Src, SizeNode, Flags.getByValAlign(),
1492                        /*isVolatile*/false, /*AlwaysInline=*/true,
1493                        MachinePointerInfo(), MachinePointerInfo());
1494 }
1495
1496 /// IsTailCallConvention - Return true if the calling convention is one that
1497 /// supports tail call optimization.
1498 static bool IsTailCallConvention(CallingConv::ID CC) {
1499   return (CC == CallingConv::Fast || CC == CallingConv::GHC);
1500 }
1501
1502 /// FuncIsMadeTailCallSafe - Return true if the function is being made into
1503 /// a tailcall target by changing its ABI.
1504 static bool FuncIsMadeTailCallSafe(CallingConv::ID CC) {
1505   return GuaranteedTailCallOpt && IsTailCallConvention(CC);
1506 }
1507
1508 SDValue
1509 X86TargetLowering::LowerMemArgument(SDValue Chain,
1510                                     CallingConv::ID CallConv,
1511                                     const SmallVectorImpl<ISD::InputArg> &Ins,
1512                                     DebugLoc dl, SelectionDAG &DAG,
1513                                     const CCValAssign &VA,
1514                                     MachineFrameInfo *MFI,
1515                                     unsigned i) const {
1516   // Create the nodes corresponding to a load from this parameter slot.
1517   ISD::ArgFlagsTy Flags = Ins[i].Flags;
1518   bool AlwaysUseMutable = FuncIsMadeTailCallSafe(CallConv);
1519   bool isImmutable = !AlwaysUseMutable && !Flags.isByVal();
1520   EVT ValVT;
1521
1522   // If value is passed by pointer we have address passed instead of the value
1523   // itself.
1524   if (VA.getLocInfo() == CCValAssign::Indirect)
1525     ValVT = VA.getLocVT();
1526   else
1527     ValVT = VA.getValVT();
1528
1529   // FIXME: For now, all byval parameter objects are marked mutable. This can be
1530   // changed with more analysis.
1531   // In case of tail call optimization mark all arguments mutable. Since they
1532   // could be overwritten by lowering of arguments in case of a tail call.
1533   if (Flags.isByVal()) {
1534     int FI = MFI->CreateFixedObject(Flags.getByValSize(),
1535                                     VA.getLocMemOffset(), isImmutable);
1536     return DAG.getFrameIndex(FI, getPointerTy());
1537   } else {
1538     int FI = MFI->CreateFixedObject(ValVT.getSizeInBits()/8,
1539                                     VA.getLocMemOffset(), isImmutable);
1540     SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
1541     return DAG.getLoad(ValVT, dl, Chain, FIN,
1542                        MachinePointerInfo::getFixedStack(FI),
1543                        false, false, 0);
1544   }
1545 }
1546
1547 SDValue
1548 X86TargetLowering::LowerFormalArguments(SDValue Chain,
1549                                         CallingConv::ID CallConv,
1550                                         bool isVarArg,
1551                                       const SmallVectorImpl<ISD::InputArg> &Ins,
1552                                         DebugLoc dl,
1553                                         SelectionDAG &DAG,
1554                                         SmallVectorImpl<SDValue> &InVals)
1555                                           const {
1556   MachineFunction &MF = DAG.getMachineFunction();
1557   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1558
1559   const Function* Fn = MF.getFunction();
1560   if (Fn->hasExternalLinkage() &&
1561       Subtarget->isTargetCygMing() &&
1562       Fn->getName() == "main")
1563     FuncInfo->setForceFramePointer(true);
1564
1565   MachineFrameInfo *MFI = MF.getFrameInfo();
1566   bool Is64Bit = Subtarget->is64Bit();
1567   bool IsWin64 = Subtarget->isTargetWin64();
1568
1569   assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
1570          "Var args not supported with calling convention fastcc or ghc");
1571
1572   // Assign locations to all of the incoming arguments.
1573   SmallVector<CCValAssign, 16> ArgLocs;
1574   CCState CCInfo(CallConv, isVarArg, getTargetMachine(),
1575                  ArgLocs, *DAG.getContext());
1576   CCInfo.AnalyzeFormalArguments(Ins, CC_X86);
1577
1578   unsigned LastVal = ~0U;
1579   SDValue ArgValue;
1580   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
1581     CCValAssign &VA = ArgLocs[i];
1582     // TODO: If an arg is passed in two places (e.g. reg and stack), skip later
1583     // places.
1584     assert(VA.getValNo() != LastVal &&
1585            "Don't support value assigned to multiple locs yet");
1586     LastVal = VA.getValNo();
1587
1588     if (VA.isRegLoc()) {
1589       EVT RegVT = VA.getLocVT();
1590       TargetRegisterClass *RC = NULL;
1591       if (RegVT == MVT::i32)
1592         RC = X86::GR32RegisterClass;
1593       else if (Is64Bit && RegVT == MVT::i64)
1594         RC = X86::GR64RegisterClass;
1595       else if (RegVT == MVT::f32)
1596         RC = X86::FR32RegisterClass;
1597       else if (RegVT == MVT::f64)
1598         RC = X86::FR64RegisterClass;
1599       else if (RegVT.isVector() && RegVT.getSizeInBits() == 256)
1600         RC = X86::VR256RegisterClass;
1601       else if (RegVT.isVector() && RegVT.getSizeInBits() == 128)
1602         RC = X86::VR128RegisterClass;
1603       else if (RegVT == MVT::x86mmx)
1604         RC = X86::VR64RegisterClass;
1605       else
1606         llvm_unreachable("Unknown argument type!");
1607
1608       unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
1609       ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
1610
1611       // If this is an 8 or 16-bit value, it is really passed promoted to 32
1612       // bits.  Insert an assert[sz]ext to capture this, then truncate to the
1613       // right size.
1614       if (VA.getLocInfo() == CCValAssign::SExt)
1615         ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
1616                                DAG.getValueType(VA.getValVT()));
1617       else if (VA.getLocInfo() == CCValAssign::ZExt)
1618         ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
1619                                DAG.getValueType(VA.getValVT()));
1620       else if (VA.getLocInfo() == CCValAssign::BCvt)
1621         ArgValue = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), ArgValue);
1622
1623       if (VA.isExtInLoc()) {
1624         // Handle MMX values passed in XMM regs.
1625         if (RegVT.isVector()) {
1626           ArgValue = DAG.getNode(X86ISD::MOVDQ2Q, dl, VA.getValVT(),
1627                                  ArgValue);
1628         } else
1629           ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
1630       }
1631     } else {
1632       assert(VA.isMemLoc());
1633       ArgValue = LowerMemArgument(Chain, CallConv, Ins, dl, DAG, VA, MFI, i);
1634     }
1635
1636     // If value is passed via pointer - do a load.
1637     if (VA.getLocInfo() == CCValAssign::Indirect)
1638       ArgValue = DAG.getLoad(VA.getValVT(), dl, Chain, ArgValue,
1639                              MachinePointerInfo(), false, false, 0);
1640
1641     InVals.push_back(ArgValue);
1642   }
1643
1644   // The x86-64 ABI for returning structs by value requires that we copy
1645   // the sret argument into %rax for the return. Save the argument into
1646   // a virtual register so that we can access it from the return points.
1647   if (Is64Bit && MF.getFunction()->hasStructRetAttr()) {
1648     X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1649     unsigned Reg = FuncInfo->getSRetReturnReg();
1650     if (!Reg) {
1651       Reg = MF.getRegInfo().createVirtualRegister(getRegClassFor(MVT::i64));
1652       FuncInfo->setSRetReturnReg(Reg);
1653     }
1654     SDValue Copy = DAG.getCopyToReg(DAG.getEntryNode(), dl, Reg, InVals[0]);
1655     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Copy, Chain);
1656   }
1657
1658   unsigned StackSize = CCInfo.getNextStackOffset();
1659   // Align stack specially for tail calls.
1660   if (FuncIsMadeTailCallSafe(CallConv))
1661     StackSize = GetAlignedArgumentStackSize(StackSize, DAG);
1662
1663   // If the function takes variable number of arguments, make a frame index for
1664   // the start of the first vararg value... for expansion of llvm.va_start.
1665   if (isVarArg) {
1666     if (!IsWin64 && (Is64Bit || (CallConv != CallingConv::X86_FastCall &&
1667                     CallConv != CallingConv::X86_ThisCall))) {
1668       FuncInfo->setVarArgsFrameIndex(MFI->CreateFixedObject(1, StackSize,true));
1669     }
1670     if (Is64Bit) {
1671       unsigned TotalNumIntRegs = 0, TotalNumXMMRegs = 0;
1672
1673       // FIXME: We should really autogenerate these arrays
1674       static const unsigned GPR64ArgRegsWin64[] = {
1675         X86::RCX, X86::RDX, X86::R8,  X86::R9
1676       };
1677       static const unsigned GPR64ArgRegs64Bit[] = {
1678         X86::RDI, X86::RSI, X86::RDX, X86::RCX, X86::R8, X86::R9
1679       };
1680       static const unsigned XMMArgRegs64Bit[] = {
1681         X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
1682         X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
1683       };
1684       const unsigned *GPR64ArgRegs;
1685       unsigned NumXMMRegs = 0;
1686
1687       if (IsWin64) {
1688         // The XMM registers which might contain var arg parameters are shadowed
1689         // in their paired GPR.  So we only need to save the GPR to their home
1690         // slots.
1691         TotalNumIntRegs = 4;
1692         GPR64ArgRegs = GPR64ArgRegsWin64;
1693       } else {
1694         TotalNumIntRegs = 6; TotalNumXMMRegs = 8;
1695         GPR64ArgRegs = GPR64ArgRegs64Bit;
1696
1697         NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs64Bit, TotalNumXMMRegs);
1698       }
1699       unsigned NumIntRegs = CCInfo.getFirstUnallocated(GPR64ArgRegs,
1700                                                        TotalNumIntRegs);
1701
1702       bool NoImplicitFloatOps = Fn->hasFnAttr(Attribute::NoImplicitFloat);
1703       assert(!(NumXMMRegs && !Subtarget->hasXMM()) &&
1704              "SSE register cannot be used when SSE is disabled!");
1705       assert(!(NumXMMRegs && UseSoftFloat && NoImplicitFloatOps) &&
1706              "SSE register cannot be used when SSE is disabled!");
1707       if (UseSoftFloat || NoImplicitFloatOps || !Subtarget->hasXMM())
1708         // Kernel mode asks for SSE to be disabled, so don't push them
1709         // on the stack.
1710         TotalNumXMMRegs = 0;
1711
1712       if (IsWin64) {
1713         const TargetFrameInfo &TFI = *getTargetMachine().getFrameInfo();
1714         // Get to the caller-allocated home save location.  Add 8 to account
1715         // for the return address.
1716         int HomeOffset = TFI.getOffsetOfLocalArea() + 8;
1717         FuncInfo->setRegSaveFrameIndex(
1718           MFI->CreateFixedObject(1, NumIntRegs * 8 + HomeOffset, false));
1719         FuncInfo->setVarArgsFrameIndex(FuncInfo->getRegSaveFrameIndex());
1720       } else {
1721         // For X86-64, if there are vararg parameters that are passed via
1722         // registers, then we must store them to their spots on the stack so they
1723         // may be loaded by deferencing the result of va_next.
1724         FuncInfo->setVarArgsGPOffset(NumIntRegs * 8);
1725         FuncInfo->setVarArgsFPOffset(TotalNumIntRegs * 8 + NumXMMRegs * 16);
1726         FuncInfo->setRegSaveFrameIndex(
1727           MFI->CreateStackObject(TotalNumIntRegs * 8 + TotalNumXMMRegs * 16, 16,
1728                                false));
1729       }
1730
1731       // Store the integer parameter registers.
1732       SmallVector<SDValue, 8> MemOps;
1733       SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
1734                                         getPointerTy());
1735       unsigned Offset = FuncInfo->getVarArgsGPOffset();
1736       for (; NumIntRegs != TotalNumIntRegs; ++NumIntRegs) {
1737         SDValue FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(), RSFIN,
1738                                   DAG.getIntPtrConstant(Offset));
1739         unsigned VReg = MF.addLiveIn(GPR64ArgRegs[NumIntRegs],
1740                                      X86::GR64RegisterClass);
1741         SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
1742         SDValue Store =
1743           DAG.getStore(Val.getValue(1), dl, Val, FIN,
1744                        MachinePointerInfo::getFixedStack(
1745                          FuncInfo->getRegSaveFrameIndex(), Offset),
1746                        false, false, 0);
1747         MemOps.push_back(Store);
1748         Offset += 8;
1749       }
1750
1751       if (TotalNumXMMRegs != 0 && NumXMMRegs != TotalNumXMMRegs) {
1752         // Now store the XMM (fp + vector) parameter registers.
1753         SmallVector<SDValue, 11> SaveXMMOps;
1754         SaveXMMOps.push_back(Chain);
1755
1756         unsigned AL = MF.addLiveIn(X86::AL, X86::GR8RegisterClass);
1757         SDValue ALVal = DAG.getCopyFromReg(DAG.getEntryNode(), dl, AL, MVT::i8);
1758         SaveXMMOps.push_back(ALVal);
1759
1760         SaveXMMOps.push_back(DAG.getIntPtrConstant(
1761                                FuncInfo->getRegSaveFrameIndex()));
1762         SaveXMMOps.push_back(DAG.getIntPtrConstant(
1763                                FuncInfo->getVarArgsFPOffset()));
1764
1765         for (; NumXMMRegs != TotalNumXMMRegs; ++NumXMMRegs) {
1766           unsigned VReg = MF.addLiveIn(XMMArgRegs64Bit[NumXMMRegs],
1767                                        X86::VR128RegisterClass);
1768           SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::v4f32);
1769           SaveXMMOps.push_back(Val);
1770         }
1771         MemOps.push_back(DAG.getNode(X86ISD::VASTART_SAVE_XMM_REGS, dl,
1772                                      MVT::Other,
1773                                      &SaveXMMOps[0], SaveXMMOps.size()));
1774       }
1775
1776       if (!MemOps.empty())
1777         Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
1778                             &MemOps[0], MemOps.size());
1779     }
1780   }
1781
1782   // Some CCs need callee pop.
1783   if (Subtarget->IsCalleePop(isVarArg, CallConv)) {
1784     FuncInfo->setBytesToPopOnReturn(StackSize); // Callee pops everything.
1785   } else {
1786     FuncInfo->setBytesToPopOnReturn(0); // Callee pops nothing.
1787     // If this is an sret function, the return should pop the hidden pointer.
1788     if (!Is64Bit && !IsTailCallConvention(CallConv) && ArgsAreStructReturn(Ins))
1789       FuncInfo->setBytesToPopOnReturn(4);
1790   }
1791
1792   if (!Is64Bit) {
1793     // RegSaveFrameIndex is X86-64 only.
1794     FuncInfo->setRegSaveFrameIndex(0xAAAAAAA);
1795     if (CallConv == CallingConv::X86_FastCall ||
1796         CallConv == CallingConv::X86_ThisCall)
1797       // fastcc functions can't have varargs.
1798       FuncInfo->setVarArgsFrameIndex(0xAAAAAAA);
1799   }
1800
1801   return Chain;
1802 }
1803
1804 SDValue
1805 X86TargetLowering::LowerMemOpCallTo(SDValue Chain,
1806                                     SDValue StackPtr, SDValue Arg,
1807                                     DebugLoc dl, SelectionDAG &DAG,
1808                                     const CCValAssign &VA,
1809                                     ISD::ArgFlagsTy Flags) const {
1810   const unsigned FirstStackArgOffset = (Subtarget->isTargetWin64() ? 32 : 0);
1811   unsigned LocMemOffset = FirstStackArgOffset + VA.getLocMemOffset();
1812   SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset);
1813   PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, PtrOff);
1814   if (Flags.isByVal())
1815     return CreateCopyOfByValArgument(Arg, PtrOff, Chain, Flags, DAG, dl);
1816
1817   return DAG.getStore(Chain, dl, Arg, PtrOff,
1818                       MachinePointerInfo::getStack(LocMemOffset),
1819                       false, false, 0);
1820 }
1821
1822 /// EmitTailCallLoadRetAddr - Emit a load of return address if tail call
1823 /// optimization is performed and it is required.
1824 SDValue
1825 X86TargetLowering::EmitTailCallLoadRetAddr(SelectionDAG &DAG,
1826                                            SDValue &OutRetAddr, SDValue Chain,
1827                                            bool IsTailCall, bool Is64Bit,
1828                                            int FPDiff, DebugLoc dl) const {
1829   // Adjust the Return address stack slot.
1830   EVT VT = getPointerTy();
1831   OutRetAddr = getReturnAddressFrameIndex(DAG);
1832
1833   // Load the "old" Return address.
1834   OutRetAddr = DAG.getLoad(VT, dl, Chain, OutRetAddr, MachinePointerInfo(),
1835                            false, false, 0);
1836   return SDValue(OutRetAddr.getNode(), 1);
1837 }
1838
1839 /// EmitTailCallStoreRetAddr - Emit a store of the return adress if tail call
1840 /// optimization is performed and it is required (FPDiff!=0).
1841 static SDValue
1842 EmitTailCallStoreRetAddr(SelectionDAG & DAG, MachineFunction &MF,
1843                          SDValue Chain, SDValue RetAddrFrIdx,
1844                          bool Is64Bit, int FPDiff, DebugLoc dl) {
1845   // Store the return address to the appropriate stack slot.
1846   if (!FPDiff) return Chain;
1847   // Calculate the new stack slot for the return address.
1848   int SlotSize = Is64Bit ? 8 : 4;
1849   int NewReturnAddrFI =
1850     MF.getFrameInfo()->CreateFixedObject(SlotSize, FPDiff-SlotSize, false);
1851   EVT VT = Is64Bit ? MVT::i64 : MVT::i32;
1852   SDValue NewRetAddrFrIdx = DAG.getFrameIndex(NewReturnAddrFI, VT);
1853   Chain = DAG.getStore(Chain, dl, RetAddrFrIdx, NewRetAddrFrIdx,
1854                        MachinePointerInfo::getFixedStack(NewReturnAddrFI),
1855                        false, false, 0);
1856   return Chain;
1857 }
1858
1859 SDValue
1860 X86TargetLowering::LowerCall(SDValue Chain, SDValue Callee,
1861                              CallingConv::ID CallConv, bool isVarArg,
1862                              bool &isTailCall,
1863                              const SmallVectorImpl<ISD::OutputArg> &Outs,
1864                              const SmallVectorImpl<SDValue> &OutVals,
1865                              const SmallVectorImpl<ISD::InputArg> &Ins,
1866                              DebugLoc dl, SelectionDAG &DAG,
1867                              SmallVectorImpl<SDValue> &InVals) const {
1868   MachineFunction &MF = DAG.getMachineFunction();
1869   bool Is64Bit        = Subtarget->is64Bit();
1870   bool IsStructRet    = CallIsStructReturn(Outs);
1871   bool IsSibcall      = false;
1872
1873   if (isTailCall) {
1874     // Check if it's really possible to do a tail call.
1875     isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv,
1876                     isVarArg, IsStructRet, MF.getFunction()->hasStructRetAttr(),
1877                                                    Outs, OutVals, Ins, DAG);
1878
1879     // Sibcalls are automatically detected tailcalls which do not require
1880     // ABI changes.
1881     if (!GuaranteedTailCallOpt && isTailCall)
1882       IsSibcall = true;
1883
1884     if (isTailCall)
1885       ++NumTailCalls;
1886   }
1887
1888   assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
1889          "Var args not supported with calling convention fastcc or ghc");
1890
1891   // Analyze operands of the call, assigning locations to each operand.
1892   SmallVector<CCValAssign, 16> ArgLocs;
1893   CCState CCInfo(CallConv, isVarArg, getTargetMachine(),
1894                  ArgLocs, *DAG.getContext());
1895   CCInfo.AnalyzeCallOperands(Outs, CC_X86);
1896
1897   // Get a count of how many bytes are to be pushed on the stack.
1898   unsigned NumBytes = CCInfo.getNextStackOffset();
1899   if (IsSibcall)
1900     // This is a sibcall. The memory operands are available in caller's
1901     // own caller's stack.
1902     NumBytes = 0;
1903   else if (GuaranteedTailCallOpt && IsTailCallConvention(CallConv))
1904     NumBytes = GetAlignedArgumentStackSize(NumBytes, DAG);
1905
1906   int FPDiff = 0;
1907   if (isTailCall && !IsSibcall) {
1908     // Lower arguments at fp - stackoffset + fpdiff.
1909     unsigned NumBytesCallerPushed =
1910       MF.getInfo<X86MachineFunctionInfo>()->getBytesToPopOnReturn();
1911     FPDiff = NumBytesCallerPushed - NumBytes;
1912
1913     // Set the delta of movement of the returnaddr stackslot.
1914     // But only set if delta is greater than previous delta.
1915     if (FPDiff < (MF.getInfo<X86MachineFunctionInfo>()->getTCReturnAddrDelta()))
1916       MF.getInfo<X86MachineFunctionInfo>()->setTCReturnAddrDelta(FPDiff);
1917   }
1918
1919   if (!IsSibcall)
1920     Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes, true));
1921
1922   SDValue RetAddrFrIdx;
1923   // Load return adress for tail calls.
1924   if (isTailCall && FPDiff)
1925     Chain = EmitTailCallLoadRetAddr(DAG, RetAddrFrIdx, Chain, isTailCall,
1926                                     Is64Bit, FPDiff, dl);
1927
1928   SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
1929   SmallVector<SDValue, 8> MemOpChains;
1930   SDValue StackPtr;
1931
1932   // Walk the register/memloc assignments, inserting copies/loads.  In the case
1933   // of tail call optimization arguments are handle later.
1934   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
1935     CCValAssign &VA = ArgLocs[i];
1936     EVT RegVT = VA.getLocVT();
1937     SDValue Arg = OutVals[i];
1938     ISD::ArgFlagsTy Flags = Outs[i].Flags;
1939     bool isByVal = Flags.isByVal();
1940
1941     // Promote the value if needed.
1942     switch (VA.getLocInfo()) {
1943     default: llvm_unreachable("Unknown loc info!");
1944     case CCValAssign::Full: break;
1945     case CCValAssign::SExt:
1946       Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, RegVT, Arg);
1947       break;
1948     case CCValAssign::ZExt:
1949       Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, RegVT, Arg);
1950       break;
1951     case CCValAssign::AExt:
1952       if (RegVT.isVector() && RegVT.getSizeInBits() == 128) {
1953         // Special case: passing MMX values in XMM registers.
1954         Arg = DAG.getNode(ISD::BITCAST, dl, MVT::i64, Arg);
1955         Arg = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64, Arg);
1956         Arg = getMOVL(DAG, dl, MVT::v2i64, DAG.getUNDEF(MVT::v2i64), Arg);
1957       } else
1958         Arg = DAG.getNode(ISD::ANY_EXTEND, dl, RegVT, Arg);
1959       break;
1960     case CCValAssign::BCvt:
1961       Arg = DAG.getNode(ISD::BITCAST, dl, RegVT, Arg);
1962       break;
1963     case CCValAssign::Indirect: {
1964       // Store the argument.
1965       SDValue SpillSlot = DAG.CreateStackTemporary(VA.getValVT());
1966       int FI = cast<FrameIndexSDNode>(SpillSlot)->getIndex();
1967       Chain = DAG.getStore(Chain, dl, Arg, SpillSlot,
1968                            MachinePointerInfo::getFixedStack(FI),
1969                            false, false, 0);
1970       Arg = SpillSlot;
1971       break;
1972     }
1973     }
1974
1975     if (VA.isRegLoc()) {
1976       RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
1977       if (isVarArg && Subtarget->isTargetWin64()) {
1978         // Win64 ABI requires argument XMM reg to be copied to the corresponding
1979         // shadow reg if callee is a varargs function.
1980         unsigned ShadowReg = 0;
1981         switch (VA.getLocReg()) {
1982         case X86::XMM0: ShadowReg = X86::RCX; break;
1983         case X86::XMM1: ShadowReg = X86::RDX; break;
1984         case X86::XMM2: ShadowReg = X86::R8; break;
1985         case X86::XMM3: ShadowReg = X86::R9; break;
1986         }
1987         if (ShadowReg)
1988           RegsToPass.push_back(std::make_pair(ShadowReg, Arg));
1989       }
1990     } else if (!IsSibcall && (!isTailCall || isByVal)) {
1991       assert(VA.isMemLoc());
1992       if (StackPtr.getNode() == 0)
1993         StackPtr = DAG.getCopyFromReg(Chain, dl, X86StackPtr, getPointerTy());
1994       MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg,
1995                                              dl, DAG, VA, Flags));
1996     }
1997   }
1998
1999   if (!MemOpChains.empty())
2000     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
2001                         &MemOpChains[0], MemOpChains.size());
2002
2003   // Build a sequence of copy-to-reg nodes chained together with token chain
2004   // and flag operands which copy the outgoing args into registers.
2005   SDValue InFlag;
2006   // Tail call byval lowering might overwrite argument registers so in case of
2007   // tail call optimization the copies to registers are lowered later.
2008   if (!isTailCall)
2009     for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
2010       Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
2011                                RegsToPass[i].second, InFlag);
2012       InFlag = Chain.getValue(1);
2013     }
2014
2015   if (Subtarget->isPICStyleGOT()) {
2016     // ELF / PIC requires GOT in the EBX register before function calls via PLT
2017     // GOT pointer.
2018     if (!isTailCall) {
2019       Chain = DAG.getCopyToReg(Chain, dl, X86::EBX,
2020                                DAG.getNode(X86ISD::GlobalBaseReg,
2021                                            DebugLoc(), getPointerTy()),
2022                                InFlag);
2023       InFlag = Chain.getValue(1);
2024     } else {
2025       // If we are tail calling and generating PIC/GOT style code load the
2026       // address of the callee into ECX. The value in ecx is used as target of
2027       // the tail jump. This is done to circumvent the ebx/callee-saved problem
2028       // for tail calls on PIC/GOT architectures. Normally we would just put the
2029       // address of GOT into ebx and then call target@PLT. But for tail calls
2030       // ebx would be restored (since ebx is callee saved) before jumping to the
2031       // target@PLT.
2032
2033       // Note: The actual moving to ECX is done further down.
2034       GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee);
2035       if (G && !G->getGlobal()->hasHiddenVisibility() &&
2036           !G->getGlobal()->hasProtectedVisibility())
2037         Callee = LowerGlobalAddress(Callee, DAG);
2038       else if (isa<ExternalSymbolSDNode>(Callee))
2039         Callee = LowerExternalSymbol(Callee, DAG);
2040     }
2041   }
2042
2043   if (Is64Bit && isVarArg && !Subtarget->isTargetWin64()) {
2044     // From AMD64 ABI document:
2045     // For calls that may call functions that use varargs or stdargs
2046     // (prototype-less calls or calls to functions containing ellipsis (...) in
2047     // the declaration) %al is used as hidden argument to specify the number
2048     // of SSE registers used. The contents of %al do not need to match exactly
2049     // the number of registers, but must be an ubound on the number of SSE
2050     // registers used and is in the range 0 - 8 inclusive.
2051
2052     // Count the number of XMM registers allocated.
2053     static const unsigned XMMArgRegs[] = {
2054       X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
2055       X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
2056     };
2057     unsigned NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs, 8);
2058     assert((Subtarget->hasXMM() || !NumXMMRegs)
2059            && "SSE registers cannot be used when SSE is disabled");
2060
2061     Chain = DAG.getCopyToReg(Chain, dl, X86::AL,
2062                              DAG.getConstant(NumXMMRegs, MVT::i8), InFlag);
2063     InFlag = Chain.getValue(1);
2064   }
2065
2066
2067   // For tail calls lower the arguments to the 'real' stack slot.
2068   if (isTailCall) {
2069     // Force all the incoming stack arguments to be loaded from the stack
2070     // before any new outgoing arguments are stored to the stack, because the
2071     // outgoing stack slots may alias the incoming argument stack slots, and
2072     // the alias isn't otherwise explicit. This is slightly more conservative
2073     // than necessary, because it means that each store effectively depends
2074     // on every argument instead of just those arguments it would clobber.
2075     SDValue ArgChain = DAG.getStackArgumentTokenFactor(Chain);
2076
2077     SmallVector<SDValue, 8> MemOpChains2;
2078     SDValue FIN;
2079     int FI = 0;
2080     // Do not flag preceeding copytoreg stuff together with the following stuff.
2081     InFlag = SDValue();
2082     if (GuaranteedTailCallOpt) {
2083       for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2084         CCValAssign &VA = ArgLocs[i];
2085         if (VA.isRegLoc())
2086           continue;
2087         assert(VA.isMemLoc());
2088         SDValue Arg = OutVals[i];
2089         ISD::ArgFlagsTy Flags = Outs[i].Flags;
2090         // Create frame index.
2091         int32_t Offset = VA.getLocMemOffset()+FPDiff;
2092         uint32_t OpSize = (VA.getLocVT().getSizeInBits()+7)/8;
2093         FI = MF.getFrameInfo()->CreateFixedObject(OpSize, Offset, true);
2094         FIN = DAG.getFrameIndex(FI, getPointerTy());
2095
2096         if (Flags.isByVal()) {
2097           // Copy relative to framepointer.
2098           SDValue Source = DAG.getIntPtrConstant(VA.getLocMemOffset());
2099           if (StackPtr.getNode() == 0)
2100             StackPtr = DAG.getCopyFromReg(Chain, dl, X86StackPtr,
2101                                           getPointerTy());
2102           Source = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, Source);
2103
2104           MemOpChains2.push_back(CreateCopyOfByValArgument(Source, FIN,
2105                                                            ArgChain,
2106                                                            Flags, DAG, dl));
2107         } else {
2108           // Store relative to framepointer.
2109           MemOpChains2.push_back(
2110             DAG.getStore(ArgChain, dl, Arg, FIN,
2111                          MachinePointerInfo::getFixedStack(FI),
2112                          false, false, 0));
2113         }
2114       }
2115     }
2116
2117     if (!MemOpChains2.empty())
2118       Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
2119                           &MemOpChains2[0], MemOpChains2.size());
2120
2121     // Copy arguments to their registers.
2122     for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
2123       Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
2124                                RegsToPass[i].second, InFlag);
2125       InFlag = Chain.getValue(1);
2126     }
2127     InFlag =SDValue();
2128
2129     // Store the return address to the appropriate stack slot.
2130     Chain = EmitTailCallStoreRetAddr(DAG, MF, Chain, RetAddrFrIdx, Is64Bit,
2131                                      FPDiff, dl);
2132   }
2133
2134   if (getTargetMachine().getCodeModel() == CodeModel::Large) {
2135     assert(Is64Bit && "Large code model is only legal in 64-bit mode.");
2136     // In the 64-bit large code model, we have to make all calls
2137     // through a register, since the call instruction's 32-bit
2138     // pc-relative offset may not be large enough to hold the whole
2139     // address.
2140   } else if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
2141     // If the callee is a GlobalAddress node (quite common, every direct call
2142     // is) turn it into a TargetGlobalAddress node so that legalize doesn't hack
2143     // it.
2144
2145     // We should use extra load for direct calls to dllimported functions in
2146     // non-JIT mode.
2147     const GlobalValue *GV = G->getGlobal();
2148     if (!GV->hasDLLImportLinkage()) {
2149       unsigned char OpFlags = 0;
2150
2151       // On ELF targets, in both X86-64 and X86-32 mode, direct calls to
2152       // external symbols most go through the PLT in PIC mode.  If the symbol
2153       // has hidden or protected visibility, or if it is static or local, then
2154       // we don't need to use the PLT - we can directly call it.
2155       if (Subtarget->isTargetELF() &&
2156           getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
2157           GV->hasDefaultVisibility() && !GV->hasLocalLinkage()) {
2158         OpFlags = X86II::MO_PLT;
2159       } else if (Subtarget->isPICStyleStubAny() &&
2160                  (GV->isDeclaration() || GV->isWeakForLinker()) &&
2161                  Subtarget->getDarwinVers() < 9) {
2162         // PC-relative references to external symbols should go through $stub,
2163         // unless we're building with the leopard linker or later, which
2164         // automatically synthesizes these stubs.
2165         OpFlags = X86II::MO_DARWIN_STUB;
2166       }
2167
2168       Callee = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(),
2169                                           G->getOffset(), OpFlags);
2170     }
2171   } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
2172     unsigned char OpFlags = 0;
2173
2174     // On ELF targets, in either X86-64 or X86-32 mode, direct calls to
2175     // external symbols should go through the PLT.
2176     if (Subtarget->isTargetELF() &&
2177         getTargetMachine().getRelocationModel() == Reloc::PIC_) {
2178       OpFlags = X86II::MO_PLT;
2179     } else if (Subtarget->isPICStyleStubAny() &&
2180                Subtarget->getDarwinVers() < 9) {
2181       // PC-relative references to external symbols should go through $stub,
2182       // unless we're building with the leopard linker or later, which
2183       // automatically synthesizes these stubs.
2184       OpFlags = X86II::MO_DARWIN_STUB;
2185     }
2186
2187     Callee = DAG.getTargetExternalSymbol(S->getSymbol(), getPointerTy(),
2188                                          OpFlags);
2189   }
2190
2191   // Returns a chain & a flag for retval copy to use.
2192   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Flag);
2193   SmallVector<SDValue, 8> Ops;
2194
2195   if (!IsSibcall && isTailCall) {
2196     Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, true),
2197                            DAG.getIntPtrConstant(0, true), InFlag);
2198     InFlag = Chain.getValue(1);
2199   }
2200
2201   Ops.push_back(Chain);
2202   Ops.push_back(Callee);
2203
2204   if (isTailCall)
2205     Ops.push_back(DAG.getConstant(FPDiff, MVT::i32));
2206
2207   // Add argument registers to the end of the list so that they are known live
2208   // into the call.
2209   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
2210     Ops.push_back(DAG.getRegister(RegsToPass[i].first,
2211                                   RegsToPass[i].second.getValueType()));
2212
2213   // Add an implicit use GOT pointer in EBX.
2214   if (!isTailCall && Subtarget->isPICStyleGOT())
2215     Ops.push_back(DAG.getRegister(X86::EBX, getPointerTy()));
2216
2217   // Add an implicit use of AL for non-Windows x86 64-bit vararg functions.
2218   if (Is64Bit && isVarArg && !Subtarget->isTargetWin64())
2219     Ops.push_back(DAG.getRegister(X86::AL, MVT::i8));
2220
2221   if (InFlag.getNode())
2222     Ops.push_back(InFlag);
2223
2224   if (isTailCall) {
2225     // We used to do:
2226     //// If this is the first return lowered for this function, add the regs
2227     //// to the liveout set for the function.
2228     // This isn't right, although it's probably harmless on x86; liveouts
2229     // should be computed from returns not tail calls.  Consider a void
2230     // function making a tail call to a function returning int.
2231     return DAG.getNode(X86ISD::TC_RETURN, dl,
2232                        NodeTys, &Ops[0], Ops.size());
2233   }
2234
2235   Chain = DAG.getNode(X86ISD::CALL, dl, NodeTys, &Ops[0], Ops.size());
2236   InFlag = Chain.getValue(1);
2237
2238   // Create the CALLSEQ_END node.
2239   unsigned NumBytesForCalleeToPush;
2240   if (Subtarget->IsCalleePop(isVarArg, CallConv))
2241     NumBytesForCalleeToPush = NumBytes;    // Callee pops everything
2242   else if (!Is64Bit && !IsTailCallConvention(CallConv) && IsStructRet)
2243     // If this is a call to a struct-return function, the callee
2244     // pops the hidden struct pointer, so we have to push it back.
2245     // This is common for Darwin/X86, Linux & Mingw32 targets.
2246     NumBytesForCalleeToPush = 4;
2247   else
2248     NumBytesForCalleeToPush = 0;  // Callee pops nothing.
2249
2250   // Returns a flag for retval copy to use.
2251   if (!IsSibcall) {
2252     Chain = DAG.getCALLSEQ_END(Chain,
2253                                DAG.getIntPtrConstant(NumBytes, true),
2254                                DAG.getIntPtrConstant(NumBytesForCalleeToPush,
2255                                                      true),
2256                                InFlag);
2257     InFlag = Chain.getValue(1);
2258   }
2259
2260   // Handle result values, copying them out of physregs into vregs that we
2261   // return.
2262   return LowerCallResult(Chain, InFlag, CallConv, isVarArg,
2263                          Ins, dl, DAG, InVals);
2264 }
2265
2266
2267 //===----------------------------------------------------------------------===//
2268 //                Fast Calling Convention (tail call) implementation
2269 //===----------------------------------------------------------------------===//
2270
2271 //  Like std call, callee cleans arguments, convention except that ECX is
2272 //  reserved for storing the tail called function address. Only 2 registers are
2273 //  free for argument passing (inreg). Tail call optimization is performed
2274 //  provided:
2275 //                * tailcallopt is enabled
2276 //                * caller/callee are fastcc
2277 //  On X86_64 architecture with GOT-style position independent code only local
2278 //  (within module) calls are supported at the moment.
2279 //  To keep the stack aligned according to platform abi the function
2280 //  GetAlignedArgumentStackSize ensures that argument delta is always multiples
2281 //  of stack alignment. (Dynamic linkers need this - darwin's dyld for example)
2282 //  If a tail called function callee has more arguments than the caller the
2283 //  caller needs to make sure that there is room to move the RETADDR to. This is
2284 //  achieved by reserving an area the size of the argument delta right after the
2285 //  original REtADDR, but before the saved framepointer or the spilled registers
2286 //  e.g. caller(arg1, arg2) calls callee(arg1, arg2,arg3,arg4)
2287 //  stack layout:
2288 //    arg1
2289 //    arg2
2290 //    RETADDR
2291 //    [ new RETADDR
2292 //      move area ]
2293 //    (possible EBP)
2294 //    ESI
2295 //    EDI
2296 //    local1 ..
2297
2298 /// GetAlignedArgumentStackSize - Make the stack size align e.g 16n + 12 aligned
2299 /// for a 16 byte align requirement.
2300 unsigned
2301 X86TargetLowering::GetAlignedArgumentStackSize(unsigned StackSize,
2302                                                SelectionDAG& DAG) const {
2303   MachineFunction &MF = DAG.getMachineFunction();
2304   const TargetMachine &TM = MF.getTarget();
2305   const TargetFrameInfo &TFI = *TM.getFrameInfo();
2306   unsigned StackAlignment = TFI.getStackAlignment();
2307   uint64_t AlignMask = StackAlignment - 1;
2308   int64_t Offset = StackSize;
2309   uint64_t SlotSize = TD->getPointerSize();
2310   if ( (Offset & AlignMask) <= (StackAlignment - SlotSize) ) {
2311     // Number smaller than 12 so just add the difference.
2312     Offset += ((StackAlignment - SlotSize) - (Offset & AlignMask));
2313   } else {
2314     // Mask out lower bits, add stackalignment once plus the 12 bytes.
2315     Offset = ((~AlignMask) & Offset) + StackAlignment +
2316       (StackAlignment-SlotSize);
2317   }
2318   return Offset;
2319 }
2320
2321 /// MatchingStackOffset - Return true if the given stack call argument is
2322 /// already available in the same position (relatively) of the caller's
2323 /// incoming argument stack.
2324 static
2325 bool MatchingStackOffset(SDValue Arg, unsigned Offset, ISD::ArgFlagsTy Flags,
2326                          MachineFrameInfo *MFI, const MachineRegisterInfo *MRI,
2327                          const X86InstrInfo *TII) {
2328   unsigned Bytes = Arg.getValueType().getSizeInBits() / 8;
2329   int FI = INT_MAX;
2330   if (Arg.getOpcode() == ISD::CopyFromReg) {
2331     unsigned VR = cast<RegisterSDNode>(Arg.getOperand(1))->getReg();
2332     if (!VR || TargetRegisterInfo::isPhysicalRegister(VR))
2333       return false;
2334     MachineInstr *Def = MRI->getVRegDef(VR);
2335     if (!Def)
2336       return false;
2337     if (!Flags.isByVal()) {
2338       if (!TII->isLoadFromStackSlot(Def, FI))
2339         return false;
2340     } else {
2341       unsigned Opcode = Def->getOpcode();
2342       if ((Opcode == X86::LEA32r || Opcode == X86::LEA64r) &&
2343           Def->getOperand(1).isFI()) {
2344         FI = Def->getOperand(1).getIndex();
2345         Bytes = Flags.getByValSize();
2346       } else
2347         return false;
2348     }
2349   } else if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Arg)) {
2350     if (Flags.isByVal())
2351       // ByVal argument is passed in as a pointer but it's now being
2352       // dereferenced. e.g.
2353       // define @foo(%struct.X* %A) {
2354       //   tail call @bar(%struct.X* byval %A)
2355       // }
2356       return false;
2357     SDValue Ptr = Ld->getBasePtr();
2358     FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr);
2359     if (!FINode)
2360       return false;
2361     FI = FINode->getIndex();
2362   } else
2363     return false;
2364
2365   assert(FI != INT_MAX);
2366   if (!MFI->isFixedObjectIndex(FI))
2367     return false;
2368   return Offset == MFI->getObjectOffset(FI) && Bytes == MFI->getObjectSize(FI);
2369 }
2370
2371 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
2372 /// for tail call optimization. Targets which want to do tail call
2373 /// optimization should implement this function.
2374 bool
2375 X86TargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
2376                                                      CallingConv::ID CalleeCC,
2377                                                      bool isVarArg,
2378                                                      bool isCalleeStructRet,
2379                                                      bool isCallerStructRet,
2380                                     const SmallVectorImpl<ISD::OutputArg> &Outs,
2381                                     const SmallVectorImpl<SDValue> &OutVals,
2382                                     const SmallVectorImpl<ISD::InputArg> &Ins,
2383                                                      SelectionDAG& DAG) const {
2384   if (!IsTailCallConvention(CalleeCC) &&
2385       CalleeCC != CallingConv::C)
2386     return false;
2387
2388   // If -tailcallopt is specified, make fastcc functions tail-callable.
2389   const MachineFunction &MF = DAG.getMachineFunction();
2390   const Function *CallerF = DAG.getMachineFunction().getFunction();
2391   CallingConv::ID CallerCC = CallerF->getCallingConv();
2392   bool CCMatch = CallerCC == CalleeCC;
2393
2394   if (GuaranteedTailCallOpt) {
2395     if (IsTailCallConvention(CalleeCC) && CCMatch)
2396       return true;
2397     return false;
2398   }
2399
2400   // Look for obvious safe cases to perform tail call optimization that do not
2401   // require ABI changes. This is what gcc calls sibcall.
2402
2403   // Can't do sibcall if stack needs to be dynamically re-aligned. PEI needs to
2404   // emit a special epilogue.
2405   if (RegInfo->needsStackRealignment(MF))
2406     return false;
2407
2408   // Do not sibcall optimize vararg calls unless the call site is not passing
2409   // any arguments.
2410   if (isVarArg && !Outs.empty())
2411     return false;
2412
2413   // Also avoid sibcall optimization if either caller or callee uses struct
2414   // return semantics.
2415   if (isCalleeStructRet || isCallerStructRet)
2416     return false;
2417
2418   // If the call result is in ST0 / ST1, it needs to be popped off the x87 stack.
2419   // Therefore if it's not used by the call it is not safe to optimize this into
2420   // a sibcall.
2421   bool Unused = false;
2422   for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
2423     if (!Ins[i].Used) {
2424       Unused = true;
2425       break;
2426     }
2427   }
2428   if (Unused) {
2429     SmallVector<CCValAssign, 16> RVLocs;
2430     CCState CCInfo(CalleeCC, false, getTargetMachine(),
2431                    RVLocs, *DAG.getContext());
2432     CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
2433     for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
2434       CCValAssign &VA = RVLocs[i];
2435       if (VA.getLocReg() == X86::ST0 || VA.getLocReg() == X86::ST1)
2436         return false;
2437     }
2438   }
2439
2440   // If the calling conventions do not match, then we'd better make sure the
2441   // results are returned in the same way as what the caller expects.
2442   if (!CCMatch) {
2443     SmallVector<CCValAssign, 16> RVLocs1;
2444     CCState CCInfo1(CalleeCC, false, getTargetMachine(),
2445                     RVLocs1, *DAG.getContext());
2446     CCInfo1.AnalyzeCallResult(Ins, RetCC_X86);
2447
2448     SmallVector<CCValAssign, 16> RVLocs2;
2449     CCState CCInfo2(CallerCC, false, getTargetMachine(),
2450                     RVLocs2, *DAG.getContext());
2451     CCInfo2.AnalyzeCallResult(Ins, RetCC_X86);
2452
2453     if (RVLocs1.size() != RVLocs2.size())
2454       return false;
2455     for (unsigned i = 0, e = RVLocs1.size(); i != e; ++i) {
2456       if (RVLocs1[i].isRegLoc() != RVLocs2[i].isRegLoc())
2457         return false;
2458       if (RVLocs1[i].getLocInfo() != RVLocs2[i].getLocInfo())
2459         return false;
2460       if (RVLocs1[i].isRegLoc()) {
2461         if (RVLocs1[i].getLocReg() != RVLocs2[i].getLocReg())
2462           return false;
2463       } else {
2464         if (RVLocs1[i].getLocMemOffset() != RVLocs2[i].getLocMemOffset())
2465           return false;
2466       }
2467     }
2468   }
2469
2470   // If the callee takes no arguments then go on to check the results of the
2471   // call.
2472   if (!Outs.empty()) {
2473     // Check if stack adjustment is needed. For now, do not do this if any
2474     // argument is passed on the stack.
2475     SmallVector<CCValAssign, 16> ArgLocs;
2476     CCState CCInfo(CalleeCC, isVarArg, getTargetMachine(),
2477                    ArgLocs, *DAG.getContext());
2478     CCInfo.AnalyzeCallOperands(Outs, CC_X86);
2479     if (CCInfo.getNextStackOffset()) {
2480       MachineFunction &MF = DAG.getMachineFunction();
2481       if (MF.getInfo<X86MachineFunctionInfo>()->getBytesToPopOnReturn())
2482         return false;
2483       if (Subtarget->isTargetWin64())
2484         // Win64 ABI has additional complications.
2485         return false;
2486
2487       // Check if the arguments are already laid out in the right way as
2488       // the caller's fixed stack objects.
2489       MachineFrameInfo *MFI = MF.getFrameInfo();
2490       const MachineRegisterInfo *MRI = &MF.getRegInfo();
2491       const X86InstrInfo *TII =
2492         ((X86TargetMachine&)getTargetMachine()).getInstrInfo();
2493       for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2494         CCValAssign &VA = ArgLocs[i];
2495         SDValue Arg = OutVals[i];
2496         ISD::ArgFlagsTy Flags = Outs[i].Flags;
2497         if (VA.getLocInfo() == CCValAssign::Indirect)
2498           return false;
2499         if (!VA.isRegLoc()) {
2500           if (!MatchingStackOffset(Arg, VA.getLocMemOffset(), Flags,
2501                                    MFI, MRI, TII))
2502             return false;
2503         }
2504       }
2505     }
2506
2507     // If the tailcall address may be in a register, then make sure it's
2508     // possible to register allocate for it. In 32-bit, the call address can
2509     // only target EAX, EDX, or ECX since the tail call must be scheduled after
2510     // callee-saved registers are restored. These happen to be the same
2511     // registers used to pass 'inreg' arguments so watch out for those.
2512     if (!Subtarget->is64Bit() &&
2513         !isa<GlobalAddressSDNode>(Callee) &&
2514         !isa<ExternalSymbolSDNode>(Callee)) {
2515       unsigned NumInRegs = 0;
2516       for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2517         CCValAssign &VA = ArgLocs[i];
2518         if (!VA.isRegLoc())
2519           continue;
2520         unsigned Reg = VA.getLocReg();
2521         switch (Reg) {
2522         default: break;
2523         case X86::EAX: case X86::EDX: case X86::ECX:
2524           if (++NumInRegs == 3)
2525             return false;
2526           break;
2527         }
2528       }
2529     }
2530   }
2531
2532   // An stdcall caller is expected to clean up its arguments; the callee
2533   // isn't going to do that.
2534   if (!CCMatch && CallerCC==CallingConv::X86_StdCall)
2535     return false;
2536
2537   return true;
2538 }
2539
2540 FastISel *
2541 X86TargetLowering::createFastISel(FunctionLoweringInfo &funcInfo) const {
2542   return X86::createFastISel(funcInfo);
2543 }
2544
2545
2546 //===----------------------------------------------------------------------===//
2547 //                           Other Lowering Hooks
2548 //===----------------------------------------------------------------------===//
2549
2550 static bool MayFoldLoad(SDValue Op) {
2551   return Op.hasOneUse() && ISD::isNormalLoad(Op.getNode());
2552 }
2553
2554 static bool MayFoldIntoStore(SDValue Op) {
2555   return Op.hasOneUse() && ISD::isNormalStore(*Op.getNode()->use_begin());
2556 }
2557
2558 static bool isTargetShuffle(unsigned Opcode) {
2559   switch(Opcode) {
2560   default: return false;
2561   case X86ISD::PSHUFD:
2562   case X86ISD::PSHUFHW:
2563   case X86ISD::PSHUFLW:
2564   case X86ISD::SHUFPD:
2565   case X86ISD::PALIGN:
2566   case X86ISD::SHUFPS:
2567   case X86ISD::MOVLHPS:
2568   case X86ISD::MOVLHPD:
2569   case X86ISD::MOVHLPS:
2570   case X86ISD::MOVLPS:
2571   case X86ISD::MOVLPD:
2572   case X86ISD::MOVSHDUP:
2573   case X86ISD::MOVSLDUP:
2574   case X86ISD::MOVDDUP:
2575   case X86ISD::MOVSS:
2576   case X86ISD::MOVSD:
2577   case X86ISD::UNPCKLPS:
2578   case X86ISD::UNPCKLPD:
2579   case X86ISD::PUNPCKLWD:
2580   case X86ISD::PUNPCKLBW:
2581   case X86ISD::PUNPCKLDQ:
2582   case X86ISD::PUNPCKLQDQ:
2583   case X86ISD::UNPCKHPS:
2584   case X86ISD::UNPCKHPD:
2585   case X86ISD::PUNPCKHWD:
2586   case X86ISD::PUNPCKHBW:
2587   case X86ISD::PUNPCKHDQ:
2588   case X86ISD::PUNPCKHQDQ:
2589     return true;
2590   }
2591   return false;
2592 }
2593
2594 static SDValue getTargetShuffleNode(unsigned Opc, DebugLoc dl, EVT VT,
2595                                                SDValue V1, SelectionDAG &DAG) {
2596   switch(Opc) {
2597   default: llvm_unreachable("Unknown x86 shuffle node");
2598   case X86ISD::MOVSHDUP:
2599   case X86ISD::MOVSLDUP:
2600   case X86ISD::MOVDDUP:
2601     return DAG.getNode(Opc, dl, VT, V1);
2602   }
2603
2604   return SDValue();
2605 }
2606
2607 static SDValue getTargetShuffleNode(unsigned Opc, DebugLoc dl, EVT VT,
2608                           SDValue V1, unsigned TargetMask, SelectionDAG &DAG) {
2609   switch(Opc) {
2610   default: llvm_unreachable("Unknown x86 shuffle node");
2611   case X86ISD::PSHUFD:
2612   case X86ISD::PSHUFHW:
2613   case X86ISD::PSHUFLW:
2614     return DAG.getNode(Opc, dl, VT, V1, DAG.getConstant(TargetMask, MVT::i8));
2615   }
2616
2617   return SDValue();
2618 }
2619
2620 static SDValue getTargetShuffleNode(unsigned Opc, DebugLoc dl, EVT VT,
2621                SDValue V1, SDValue V2, unsigned TargetMask, SelectionDAG &DAG) {
2622   switch(Opc) {
2623   default: llvm_unreachable("Unknown x86 shuffle node");
2624   case X86ISD::PALIGN:
2625   case X86ISD::SHUFPD:
2626   case X86ISD::SHUFPS:
2627     return DAG.getNode(Opc, dl, VT, V1, V2,
2628                        DAG.getConstant(TargetMask, MVT::i8));
2629   }
2630   return SDValue();
2631 }
2632
2633 static SDValue getTargetShuffleNode(unsigned Opc, DebugLoc dl, EVT VT,
2634                                     SDValue V1, SDValue V2, SelectionDAG &DAG) {
2635   switch(Opc) {
2636   default: llvm_unreachable("Unknown x86 shuffle node");
2637   case X86ISD::MOVLHPS:
2638   case X86ISD::MOVLHPD:
2639   case X86ISD::MOVHLPS:
2640   case X86ISD::MOVLPS:
2641   case X86ISD::MOVLPD:
2642   case X86ISD::MOVSS:
2643   case X86ISD::MOVSD:
2644   case X86ISD::UNPCKLPS:
2645   case X86ISD::UNPCKLPD:
2646   case X86ISD::PUNPCKLWD:
2647   case X86ISD::PUNPCKLBW:
2648   case X86ISD::PUNPCKLDQ:
2649   case X86ISD::PUNPCKLQDQ:
2650   case X86ISD::UNPCKHPS:
2651   case X86ISD::UNPCKHPD:
2652   case X86ISD::PUNPCKHWD:
2653   case X86ISD::PUNPCKHBW:
2654   case X86ISD::PUNPCKHDQ:
2655   case X86ISD::PUNPCKHQDQ:
2656     return DAG.getNode(Opc, dl, VT, V1, V2);
2657   }
2658   return SDValue();
2659 }
2660
2661 SDValue X86TargetLowering::getReturnAddressFrameIndex(SelectionDAG &DAG) const {
2662   MachineFunction &MF = DAG.getMachineFunction();
2663   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
2664   int ReturnAddrIndex = FuncInfo->getRAIndex();
2665
2666   if (ReturnAddrIndex == 0) {
2667     // Set up a frame object for the return address.
2668     uint64_t SlotSize = TD->getPointerSize();
2669     ReturnAddrIndex = MF.getFrameInfo()->CreateFixedObject(SlotSize, -SlotSize,
2670                                                            false);
2671     FuncInfo->setRAIndex(ReturnAddrIndex);
2672   }
2673
2674   return DAG.getFrameIndex(ReturnAddrIndex, getPointerTy());
2675 }
2676
2677
2678 bool X86::isOffsetSuitableForCodeModel(int64_t Offset, CodeModel::Model M,
2679                                        bool hasSymbolicDisplacement) {
2680   // Offset should fit into 32 bit immediate field.
2681   if (!isInt<32>(Offset))
2682     return false;
2683
2684   // If we don't have a symbolic displacement - we don't have any extra
2685   // restrictions.
2686   if (!hasSymbolicDisplacement)
2687     return true;
2688
2689   // FIXME: Some tweaks might be needed for medium code model.
2690   if (M != CodeModel::Small && M != CodeModel::Kernel)
2691     return false;
2692
2693   // For small code model we assume that latest object is 16MB before end of 31
2694   // bits boundary. We may also accept pretty large negative constants knowing
2695   // that all objects are in the positive half of address space.
2696   if (M == CodeModel::Small && Offset < 16*1024*1024)
2697     return true;
2698
2699   // For kernel code model we know that all object resist in the negative half
2700   // of 32bits address space. We may not accept negative offsets, since they may
2701   // be just off and we may accept pretty large positive ones.
2702   if (M == CodeModel::Kernel && Offset > 0)
2703     return true;
2704
2705   return false;
2706 }
2707
2708 /// TranslateX86CC - do a one to one translation of a ISD::CondCode to the X86
2709 /// specific condition code, returning the condition code and the LHS/RHS of the
2710 /// comparison to make.
2711 static unsigned TranslateX86CC(ISD::CondCode SetCCOpcode, bool isFP,
2712                                SDValue &LHS, SDValue &RHS, SelectionDAG &DAG) {
2713   if (!isFP) {
2714     if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) {
2715       if (SetCCOpcode == ISD::SETGT && RHSC->isAllOnesValue()) {
2716         // X > -1   -> X == 0, jump !sign.
2717         RHS = DAG.getConstant(0, RHS.getValueType());
2718         return X86::COND_NS;
2719       } else if (SetCCOpcode == ISD::SETLT && RHSC->isNullValue()) {
2720         // X < 0   -> X == 0, jump on sign.
2721         return X86::COND_S;
2722       } else if (SetCCOpcode == ISD::SETLT && RHSC->getZExtValue() == 1) {
2723         // X < 1   -> X <= 0
2724         RHS = DAG.getConstant(0, RHS.getValueType());
2725         return X86::COND_LE;
2726       }
2727     }
2728
2729     switch (SetCCOpcode) {
2730     default: llvm_unreachable("Invalid integer condition!");
2731     case ISD::SETEQ:  return X86::COND_E;
2732     case ISD::SETGT:  return X86::COND_G;
2733     case ISD::SETGE:  return X86::COND_GE;
2734     case ISD::SETLT:  return X86::COND_L;
2735     case ISD::SETLE:  return X86::COND_LE;
2736     case ISD::SETNE:  return X86::COND_NE;
2737     case ISD::SETULT: return X86::COND_B;
2738     case ISD::SETUGT: return X86::COND_A;
2739     case ISD::SETULE: return X86::COND_BE;
2740     case ISD::SETUGE: return X86::COND_AE;
2741     }
2742   }
2743
2744   // First determine if it is required or is profitable to flip the operands.
2745
2746   // If LHS is a foldable load, but RHS is not, flip the condition.
2747   if ((ISD::isNON_EXTLoad(LHS.getNode()) && LHS.hasOneUse()) &&
2748       !(ISD::isNON_EXTLoad(RHS.getNode()) && RHS.hasOneUse())) {
2749     SetCCOpcode = getSetCCSwappedOperands(SetCCOpcode);
2750     std::swap(LHS, RHS);
2751   }
2752
2753   switch (SetCCOpcode) {
2754   default: break;
2755   case ISD::SETOLT:
2756   case ISD::SETOLE:
2757   case ISD::SETUGT:
2758   case ISD::SETUGE:
2759     std::swap(LHS, RHS);
2760     break;
2761   }
2762
2763   // On a floating point condition, the flags are set as follows:
2764   // ZF  PF  CF   op
2765   //  0 | 0 | 0 | X > Y
2766   //  0 | 0 | 1 | X < Y
2767   //  1 | 0 | 0 | X == Y
2768   //  1 | 1 | 1 | unordered
2769   switch (SetCCOpcode) {
2770   default: llvm_unreachable("Condcode should be pre-legalized away");
2771   case ISD::SETUEQ:
2772   case ISD::SETEQ:   return X86::COND_E;
2773   case ISD::SETOLT:              // flipped
2774   case ISD::SETOGT:
2775   case ISD::SETGT:   return X86::COND_A;
2776   case ISD::SETOLE:              // flipped
2777   case ISD::SETOGE:
2778   case ISD::SETGE:   return X86::COND_AE;
2779   case ISD::SETUGT:              // flipped
2780   case ISD::SETULT:
2781   case ISD::SETLT:   return X86::COND_B;
2782   case ISD::SETUGE:              // flipped
2783   case ISD::SETULE:
2784   case ISD::SETLE:   return X86::COND_BE;
2785   case ISD::SETONE:
2786   case ISD::SETNE:   return X86::COND_NE;
2787   case ISD::SETUO:   return X86::COND_P;
2788   case ISD::SETO:    return X86::COND_NP;
2789   case ISD::SETOEQ:
2790   case ISD::SETUNE:  return X86::COND_INVALID;
2791   }
2792 }
2793
2794 /// hasFPCMov - is there a floating point cmov for the specific X86 condition
2795 /// code. Current x86 isa includes the following FP cmov instructions:
2796 /// fcmovb, fcomvbe, fcomve, fcmovu, fcmovae, fcmova, fcmovne, fcmovnu.
2797 static bool hasFPCMov(unsigned X86CC) {
2798   switch (X86CC) {
2799   default:
2800     return false;
2801   case X86::COND_B:
2802   case X86::COND_BE:
2803   case X86::COND_E:
2804   case X86::COND_P:
2805   case X86::COND_A:
2806   case X86::COND_AE:
2807   case X86::COND_NE:
2808   case X86::COND_NP:
2809     return true;
2810   }
2811 }
2812
2813 /// isFPImmLegal - Returns true if the target can instruction select the
2814 /// specified FP immediate natively. If false, the legalizer will
2815 /// materialize the FP immediate as a load from a constant pool.
2816 bool X86TargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
2817   for (unsigned i = 0, e = LegalFPImmediates.size(); i != e; ++i) {
2818     if (Imm.bitwiseIsEqual(LegalFPImmediates[i]))
2819       return true;
2820   }
2821   return false;
2822 }
2823
2824 /// isUndefOrInRange - Return true if Val is undef or if its value falls within
2825 /// the specified range (L, H].
2826 static bool isUndefOrInRange(int Val, int Low, int Hi) {
2827   return (Val < 0) || (Val >= Low && Val < Hi);
2828 }
2829
2830 /// isUndefOrEqual - Val is either less than zero (undef) or equal to the
2831 /// specified value.
2832 static bool isUndefOrEqual(int Val, int CmpVal) {
2833   if (Val < 0 || Val == CmpVal)
2834     return true;
2835   return false;
2836 }
2837
2838 /// isPSHUFDMask - Return true if the node specifies a shuffle of elements that
2839 /// is suitable for input to PSHUFD or PSHUFW.  That is, it doesn't reference
2840 /// the second operand.
2841 static bool isPSHUFDMask(const SmallVectorImpl<int> &Mask, EVT VT) {
2842   if (VT == MVT::v4f32 || VT == MVT::v4i32 )
2843     return (Mask[0] < 4 && Mask[1] < 4 && Mask[2] < 4 && Mask[3] < 4);
2844   if (VT == MVT::v2f64 || VT == MVT::v2i64)
2845     return (Mask[0] < 2 && Mask[1] < 2);
2846   return false;
2847 }
2848
2849 bool X86::isPSHUFDMask(ShuffleVectorSDNode *N) {
2850   SmallVector<int, 8> M;
2851   N->getMask(M);
2852   return ::isPSHUFDMask(M, N->getValueType(0));
2853 }
2854
2855 /// isPSHUFHWMask - Return true if the node specifies a shuffle of elements that
2856 /// is suitable for input to PSHUFHW.
2857 static bool isPSHUFHWMask(const SmallVectorImpl<int> &Mask, EVT VT) {
2858   if (VT != MVT::v8i16)
2859     return false;
2860
2861   // Lower quadword copied in order or undef.
2862   for (int i = 0; i != 4; ++i)
2863     if (Mask[i] >= 0 && Mask[i] != i)
2864       return false;
2865
2866   // Upper quadword shuffled.
2867   for (int i = 4; i != 8; ++i)
2868     if (Mask[i] >= 0 && (Mask[i] < 4 || Mask[i] > 7))
2869       return false;
2870
2871   return true;
2872 }
2873
2874 bool X86::isPSHUFHWMask(ShuffleVectorSDNode *N) {
2875   SmallVector<int, 8> M;
2876   N->getMask(M);
2877   return ::isPSHUFHWMask(M, N->getValueType(0));
2878 }
2879
2880 /// isPSHUFLWMask - Return true if the node specifies a shuffle of elements that
2881 /// is suitable for input to PSHUFLW.
2882 static bool isPSHUFLWMask(const SmallVectorImpl<int> &Mask, EVT VT) {
2883   if (VT != MVT::v8i16)
2884     return false;
2885
2886   // Upper quadword copied in order.
2887   for (int i = 4; i != 8; ++i)
2888     if (Mask[i] >= 0 && Mask[i] != i)
2889       return false;
2890
2891   // Lower quadword shuffled.
2892   for (int i = 0; i != 4; ++i)
2893     if (Mask[i] >= 4)
2894       return false;
2895
2896   return true;
2897 }
2898
2899 bool X86::isPSHUFLWMask(ShuffleVectorSDNode *N) {
2900   SmallVector<int, 8> M;
2901   N->getMask(M);
2902   return ::isPSHUFLWMask(M, N->getValueType(0));
2903 }
2904
2905 /// isPALIGNRMask - Return true if the node specifies a shuffle of elements that
2906 /// is suitable for input to PALIGNR.
2907 static bool isPALIGNRMask(const SmallVectorImpl<int> &Mask, EVT VT,
2908                           bool hasSSSE3) {
2909   int i, e = VT.getVectorNumElements();
2910
2911   // Do not handle v2i64 / v2f64 shuffles with palignr.
2912   if (e < 4 || !hasSSSE3)
2913     return false;
2914
2915   for (i = 0; i != e; ++i)
2916     if (Mask[i] >= 0)
2917       break;
2918
2919   // All undef, not a palignr.
2920   if (i == e)
2921     return false;
2922
2923   // Determine if it's ok to perform a palignr with only the LHS, since we
2924   // don't have access to the actual shuffle elements to see if RHS is undef.
2925   bool Unary = Mask[i] < (int)e;
2926   bool NeedsUnary = false;
2927
2928   int s = Mask[i] - i;
2929
2930   // Check the rest of the elements to see if they are consecutive.
2931   for (++i; i != e; ++i) {
2932     int m = Mask[i];
2933     if (m < 0)
2934       continue;
2935
2936     Unary = Unary && (m < (int)e);
2937     NeedsUnary = NeedsUnary || (m < s);
2938
2939     if (NeedsUnary && !Unary)
2940       return false;
2941     if (Unary && m != ((s+i) & (e-1)))
2942       return false;
2943     if (!Unary && m != (s+i))
2944       return false;
2945   }
2946   return true;
2947 }
2948
2949 bool X86::isPALIGNRMask(ShuffleVectorSDNode *N) {
2950   SmallVector<int, 8> M;
2951   N->getMask(M);
2952   return ::isPALIGNRMask(M, N->getValueType(0), true);
2953 }
2954
2955 /// isSHUFPMask - Return true if the specified VECTOR_SHUFFLE operand
2956 /// specifies a shuffle of elements that is suitable for input to SHUFP*.
2957 static bool isSHUFPMask(const SmallVectorImpl<int> &Mask, EVT VT) {
2958   int NumElems = VT.getVectorNumElements();
2959   if (NumElems != 2 && NumElems != 4)
2960     return false;
2961
2962   int Half = NumElems / 2;
2963   for (int i = 0; i < Half; ++i)
2964     if (!isUndefOrInRange(Mask[i], 0, NumElems))
2965       return false;
2966   for (int i = Half; i < NumElems; ++i)
2967     if (!isUndefOrInRange(Mask[i], NumElems, NumElems*2))
2968       return false;
2969
2970   return true;
2971 }
2972
2973 bool X86::isSHUFPMask(ShuffleVectorSDNode *N) {
2974   SmallVector<int, 8> M;
2975   N->getMask(M);
2976   return ::isSHUFPMask(M, N->getValueType(0));
2977 }
2978
2979 /// isCommutedSHUFP - Returns true if the shuffle mask is exactly
2980 /// the reverse of what x86 shuffles want. x86 shuffles requires the lower
2981 /// half elements to come from vector 1 (which would equal the dest.) and
2982 /// the upper half to come from vector 2.
2983 static bool isCommutedSHUFPMask(const SmallVectorImpl<int> &Mask, EVT VT) {
2984   int NumElems = VT.getVectorNumElements();
2985
2986   if (NumElems != 2 && NumElems != 4)
2987     return false;
2988
2989   int Half = NumElems / 2;
2990   for (int i = 0; i < Half; ++i)
2991     if (!isUndefOrInRange(Mask[i], NumElems, NumElems*2))
2992       return false;
2993   for (int i = Half; i < NumElems; ++i)
2994     if (!isUndefOrInRange(Mask[i], 0, NumElems))
2995       return false;
2996   return true;
2997 }
2998
2999 static bool isCommutedSHUFP(ShuffleVectorSDNode *N) {
3000   SmallVector<int, 8> M;
3001   N->getMask(M);
3002   return isCommutedSHUFPMask(M, N->getValueType(0));
3003 }
3004
3005 /// isMOVHLPSMask - Return true if the specified VECTOR_SHUFFLE operand
3006 /// specifies a shuffle of elements that is suitable for input to MOVHLPS.
3007 bool X86::isMOVHLPSMask(ShuffleVectorSDNode *N) {
3008   if (N->getValueType(0).getVectorNumElements() != 4)
3009     return false;
3010
3011   // Expect bit0 == 6, bit1 == 7, bit2 == 2, bit3 == 3
3012   return isUndefOrEqual(N->getMaskElt(0), 6) &&
3013          isUndefOrEqual(N->getMaskElt(1), 7) &&
3014          isUndefOrEqual(N->getMaskElt(2), 2) &&
3015          isUndefOrEqual(N->getMaskElt(3), 3);
3016 }
3017
3018 /// isMOVHLPS_v_undef_Mask - Special case of isMOVHLPSMask for canonical form
3019 /// of vector_shuffle v, v, <2, 3, 2, 3>, i.e. vector_shuffle v, undef,
3020 /// <2, 3, 2, 3>
3021 bool X86::isMOVHLPS_v_undef_Mask(ShuffleVectorSDNode *N) {
3022   unsigned NumElems = N->getValueType(0).getVectorNumElements();
3023
3024   if (NumElems != 4)
3025     return false;
3026
3027   return isUndefOrEqual(N->getMaskElt(0), 2) &&
3028   isUndefOrEqual(N->getMaskElt(1), 3) &&
3029   isUndefOrEqual(N->getMaskElt(2), 2) &&
3030   isUndefOrEqual(N->getMaskElt(3), 3);
3031 }
3032
3033 /// isMOVLPMask - Return true if the specified VECTOR_SHUFFLE operand
3034 /// specifies a shuffle of elements that is suitable for input to MOVLP{S|D}.
3035 bool X86::isMOVLPMask(ShuffleVectorSDNode *N) {
3036   unsigned NumElems = N->getValueType(0).getVectorNumElements();
3037
3038   if (NumElems != 2 && NumElems != 4)
3039     return false;
3040
3041   for (unsigned i = 0; i < NumElems/2; ++i)
3042     if (!isUndefOrEqual(N->getMaskElt(i), i + NumElems))
3043       return false;
3044
3045   for (unsigned i = NumElems/2; i < NumElems; ++i)
3046     if (!isUndefOrEqual(N->getMaskElt(i), i))
3047       return false;
3048
3049   return true;
3050 }
3051
3052 /// isMOVLHPSMask - Return true if the specified VECTOR_SHUFFLE operand
3053 /// specifies a shuffle of elements that is suitable for input to MOVLHPS.
3054 bool X86::isMOVLHPSMask(ShuffleVectorSDNode *N) {
3055   unsigned NumElems = N->getValueType(0).getVectorNumElements();
3056
3057   if (NumElems != 2 && NumElems != 4)
3058     return false;
3059
3060   for (unsigned i = 0; i < NumElems/2; ++i)
3061     if (!isUndefOrEqual(N->getMaskElt(i), i))
3062       return false;
3063
3064   for (unsigned i = 0; i < NumElems/2; ++i)
3065     if (!isUndefOrEqual(N->getMaskElt(i + NumElems/2), i + NumElems))
3066       return false;
3067
3068   return true;
3069 }
3070
3071 /// isUNPCKLMask - Return true if the specified VECTOR_SHUFFLE operand
3072 /// specifies a shuffle of elements that is suitable for input to UNPCKL.
3073 static bool isUNPCKLMask(const SmallVectorImpl<int> &Mask, EVT VT,
3074                          bool V2IsSplat = false) {
3075   int NumElts = VT.getVectorNumElements();
3076   if (NumElts != 2 && NumElts != 4 && NumElts != 8 && NumElts != 16)
3077     return false;
3078
3079   for (int i = 0, j = 0; i != NumElts; i += 2, ++j) {
3080     int BitI  = Mask[i];
3081     int BitI1 = Mask[i+1];
3082     if (!isUndefOrEqual(BitI, j))
3083       return false;
3084     if (V2IsSplat) {
3085       if (!isUndefOrEqual(BitI1, NumElts))
3086         return false;
3087     } else {
3088       if (!isUndefOrEqual(BitI1, j + NumElts))
3089         return false;
3090     }
3091   }
3092   return true;
3093 }
3094
3095 bool X86::isUNPCKLMask(ShuffleVectorSDNode *N, bool V2IsSplat) {
3096   SmallVector<int, 8> M;
3097   N->getMask(M);
3098   return ::isUNPCKLMask(M, N->getValueType(0), V2IsSplat);
3099 }
3100
3101 /// isUNPCKHMask - Return true if the specified VECTOR_SHUFFLE operand
3102 /// specifies a shuffle of elements that is suitable for input to UNPCKH.
3103 static bool isUNPCKHMask(const SmallVectorImpl<int> &Mask, EVT VT,
3104                          bool V2IsSplat = false) {
3105   int NumElts = VT.getVectorNumElements();
3106   if (NumElts != 2 && NumElts != 4 && NumElts != 8 && NumElts != 16)
3107     return false;
3108
3109   for (int i = 0, j = 0; i != NumElts; i += 2, ++j) {
3110     int BitI  = Mask[i];
3111     int BitI1 = Mask[i+1];
3112     if (!isUndefOrEqual(BitI, j + NumElts/2))
3113       return false;
3114     if (V2IsSplat) {
3115       if (isUndefOrEqual(BitI1, NumElts))
3116         return false;
3117     } else {
3118       if (!isUndefOrEqual(BitI1, j + NumElts/2 + NumElts))
3119         return false;
3120     }
3121   }
3122   return true;
3123 }
3124
3125 bool X86::isUNPCKHMask(ShuffleVectorSDNode *N, bool V2IsSplat) {
3126   SmallVector<int, 8> M;
3127   N->getMask(M);
3128   return ::isUNPCKHMask(M, N->getValueType(0), V2IsSplat);
3129 }
3130
3131 /// isUNPCKL_v_undef_Mask - Special case of isUNPCKLMask for canonical form
3132 /// of vector_shuffle v, v, <0, 4, 1, 5>, i.e. vector_shuffle v, undef,
3133 /// <0, 0, 1, 1>
3134 static bool isUNPCKL_v_undef_Mask(const SmallVectorImpl<int> &Mask, EVT VT) {
3135   int NumElems = VT.getVectorNumElements();
3136   if (NumElems != 2 && NumElems != 4 && NumElems != 8 && NumElems != 16)
3137     return false;
3138
3139   for (int i = 0, j = 0; i != NumElems; i += 2, ++j) {
3140     int BitI  = Mask[i];
3141     int BitI1 = Mask[i+1];
3142     if (!isUndefOrEqual(BitI, j))
3143       return false;
3144     if (!isUndefOrEqual(BitI1, j))
3145       return false;
3146   }
3147   return true;
3148 }
3149
3150 bool X86::isUNPCKL_v_undef_Mask(ShuffleVectorSDNode *N) {
3151   SmallVector<int, 8> M;
3152   N->getMask(M);
3153   return ::isUNPCKL_v_undef_Mask(M, N->getValueType(0));
3154 }
3155
3156 /// isUNPCKH_v_undef_Mask - Special case of isUNPCKHMask for canonical form
3157 /// of vector_shuffle v, v, <2, 6, 3, 7>, i.e. vector_shuffle v, undef,
3158 /// <2, 2, 3, 3>
3159 static bool isUNPCKH_v_undef_Mask(const SmallVectorImpl<int> &Mask, EVT VT) {
3160   int NumElems = VT.getVectorNumElements();
3161   if (NumElems != 2 && NumElems != 4 && NumElems != 8 && NumElems != 16)
3162     return false;
3163
3164   for (int i = 0, j = NumElems / 2; i != NumElems; i += 2, ++j) {
3165     int BitI  = Mask[i];
3166     int BitI1 = Mask[i+1];
3167     if (!isUndefOrEqual(BitI, j))
3168       return false;
3169     if (!isUndefOrEqual(BitI1, j))
3170       return false;
3171   }
3172   return true;
3173 }
3174
3175 bool X86::isUNPCKH_v_undef_Mask(ShuffleVectorSDNode *N) {
3176   SmallVector<int, 8> M;
3177   N->getMask(M);
3178   return ::isUNPCKH_v_undef_Mask(M, N->getValueType(0));
3179 }
3180
3181 /// isMOVLMask - Return true if the specified VECTOR_SHUFFLE operand
3182 /// specifies a shuffle of elements that is suitable for input to MOVSS,
3183 /// MOVSD, and MOVD, i.e. setting the lowest element.
3184 static bool isMOVLMask(const SmallVectorImpl<int> &Mask, EVT VT) {
3185   if (VT.getVectorElementType().getSizeInBits() < 32)
3186     return false;
3187
3188   int NumElts = VT.getVectorNumElements();
3189
3190   if (!isUndefOrEqual(Mask[0], NumElts))
3191     return false;
3192
3193   for (int i = 1; i < NumElts; ++i)
3194     if (!isUndefOrEqual(Mask[i], i))
3195       return false;
3196
3197   return true;
3198 }
3199
3200 bool X86::isMOVLMask(ShuffleVectorSDNode *N) {
3201   SmallVector<int, 8> M;
3202   N->getMask(M);
3203   return ::isMOVLMask(M, N->getValueType(0));
3204 }
3205
3206 /// isCommutedMOVL - Returns true if the shuffle mask is except the reverse
3207 /// of what x86 movss want. X86 movs requires the lowest  element to be lowest
3208 /// element of vector 2 and the other elements to come from vector 1 in order.
3209 static bool isCommutedMOVLMask(const SmallVectorImpl<int> &Mask, EVT VT,
3210                                bool V2IsSplat = false, bool V2IsUndef = false) {
3211   int NumOps = VT.getVectorNumElements();
3212   if (NumOps != 2 && NumOps != 4 && NumOps != 8 && NumOps != 16)
3213     return false;
3214
3215   if (!isUndefOrEqual(Mask[0], 0))
3216     return false;
3217
3218   for (int i = 1; i < NumOps; ++i)
3219     if (!(isUndefOrEqual(Mask[i], i+NumOps) ||
3220           (V2IsUndef && isUndefOrInRange(Mask[i], NumOps, NumOps*2)) ||
3221           (V2IsSplat && isUndefOrEqual(Mask[i], NumOps))))
3222       return false;
3223
3224   return true;
3225 }
3226
3227 static bool isCommutedMOVL(ShuffleVectorSDNode *N, bool V2IsSplat = false,
3228                            bool V2IsUndef = false) {
3229   SmallVector<int, 8> M;
3230   N->getMask(M);
3231   return isCommutedMOVLMask(M, N->getValueType(0), V2IsSplat, V2IsUndef);
3232 }
3233
3234 /// isMOVSHDUPMask - Return true if the specified VECTOR_SHUFFLE operand
3235 /// specifies a shuffle of elements that is suitable for input to MOVSHDUP.
3236 bool X86::isMOVSHDUPMask(ShuffleVectorSDNode *N) {
3237   if (N->getValueType(0).getVectorNumElements() != 4)
3238     return false;
3239
3240   // Expect 1, 1, 3, 3
3241   for (unsigned i = 0; i < 2; ++i) {
3242     int Elt = N->getMaskElt(i);
3243     if (Elt >= 0 && Elt != 1)
3244       return false;
3245   }
3246
3247   bool HasHi = false;
3248   for (unsigned i = 2; i < 4; ++i) {
3249     int Elt = N->getMaskElt(i);
3250     if (Elt >= 0 && Elt != 3)
3251       return false;
3252     if (Elt == 3)
3253       HasHi = true;
3254   }
3255   // Don't use movshdup if it can be done with a shufps.
3256   // FIXME: verify that matching u, u, 3, 3 is what we want.
3257   return HasHi;
3258 }
3259
3260 /// isMOVSLDUPMask - Return true if the specified VECTOR_SHUFFLE operand
3261 /// specifies a shuffle of elements that is suitable for input to MOVSLDUP.
3262 bool X86::isMOVSLDUPMask(ShuffleVectorSDNode *N) {
3263   if (N->getValueType(0).getVectorNumElements() != 4)
3264     return false;
3265
3266   // Expect 0, 0, 2, 2
3267   for (unsigned i = 0; i < 2; ++i)
3268     if (N->getMaskElt(i) > 0)
3269       return false;
3270
3271   bool HasHi = false;
3272   for (unsigned i = 2; i < 4; ++i) {
3273     int Elt = N->getMaskElt(i);
3274     if (Elt >= 0 && Elt != 2)
3275       return false;
3276     if (Elt == 2)
3277       HasHi = true;
3278   }
3279   // Don't use movsldup if it can be done with a shufps.
3280   return HasHi;
3281 }
3282
3283 /// isMOVDDUPMask - Return true if the specified VECTOR_SHUFFLE operand
3284 /// specifies a shuffle of elements that is suitable for input to MOVDDUP.
3285 bool X86::isMOVDDUPMask(ShuffleVectorSDNode *N) {
3286   int e = N->getValueType(0).getVectorNumElements() / 2;
3287
3288   for (int i = 0; i < e; ++i)
3289     if (!isUndefOrEqual(N->getMaskElt(i), i))
3290       return false;
3291   for (int i = 0; i < e; ++i)
3292     if (!isUndefOrEqual(N->getMaskElt(e+i), i))
3293       return false;
3294   return true;
3295 }
3296
3297 /// getShuffleSHUFImmediate - Return the appropriate immediate to shuffle
3298 /// the specified VECTOR_SHUFFLE mask with PSHUF* and SHUFP* instructions.
3299 unsigned X86::getShuffleSHUFImmediate(SDNode *N) {
3300   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
3301   int NumOperands = SVOp->getValueType(0).getVectorNumElements();
3302
3303   unsigned Shift = (NumOperands == 4) ? 2 : 1;
3304   unsigned Mask = 0;
3305   for (int i = 0; i < NumOperands; ++i) {
3306     int Val = SVOp->getMaskElt(NumOperands-i-1);
3307     if (Val < 0) Val = 0;
3308     if (Val >= NumOperands) Val -= NumOperands;
3309     Mask |= Val;
3310     if (i != NumOperands - 1)
3311       Mask <<= Shift;
3312   }
3313   return Mask;
3314 }
3315
3316 /// getShufflePSHUFHWImmediate - Return the appropriate immediate to shuffle
3317 /// the specified VECTOR_SHUFFLE mask with the PSHUFHW instruction.
3318 unsigned X86::getShufflePSHUFHWImmediate(SDNode *N) {
3319   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
3320   unsigned Mask = 0;
3321   // 8 nodes, but we only care about the last 4.
3322   for (unsigned i = 7; i >= 4; --i) {
3323     int Val = SVOp->getMaskElt(i);
3324     if (Val >= 0)
3325       Mask |= (Val - 4);
3326     if (i != 4)
3327       Mask <<= 2;
3328   }
3329   return Mask;
3330 }
3331
3332 /// getShufflePSHUFLWImmediate - Return the appropriate immediate to shuffle
3333 /// the specified VECTOR_SHUFFLE mask with the PSHUFLW instruction.
3334 unsigned X86::getShufflePSHUFLWImmediate(SDNode *N) {
3335   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
3336   unsigned Mask = 0;
3337   // 8 nodes, but we only care about the first 4.
3338   for (int i = 3; i >= 0; --i) {
3339     int Val = SVOp->getMaskElt(i);
3340     if (Val >= 0)
3341       Mask |= Val;
3342     if (i != 0)
3343       Mask <<= 2;
3344   }
3345   return Mask;
3346 }
3347
3348 /// getShufflePALIGNRImmediate - Return the appropriate immediate to shuffle
3349 /// the specified VECTOR_SHUFFLE mask with the PALIGNR instruction.
3350 unsigned X86::getShufflePALIGNRImmediate(SDNode *N) {
3351   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
3352   EVT VVT = N->getValueType(0);
3353   unsigned EltSize = VVT.getVectorElementType().getSizeInBits() >> 3;
3354   int Val = 0;
3355
3356   unsigned i, e;
3357   for (i = 0, e = VVT.getVectorNumElements(); i != e; ++i) {
3358     Val = SVOp->getMaskElt(i);
3359     if (Val >= 0)
3360       break;
3361   }
3362   return (Val - i) * EltSize;
3363 }
3364
3365 /// isZeroNode - Returns true if Elt is a constant zero or a floating point
3366 /// constant +0.0.
3367 bool X86::isZeroNode(SDValue Elt) {
3368   return ((isa<ConstantSDNode>(Elt) &&
3369            cast<ConstantSDNode>(Elt)->isNullValue()) ||
3370           (isa<ConstantFPSDNode>(Elt) &&
3371            cast<ConstantFPSDNode>(Elt)->getValueAPF().isPosZero()));
3372 }
3373
3374 /// CommuteVectorShuffle - Swap vector_shuffle operands as well as values in
3375 /// their permute mask.
3376 static SDValue CommuteVectorShuffle(ShuffleVectorSDNode *SVOp,
3377                                     SelectionDAG &DAG) {
3378   EVT VT = SVOp->getValueType(0);
3379   unsigned NumElems = VT.getVectorNumElements();
3380   SmallVector<int, 8> MaskVec;
3381
3382   for (unsigned i = 0; i != NumElems; ++i) {
3383     int idx = SVOp->getMaskElt(i);
3384     if (idx < 0)
3385       MaskVec.push_back(idx);
3386     else if (idx < (int)NumElems)
3387       MaskVec.push_back(idx + NumElems);
3388     else
3389       MaskVec.push_back(idx - NumElems);
3390   }
3391   return DAG.getVectorShuffle(VT, SVOp->getDebugLoc(), SVOp->getOperand(1),
3392                               SVOp->getOperand(0), &MaskVec[0]);
3393 }
3394
3395 /// CommuteVectorShuffleMask - Change values in a shuffle permute mask assuming
3396 /// the two vector operands have swapped position.
3397 static void CommuteVectorShuffleMask(SmallVectorImpl<int> &Mask, EVT VT) {
3398   unsigned NumElems = VT.getVectorNumElements();
3399   for (unsigned i = 0; i != NumElems; ++i) {
3400     int idx = Mask[i];
3401     if (idx < 0)
3402       continue;
3403     else if (idx < (int)NumElems)
3404       Mask[i] = idx + NumElems;
3405     else
3406       Mask[i] = idx - NumElems;
3407   }
3408 }
3409
3410 /// ShouldXformToMOVHLPS - Return true if the node should be transformed to
3411 /// match movhlps. The lower half elements should come from upper half of
3412 /// V1 (and in order), and the upper half elements should come from the upper
3413 /// half of V2 (and in order).
3414 static bool ShouldXformToMOVHLPS(ShuffleVectorSDNode *Op) {
3415   if (Op->getValueType(0).getVectorNumElements() != 4)
3416     return false;
3417   for (unsigned i = 0, e = 2; i != e; ++i)
3418     if (!isUndefOrEqual(Op->getMaskElt(i), i+2))
3419       return false;
3420   for (unsigned i = 2; i != 4; ++i)
3421     if (!isUndefOrEqual(Op->getMaskElt(i), i+4))
3422       return false;
3423   return true;
3424 }
3425
3426 /// isScalarLoadToVector - Returns true if the node is a scalar load that
3427 /// is promoted to a vector. It also returns the LoadSDNode by reference if
3428 /// required.
3429 static bool isScalarLoadToVector(SDNode *N, LoadSDNode **LD = NULL) {
3430   if (N->getOpcode() != ISD::SCALAR_TO_VECTOR)
3431     return false;
3432   N = N->getOperand(0).getNode();
3433   if (!ISD::isNON_EXTLoad(N))
3434     return false;
3435   if (LD)
3436     *LD = cast<LoadSDNode>(N);
3437   return true;
3438 }
3439
3440 /// ShouldXformToMOVLP{S|D} - Return true if the node should be transformed to
3441 /// match movlp{s|d}. The lower half elements should come from lower half of
3442 /// V1 (and in order), and the upper half elements should come from the upper
3443 /// half of V2 (and in order). And since V1 will become the source of the
3444 /// MOVLP, it must be either a vector load or a scalar load to vector.
3445 static bool ShouldXformToMOVLP(SDNode *V1, SDNode *V2,
3446                                ShuffleVectorSDNode *Op) {
3447   if (!ISD::isNON_EXTLoad(V1) && !isScalarLoadToVector(V1))
3448     return false;
3449   // Is V2 is a vector load, don't do this transformation. We will try to use
3450   // load folding shufps op.
3451   if (ISD::isNON_EXTLoad(V2))
3452     return false;
3453
3454   unsigned NumElems = Op->getValueType(0).getVectorNumElements();
3455
3456   if (NumElems != 2 && NumElems != 4)
3457     return false;
3458   for (unsigned i = 0, e = NumElems/2; i != e; ++i)
3459     if (!isUndefOrEqual(Op->getMaskElt(i), i))
3460       return false;
3461   for (unsigned i = NumElems/2; i != NumElems; ++i)
3462     if (!isUndefOrEqual(Op->getMaskElt(i), i+NumElems))
3463       return false;
3464   return true;
3465 }
3466
3467 /// isSplatVector - Returns true if N is a BUILD_VECTOR node whose elements are
3468 /// all the same.
3469 static bool isSplatVector(SDNode *N) {
3470   if (N->getOpcode() != ISD::BUILD_VECTOR)
3471     return false;
3472
3473   SDValue SplatValue = N->getOperand(0);
3474   for (unsigned i = 1, e = N->getNumOperands(); i != e; ++i)
3475     if (N->getOperand(i) != SplatValue)
3476       return false;
3477   return true;
3478 }
3479
3480 /// isZeroShuffle - Returns true if N is a VECTOR_SHUFFLE that can be resolved
3481 /// to an zero vector.
3482 /// FIXME: move to dag combiner / method on ShuffleVectorSDNode
3483 static bool isZeroShuffle(ShuffleVectorSDNode *N) {
3484   SDValue V1 = N->getOperand(0);
3485   SDValue V2 = N->getOperand(1);
3486   unsigned NumElems = N->getValueType(0).getVectorNumElements();
3487   for (unsigned i = 0; i != NumElems; ++i) {
3488     int Idx = N->getMaskElt(i);
3489     if (Idx >= (int)NumElems) {
3490       unsigned Opc = V2.getOpcode();
3491       if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V2.getNode()))
3492         continue;
3493       if (Opc != ISD::BUILD_VECTOR ||
3494           !X86::isZeroNode(V2.getOperand(Idx-NumElems)))
3495         return false;
3496     } else if (Idx >= 0) {
3497       unsigned Opc = V1.getOpcode();
3498       if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V1.getNode()))
3499         continue;
3500       if (Opc != ISD::BUILD_VECTOR ||
3501           !X86::isZeroNode(V1.getOperand(Idx)))
3502         return false;
3503     }
3504   }
3505   return true;
3506 }
3507
3508 /// getZeroVector - Returns a vector of specified type with all zero elements.
3509 ///
3510 static SDValue getZeroVector(EVT VT, bool HasSSE2, SelectionDAG &DAG,
3511                              DebugLoc dl) {
3512   assert(VT.isVector() && "Expected a vector type");
3513
3514   // Always build SSE zero vectors as <4 x i32> bitcasted
3515   // to their dest type. This ensures they get CSE'd.
3516   SDValue Vec;
3517   if (VT.getSizeInBits() == 128) {  // SSE
3518     if (HasSSE2) {  // SSE2
3519       SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
3520       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
3521     } else { // SSE1
3522       SDValue Cst = DAG.getTargetConstantFP(+0.0, MVT::f32);
3523       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4f32, Cst, Cst, Cst, Cst);
3524     }
3525   } else if (VT.getSizeInBits() == 256) { // AVX
3526     // 256-bit logic and arithmetic instructions in AVX are
3527     // all floating-point, no support for integer ops. Default
3528     // to emitting fp zeroed vectors then.
3529     SDValue Cst = DAG.getTargetConstantFP(+0.0, MVT::f32);
3530     SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
3531     Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8f32, Ops, 8);
3532   }
3533   return DAG.getNode(ISD::BITCAST, dl, VT, Vec);
3534 }
3535
3536 /// getOnesVector - Returns a vector of specified type with all bits set.
3537 ///
3538 static SDValue getOnesVector(EVT VT, SelectionDAG &DAG, DebugLoc dl) {
3539   assert(VT.isVector() && "Expected a vector type");
3540
3541   // Always build ones vectors as <4 x i32> or <2 x i32> bitcasted to their dest
3542   // type.  This ensures they get CSE'd.
3543   SDValue Cst = DAG.getTargetConstant(~0U, MVT::i32);
3544   SDValue Vec;
3545   Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
3546   return DAG.getNode(ISD::BITCAST, dl, VT, Vec);
3547 }
3548
3549
3550 /// NormalizeMask - V2 is a splat, modify the mask (if needed) so all elements
3551 /// that point to V2 points to its first element.
3552 static SDValue NormalizeMask(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
3553   EVT VT = SVOp->getValueType(0);
3554   unsigned NumElems = VT.getVectorNumElements();
3555
3556   bool Changed = false;
3557   SmallVector<int, 8> MaskVec;
3558   SVOp->getMask(MaskVec);
3559
3560   for (unsigned i = 0; i != NumElems; ++i) {
3561     if (MaskVec[i] > (int)NumElems) {
3562       MaskVec[i] = NumElems;
3563       Changed = true;
3564     }
3565   }
3566   if (Changed)
3567     return DAG.getVectorShuffle(VT, SVOp->getDebugLoc(), SVOp->getOperand(0),
3568                                 SVOp->getOperand(1), &MaskVec[0]);
3569   return SDValue(SVOp, 0);
3570 }
3571
3572 /// getMOVLMask - Returns a vector_shuffle mask for an movs{s|d}, movd
3573 /// operation of specified width.
3574 static SDValue getMOVL(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
3575                        SDValue V2) {
3576   unsigned NumElems = VT.getVectorNumElements();
3577   SmallVector<int, 8> Mask;
3578   Mask.push_back(NumElems);
3579   for (unsigned i = 1; i != NumElems; ++i)
3580     Mask.push_back(i);
3581   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
3582 }
3583
3584 /// getUnpackl - Returns a vector_shuffle node for an unpackl operation.
3585 static SDValue getUnpackl(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
3586                           SDValue V2) {
3587   unsigned NumElems = VT.getVectorNumElements();
3588   SmallVector<int, 8> Mask;
3589   for (unsigned i = 0, e = NumElems/2; i != e; ++i) {
3590     Mask.push_back(i);
3591     Mask.push_back(i + NumElems);
3592   }
3593   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
3594 }
3595
3596 /// getUnpackhMask - Returns a vector_shuffle node for an unpackh operation.
3597 static SDValue getUnpackh(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
3598                           SDValue V2) {
3599   unsigned NumElems = VT.getVectorNumElements();
3600   unsigned Half = NumElems/2;
3601   SmallVector<int, 8> Mask;
3602   for (unsigned i = 0; i != Half; ++i) {
3603     Mask.push_back(i + Half);
3604     Mask.push_back(i + NumElems + Half);
3605   }
3606   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
3607 }
3608
3609 /// PromoteSplat - Promote a splat of v4i32, v8i16 or v16i8 to v4f32.
3610 static SDValue PromoteSplat(ShuffleVectorSDNode *SV, SelectionDAG &DAG) {
3611   EVT PVT = MVT::v4f32;
3612   EVT VT = SV->getValueType(0);
3613   DebugLoc dl = SV->getDebugLoc();
3614   SDValue V1 = SV->getOperand(0);
3615   int NumElems = VT.getVectorNumElements();
3616   int EltNo = SV->getSplatIndex();
3617
3618   // unpack elements to the correct location
3619   while (NumElems > 4) {
3620     if (EltNo < NumElems/2) {
3621       V1 = getUnpackl(DAG, dl, VT, V1, V1);
3622     } else {
3623       V1 = getUnpackh(DAG, dl, VT, V1, V1);
3624       EltNo -= NumElems/2;
3625     }
3626     NumElems >>= 1;
3627   }
3628
3629   // Perform the splat.
3630   int SplatMask[4] = { EltNo, EltNo, EltNo, EltNo };
3631   V1 = DAG.getNode(ISD::BITCAST, dl, PVT, V1);
3632   V1 = DAG.getVectorShuffle(PVT, dl, V1, DAG.getUNDEF(PVT), &SplatMask[0]);
3633   return DAG.getNode(ISD::BITCAST, dl, VT, V1);
3634 }
3635
3636 /// getShuffleVectorZeroOrUndef - Return a vector_shuffle of the specified
3637 /// vector of zero or undef vector.  This produces a shuffle where the low
3638 /// element of V2 is swizzled into the zero/undef vector, landing at element
3639 /// Idx.  This produces a shuffle mask like 4,1,2,3 (idx=0) or  0,1,2,4 (idx=3).
3640 static SDValue getShuffleVectorZeroOrUndef(SDValue V2, unsigned Idx,
3641                                              bool isZero, bool HasSSE2,
3642                                              SelectionDAG &DAG) {
3643   EVT VT = V2.getValueType();
3644   SDValue V1 = isZero
3645     ? getZeroVector(VT, HasSSE2, DAG, V2.getDebugLoc()) : DAG.getUNDEF(VT);
3646   unsigned NumElems = VT.getVectorNumElements();
3647   SmallVector<int, 16> MaskVec;
3648   for (unsigned i = 0; i != NumElems; ++i)
3649     // If this is the insertion idx, put the low elt of V2 here.
3650     MaskVec.push_back(i == Idx ? NumElems : i);
3651   return DAG.getVectorShuffle(VT, V2.getDebugLoc(), V1, V2, &MaskVec[0]);
3652 }
3653
3654 /// getShuffleScalarElt - Returns the scalar element that will make up the ith
3655 /// element of the result of the vector shuffle.
3656 SDValue getShuffleScalarElt(SDNode *N, int Index, SelectionDAG &DAG,
3657                             unsigned Depth) {
3658   if (Depth == 6)
3659     return SDValue();  // Limit search depth.
3660
3661   SDValue V = SDValue(N, 0);
3662   EVT VT = V.getValueType();
3663   unsigned Opcode = V.getOpcode();
3664
3665   // Recurse into ISD::VECTOR_SHUFFLE node to find scalars.
3666   if (const ShuffleVectorSDNode *SV = dyn_cast<ShuffleVectorSDNode>(N)) {
3667     Index = SV->getMaskElt(Index);
3668
3669     if (Index < 0)
3670       return DAG.getUNDEF(VT.getVectorElementType());
3671
3672     int NumElems = VT.getVectorNumElements();
3673     SDValue NewV = (Index < NumElems) ? SV->getOperand(0) : SV->getOperand(1);
3674     return getShuffleScalarElt(NewV.getNode(), Index % NumElems, DAG, Depth+1);
3675   }
3676
3677   // Recurse into target specific vector shuffles to find scalars.
3678   if (isTargetShuffle(Opcode)) {
3679     int NumElems = VT.getVectorNumElements();
3680     SmallVector<unsigned, 16> ShuffleMask;
3681     SDValue ImmN;
3682
3683     switch(Opcode) {
3684     case X86ISD::SHUFPS:
3685     case X86ISD::SHUFPD:
3686       ImmN = N->getOperand(N->getNumOperands()-1);
3687       DecodeSHUFPSMask(NumElems,
3688                        cast<ConstantSDNode>(ImmN)->getZExtValue(),
3689                        ShuffleMask);
3690       break;
3691     case X86ISD::PUNPCKHBW:
3692     case X86ISD::PUNPCKHWD:
3693     case X86ISD::PUNPCKHDQ:
3694     case X86ISD::PUNPCKHQDQ:
3695       DecodePUNPCKHMask(NumElems, ShuffleMask);
3696       break;
3697     case X86ISD::UNPCKHPS:
3698     case X86ISD::UNPCKHPD:
3699       DecodeUNPCKHPMask(NumElems, ShuffleMask);
3700       break;
3701     case X86ISD::PUNPCKLBW:
3702     case X86ISD::PUNPCKLWD:
3703     case X86ISD::PUNPCKLDQ:
3704     case X86ISD::PUNPCKLQDQ:
3705       DecodePUNPCKLMask(NumElems, ShuffleMask);
3706       break;
3707     case X86ISD::UNPCKLPS:
3708     case X86ISD::UNPCKLPD:
3709       DecodeUNPCKLPMask(NumElems, ShuffleMask);
3710       break;
3711     case X86ISD::MOVHLPS:
3712       DecodeMOVHLPSMask(NumElems, ShuffleMask);
3713       break;
3714     case X86ISD::MOVLHPS:
3715       DecodeMOVLHPSMask(NumElems, ShuffleMask);
3716       break;
3717     case X86ISD::PSHUFD:
3718       ImmN = N->getOperand(N->getNumOperands()-1);
3719       DecodePSHUFMask(NumElems,
3720                       cast<ConstantSDNode>(ImmN)->getZExtValue(),
3721                       ShuffleMask);
3722       break;
3723     case X86ISD::PSHUFHW:
3724       ImmN = N->getOperand(N->getNumOperands()-1);
3725       DecodePSHUFHWMask(cast<ConstantSDNode>(ImmN)->getZExtValue(),
3726                         ShuffleMask);
3727       break;
3728     case X86ISD::PSHUFLW:
3729       ImmN = N->getOperand(N->getNumOperands()-1);
3730       DecodePSHUFLWMask(cast<ConstantSDNode>(ImmN)->getZExtValue(),
3731                         ShuffleMask);
3732       break;
3733     case X86ISD::MOVSS:
3734     case X86ISD::MOVSD: {
3735       // The index 0 always comes from the first element of the second source,
3736       // this is why MOVSS and MOVSD are used in the first place. The other
3737       // elements come from the other positions of the first source vector.
3738       unsigned OpNum = (Index == 0) ? 1 : 0;
3739       return getShuffleScalarElt(V.getOperand(OpNum).getNode(), Index, DAG,
3740                                  Depth+1);
3741     }
3742     default:
3743       assert("not implemented for target shuffle node");
3744       return SDValue();
3745     }
3746
3747     Index = ShuffleMask[Index];
3748     if (Index < 0)
3749       return DAG.getUNDEF(VT.getVectorElementType());
3750
3751     SDValue NewV = (Index < NumElems) ? N->getOperand(0) : N->getOperand(1);
3752     return getShuffleScalarElt(NewV.getNode(), Index % NumElems, DAG,
3753                                Depth+1);
3754   }
3755
3756   // Actual nodes that may contain scalar elements
3757   if (Opcode == ISD::BITCAST) {
3758     V = V.getOperand(0);
3759     EVT SrcVT = V.getValueType();
3760     unsigned NumElems = VT.getVectorNumElements();
3761
3762     if (!SrcVT.isVector() || SrcVT.getVectorNumElements() != NumElems)
3763       return SDValue();
3764   }
3765
3766   if (V.getOpcode() == ISD::SCALAR_TO_VECTOR)
3767     return (Index == 0) ? V.getOperand(0)
3768                           : DAG.getUNDEF(VT.getVectorElementType());
3769
3770   if (V.getOpcode() == ISD::BUILD_VECTOR)
3771     return V.getOperand(Index);
3772
3773   return SDValue();
3774 }
3775
3776 /// getNumOfConsecutiveZeros - Return the number of elements of a vector
3777 /// shuffle operation which come from a consecutively from a zero. The
3778 /// search can start in two diferent directions, from left or right.
3779 static
3780 unsigned getNumOfConsecutiveZeros(SDNode *N, int NumElems,
3781                                   bool ZerosFromLeft, SelectionDAG &DAG) {
3782   int i = 0;
3783
3784   while (i < NumElems) {
3785     unsigned Index = ZerosFromLeft ? i : NumElems-i-1;
3786     SDValue Elt = getShuffleScalarElt(N, Index, DAG, 0);
3787     if (!(Elt.getNode() &&
3788          (Elt.getOpcode() == ISD::UNDEF || X86::isZeroNode(Elt))))
3789       break;
3790     ++i;
3791   }
3792
3793   return i;
3794 }
3795
3796 /// isShuffleMaskConsecutive - Check if the shuffle mask indicies from MaskI to
3797 /// MaskE correspond consecutively to elements from one of the vector operands,
3798 /// starting from its index OpIdx. Also tell OpNum which source vector operand.
3799 static
3800 bool isShuffleMaskConsecutive(ShuffleVectorSDNode *SVOp, int MaskI, int MaskE,
3801                               int OpIdx, int NumElems, unsigned &OpNum) {
3802   bool SeenV1 = false;
3803   bool SeenV2 = false;
3804
3805   for (int i = MaskI; i <= MaskE; ++i, ++OpIdx) {
3806     int Idx = SVOp->getMaskElt(i);
3807     // Ignore undef indicies
3808     if (Idx < 0)
3809       continue;
3810
3811     if (Idx < NumElems)
3812       SeenV1 = true;
3813     else
3814       SeenV2 = true;
3815
3816     // Only accept consecutive elements from the same vector
3817     if ((Idx % NumElems != OpIdx) || (SeenV1 && SeenV2))
3818       return false;
3819   }
3820
3821   OpNum = SeenV1 ? 0 : 1;
3822   return true;
3823 }
3824
3825 /// isVectorShiftRight - Returns true if the shuffle can be implemented as a
3826 /// logical left shift of a vector.
3827 static bool isVectorShiftRight(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
3828                                bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
3829   unsigned NumElems = SVOp->getValueType(0).getVectorNumElements();
3830   unsigned NumZeros = getNumOfConsecutiveZeros(SVOp, NumElems,
3831               false /* check zeros from right */, DAG);
3832   unsigned OpSrc;
3833
3834   if (!NumZeros)
3835     return false;
3836
3837   // Considering the elements in the mask that are not consecutive zeros,
3838   // check if they consecutively come from only one of the source vectors.
3839   //
3840   //               V1 = {X, A, B, C}     0
3841   //                         \  \  \    /
3842   //   vector_shuffle V1, V2 <1, 2, 3, X>
3843   //
3844   if (!isShuffleMaskConsecutive(SVOp,
3845             0,                   // Mask Start Index
3846             NumElems-NumZeros-1, // Mask End Index
3847             NumZeros,            // Where to start looking in the src vector
3848             NumElems,            // Number of elements in vector
3849             OpSrc))              // Which source operand ?
3850     return false;
3851
3852   isLeft = false;
3853   ShAmt = NumZeros;
3854   ShVal = SVOp->getOperand(OpSrc);
3855   return true;
3856 }
3857
3858 /// isVectorShiftLeft - Returns true if the shuffle can be implemented as a
3859 /// logical left shift of a vector.
3860 static bool isVectorShiftLeft(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
3861                               bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
3862   unsigned NumElems = SVOp->getValueType(0).getVectorNumElements();
3863   unsigned NumZeros = getNumOfConsecutiveZeros(SVOp, NumElems,
3864               true /* check zeros from left */, DAG);
3865   unsigned OpSrc;
3866
3867   if (!NumZeros)
3868     return false;
3869
3870   // Considering the elements in the mask that are not consecutive zeros,
3871   // check if they consecutively come from only one of the source vectors.
3872   //
3873   //                           0    { A, B, X, X } = V2
3874   //                          / \    /  /
3875   //   vector_shuffle V1, V2 <X, X, 4, 5>
3876   //
3877   if (!isShuffleMaskConsecutive(SVOp,
3878             NumZeros,     // Mask Start Index
3879             NumElems-1,   // Mask End Index
3880             0,            // Where to start looking in the src vector
3881             NumElems,     // Number of elements in vector
3882             OpSrc))       // Which source operand ?
3883     return false;
3884
3885   isLeft = true;
3886   ShAmt = NumZeros;
3887   ShVal = SVOp->getOperand(OpSrc);
3888   return true;
3889 }
3890
3891 /// isVectorShift - Returns true if the shuffle can be implemented as a
3892 /// logical left or right shift of a vector.
3893 static bool isVectorShift(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
3894                           bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
3895   if (isVectorShiftLeft(SVOp, DAG, isLeft, ShVal, ShAmt) ||
3896       isVectorShiftRight(SVOp, DAG, isLeft, ShVal, ShAmt))
3897     return true;
3898
3899   return false;
3900 }
3901
3902 /// LowerBuildVectorv16i8 - Custom lower build_vector of v16i8.
3903 ///
3904 static SDValue LowerBuildVectorv16i8(SDValue Op, unsigned NonZeros,
3905                                        unsigned NumNonZero, unsigned NumZero,
3906                                        SelectionDAG &DAG,
3907                                        const TargetLowering &TLI) {
3908   if (NumNonZero > 8)
3909     return SDValue();
3910
3911   DebugLoc dl = Op.getDebugLoc();
3912   SDValue V(0, 0);
3913   bool First = true;
3914   for (unsigned i = 0; i < 16; ++i) {
3915     bool ThisIsNonZero = (NonZeros & (1 << i)) != 0;
3916     if (ThisIsNonZero && First) {
3917       if (NumZero)
3918         V = getZeroVector(MVT::v8i16, true, DAG, dl);
3919       else
3920         V = DAG.getUNDEF(MVT::v8i16);
3921       First = false;
3922     }
3923
3924     if ((i & 1) != 0) {
3925       SDValue ThisElt(0, 0), LastElt(0, 0);
3926       bool LastIsNonZero = (NonZeros & (1 << (i-1))) != 0;
3927       if (LastIsNonZero) {
3928         LastElt = DAG.getNode(ISD::ZERO_EXTEND, dl,
3929                               MVT::i16, Op.getOperand(i-1));
3930       }
3931       if (ThisIsNonZero) {
3932         ThisElt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i16, Op.getOperand(i));
3933         ThisElt = DAG.getNode(ISD::SHL, dl, MVT::i16,
3934                               ThisElt, DAG.getConstant(8, MVT::i8));
3935         if (LastIsNonZero)
3936           ThisElt = DAG.getNode(ISD::OR, dl, MVT::i16, ThisElt, LastElt);
3937       } else
3938         ThisElt = LastElt;
3939
3940       if (ThisElt.getNode())
3941         V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, V, ThisElt,
3942                         DAG.getIntPtrConstant(i/2));
3943     }
3944   }
3945
3946   return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, V);
3947 }
3948
3949 /// LowerBuildVectorv8i16 - Custom lower build_vector of v8i16.
3950 ///
3951 static SDValue LowerBuildVectorv8i16(SDValue Op, unsigned NonZeros,
3952                                      unsigned NumNonZero, unsigned NumZero,
3953                                      SelectionDAG &DAG,
3954                                      const TargetLowering &TLI) {
3955   if (NumNonZero > 4)
3956     return SDValue();
3957
3958   DebugLoc dl = Op.getDebugLoc();
3959   SDValue V(0, 0);
3960   bool First = true;
3961   for (unsigned i = 0; i < 8; ++i) {
3962     bool isNonZero = (NonZeros & (1 << i)) != 0;
3963     if (isNonZero) {
3964       if (First) {
3965         if (NumZero)
3966           V = getZeroVector(MVT::v8i16, true, DAG, dl);
3967         else
3968           V = DAG.getUNDEF(MVT::v8i16);
3969         First = false;
3970       }
3971       V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl,
3972                       MVT::v8i16, V, Op.getOperand(i),
3973                       DAG.getIntPtrConstant(i));
3974     }
3975   }
3976
3977   return V;
3978 }
3979
3980 /// getVShift - Return a vector logical shift node.
3981 ///
3982 static SDValue getVShift(bool isLeft, EVT VT, SDValue SrcOp,
3983                          unsigned NumBits, SelectionDAG &DAG,
3984                          const TargetLowering &TLI, DebugLoc dl) {
3985   EVT ShVT = MVT::v2i64;
3986   unsigned Opc = isLeft ? X86ISD::VSHL : X86ISD::VSRL;
3987   SrcOp = DAG.getNode(ISD::BITCAST, dl, ShVT, SrcOp);
3988   return DAG.getNode(ISD::BITCAST, dl, VT,
3989                      DAG.getNode(Opc, dl, ShVT, SrcOp,
3990                              DAG.getConstant(NumBits, TLI.getShiftAmountTy())));
3991 }
3992
3993 SDValue
3994 X86TargetLowering::LowerAsSplatVectorLoad(SDValue SrcOp, EVT VT, DebugLoc dl,
3995                                           SelectionDAG &DAG) const {
3996
3997   // Check if the scalar load can be widened into a vector load. And if
3998   // the address is "base + cst" see if the cst can be "absorbed" into
3999   // the shuffle mask.
4000   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(SrcOp)) {
4001     SDValue Ptr = LD->getBasePtr();
4002     if (!ISD::isNormalLoad(LD) || LD->isVolatile())
4003       return SDValue();
4004     EVT PVT = LD->getValueType(0);
4005     if (PVT != MVT::i32 && PVT != MVT::f32)
4006       return SDValue();
4007
4008     int FI = -1;
4009     int64_t Offset = 0;
4010     if (FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr)) {
4011       FI = FINode->getIndex();
4012       Offset = 0;
4013     } else if (Ptr.getOpcode() == ISD::ADD &&
4014                isa<ConstantSDNode>(Ptr.getOperand(1)) &&
4015                isa<FrameIndexSDNode>(Ptr.getOperand(0))) {
4016       FI = cast<FrameIndexSDNode>(Ptr.getOperand(0))->getIndex();
4017       Offset = Ptr.getConstantOperandVal(1);
4018       Ptr = Ptr.getOperand(0);
4019     } else {
4020       return SDValue();
4021     }
4022
4023     SDValue Chain = LD->getChain();
4024     // Make sure the stack object alignment is at least 16.
4025     MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
4026     if (DAG.InferPtrAlignment(Ptr) < 16) {
4027       if (MFI->isFixedObjectIndex(FI)) {
4028         // Can't change the alignment. FIXME: It's possible to compute
4029         // the exact stack offset and reference FI + adjust offset instead.
4030         // If someone *really* cares about this. That's the way to implement it.
4031         return SDValue();
4032       } else {
4033         MFI->setObjectAlignment(FI, 16);
4034       }
4035     }
4036
4037     // (Offset % 16) must be multiple of 4. Then address is then
4038     // Ptr + (Offset & ~15).
4039     if (Offset < 0)
4040       return SDValue();
4041     if ((Offset % 16) & 3)
4042       return SDValue();
4043     int64_t StartOffset = Offset & ~15;
4044     if (StartOffset)
4045       Ptr = DAG.getNode(ISD::ADD, Ptr.getDebugLoc(), Ptr.getValueType(),
4046                         Ptr,DAG.getConstant(StartOffset, Ptr.getValueType()));
4047
4048     int EltNo = (Offset - StartOffset) >> 2;
4049     int Mask[4] = { EltNo, EltNo, EltNo, EltNo };
4050     EVT VT = (PVT == MVT::i32) ? MVT::v4i32 : MVT::v4f32;
4051     SDValue V1 = DAG.getLoad(VT, dl, Chain, Ptr,
4052                              LD->getPointerInfo().getWithOffset(StartOffset),
4053                              false, false, 0);
4054     // Canonicalize it to a v4i32 shuffle.
4055     V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V1);
4056     return DAG.getNode(ISD::BITCAST, dl, VT,
4057                        DAG.getVectorShuffle(MVT::v4i32, dl, V1,
4058                                             DAG.getUNDEF(MVT::v4i32),&Mask[0]));
4059   }
4060
4061   return SDValue();
4062 }
4063
4064 /// EltsFromConsecutiveLoads - Given the initializing elements 'Elts' of a
4065 /// vector of type 'VT', see if the elements can be replaced by a single large
4066 /// load which has the same value as a build_vector whose operands are 'elts'.
4067 ///
4068 /// Example: <load i32 *a, load i32 *a+4, undef, undef> -> zextload a
4069 ///
4070 /// FIXME: we'd also like to handle the case where the last elements are zero
4071 /// rather than undef via VZEXT_LOAD, but we do not detect that case today.
4072 /// There's even a handy isZeroNode for that purpose.
4073 static SDValue EltsFromConsecutiveLoads(EVT VT, SmallVectorImpl<SDValue> &Elts,
4074                                         DebugLoc &DL, SelectionDAG &DAG) {
4075   EVT EltVT = VT.getVectorElementType();
4076   unsigned NumElems = Elts.size();
4077
4078   LoadSDNode *LDBase = NULL;
4079   unsigned LastLoadedElt = -1U;
4080
4081   // For each element in the initializer, see if we've found a load or an undef.
4082   // If we don't find an initial load element, or later load elements are
4083   // non-consecutive, bail out.
4084   for (unsigned i = 0; i < NumElems; ++i) {
4085     SDValue Elt = Elts[i];
4086
4087     if (!Elt.getNode() ||
4088         (Elt.getOpcode() != ISD::UNDEF && !ISD::isNON_EXTLoad(Elt.getNode())))
4089       return SDValue();
4090     if (!LDBase) {
4091       if (Elt.getNode()->getOpcode() == ISD::UNDEF)
4092         return SDValue();
4093       LDBase = cast<LoadSDNode>(Elt.getNode());
4094       LastLoadedElt = i;
4095       continue;
4096     }
4097     if (Elt.getOpcode() == ISD::UNDEF)
4098       continue;
4099
4100     LoadSDNode *LD = cast<LoadSDNode>(Elt);
4101     if (!DAG.isConsecutiveLoad(LD, LDBase, EltVT.getSizeInBits()/8, i))
4102       return SDValue();
4103     LastLoadedElt = i;
4104   }
4105
4106   // If we have found an entire vector of loads and undefs, then return a large
4107   // load of the entire vector width starting at the base pointer.  If we found
4108   // consecutive loads for the low half, generate a vzext_load node.
4109   if (LastLoadedElt == NumElems - 1) {
4110     if (DAG.InferPtrAlignment(LDBase->getBasePtr()) >= 16)
4111       return DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(),
4112                          LDBase->getPointerInfo(),
4113                          LDBase->isVolatile(), LDBase->isNonTemporal(), 0);
4114     return DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(),
4115                        LDBase->getPointerInfo(),
4116                        LDBase->isVolatile(), LDBase->isNonTemporal(),
4117                        LDBase->getAlignment());
4118   } else if (NumElems == 4 && LastLoadedElt == 1) {
4119     SDVTList Tys = DAG.getVTList(MVT::v2i64, MVT::Other);
4120     SDValue Ops[] = { LDBase->getChain(), LDBase->getBasePtr() };
4121     SDValue ResNode = DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, DL, Tys,
4122                                               Ops, 2, MVT::i32,
4123                                               LDBase->getMemOperand());
4124     return DAG.getNode(ISD::BITCAST, DL, VT, ResNode);
4125   }
4126   return SDValue();
4127 }
4128
4129 SDValue
4130 X86TargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG) const {
4131   DebugLoc dl = Op.getDebugLoc();
4132   // All zero's are handled with pxor in SSE2 and above, xorps in SSE1.
4133   // All one's are handled with pcmpeqd. In AVX, zero's are handled with
4134   // vpxor in 128-bit and xor{pd,ps} in 256-bit, but no 256 version of pcmpeqd
4135   // is present, so AllOnes is ignored.
4136   if (ISD::isBuildVectorAllZeros(Op.getNode()) ||
4137       (Op.getValueType().getSizeInBits() != 256 &&
4138        ISD::isBuildVectorAllOnes(Op.getNode()))) {
4139     // Canonicalize this to <4 x i32> (SSE) to
4140     // 1) ensure the zero vectors are CSE'd, and 2) ensure that i64 scalars are
4141     // eliminated on x86-32 hosts.
4142     if (Op.getValueType() == MVT::v4i32)
4143       return Op;
4144
4145     if (ISD::isBuildVectorAllOnes(Op.getNode()))
4146       return getOnesVector(Op.getValueType(), DAG, dl);
4147     return getZeroVector(Op.getValueType(), Subtarget->hasSSE2(), DAG, dl);
4148   }
4149
4150   EVT VT = Op.getValueType();
4151   EVT ExtVT = VT.getVectorElementType();
4152   unsigned EVTBits = ExtVT.getSizeInBits();
4153
4154   unsigned NumElems = Op.getNumOperands();
4155   unsigned NumZero  = 0;
4156   unsigned NumNonZero = 0;
4157   unsigned NonZeros = 0;
4158   bool IsAllConstants = true;
4159   SmallSet<SDValue, 8> Values;
4160   for (unsigned i = 0; i < NumElems; ++i) {
4161     SDValue Elt = Op.getOperand(i);
4162     if (Elt.getOpcode() == ISD::UNDEF)
4163       continue;
4164     Values.insert(Elt);
4165     if (Elt.getOpcode() != ISD::Constant &&
4166         Elt.getOpcode() != ISD::ConstantFP)
4167       IsAllConstants = false;
4168     if (X86::isZeroNode(Elt))
4169       NumZero++;
4170     else {
4171       NonZeros |= (1 << i);
4172       NumNonZero++;
4173     }
4174   }
4175
4176   // All undef vector. Return an UNDEF.  All zero vectors were handled above.
4177   if (NumNonZero == 0)
4178     return DAG.getUNDEF(VT);
4179
4180   // Special case for single non-zero, non-undef, element.
4181   if (NumNonZero == 1) {
4182     unsigned Idx = CountTrailingZeros_32(NonZeros);
4183     SDValue Item = Op.getOperand(Idx);
4184
4185     // If this is an insertion of an i64 value on x86-32, and if the top bits of
4186     // the value are obviously zero, truncate the value to i32 and do the
4187     // insertion that way.  Only do this if the value is non-constant or if the
4188     // value is a constant being inserted into element 0.  It is cheaper to do
4189     // a constant pool load than it is to do a movd + shuffle.
4190     if (ExtVT == MVT::i64 && !Subtarget->is64Bit() &&
4191         (!IsAllConstants || Idx == 0)) {
4192       if (DAG.MaskedValueIsZero(Item, APInt::getBitsSet(64, 32, 64))) {
4193         // Handle SSE only.
4194         assert(VT == MVT::v2i64 && "Expected an SSE value type!");
4195         EVT VecVT = MVT::v4i32;
4196         unsigned VecElts = 4;
4197
4198         // Truncate the value (which may itself be a constant) to i32, and
4199         // convert it to a vector with movd (S2V+shuffle to zero extend).
4200         Item = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Item);
4201         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VecVT, Item);
4202         Item = getShuffleVectorZeroOrUndef(Item, 0, true,
4203                                            Subtarget->hasSSE2(), DAG);
4204
4205         // Now we have our 32-bit value zero extended in the low element of
4206         // a vector.  If Idx != 0, swizzle it into place.
4207         if (Idx != 0) {
4208           SmallVector<int, 4> Mask;
4209           Mask.push_back(Idx);
4210           for (unsigned i = 1; i != VecElts; ++i)
4211             Mask.push_back(i);
4212           Item = DAG.getVectorShuffle(VecVT, dl, Item,
4213                                       DAG.getUNDEF(Item.getValueType()),
4214                                       &Mask[0]);
4215         }
4216         return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Item);
4217       }
4218     }
4219
4220     // If we have a constant or non-constant insertion into the low element of
4221     // a vector, we can do this with SCALAR_TO_VECTOR + shuffle of zero into
4222     // the rest of the elements.  This will be matched as movd/movq/movss/movsd
4223     // depending on what the source datatype is.
4224     if (Idx == 0) {
4225       if (NumZero == 0) {
4226         return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
4227       } else if (ExtVT == MVT::i32 || ExtVT == MVT::f32 || ExtVT == MVT::f64 ||
4228           (ExtVT == MVT::i64 && Subtarget->is64Bit())) {
4229         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
4230         // Turn it into a MOVL (i.e. movss, movsd, or movd) to a zero vector.
4231         return getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget->hasSSE2(),
4232                                            DAG);
4233       } else if (ExtVT == MVT::i16 || ExtVT == MVT::i8) {
4234         Item = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, Item);
4235         assert(VT.getSizeInBits() == 128 && "Expected an SSE value type!");
4236         EVT MiddleVT = MVT::v4i32;
4237         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MiddleVT, Item);
4238         Item = getShuffleVectorZeroOrUndef(Item, 0, true,
4239                                            Subtarget->hasSSE2(), DAG);
4240         return DAG.getNode(ISD::BITCAST, dl, VT, Item);
4241       }
4242     }
4243
4244     // Is it a vector logical left shift?
4245     if (NumElems == 2 && Idx == 1 &&
4246         X86::isZeroNode(Op.getOperand(0)) &&
4247         !X86::isZeroNode(Op.getOperand(1))) {
4248       unsigned NumBits = VT.getSizeInBits();
4249       return getVShift(true, VT,
4250                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
4251                                    VT, Op.getOperand(1)),
4252                        NumBits/2, DAG, *this, dl);
4253     }
4254
4255     if (IsAllConstants) // Otherwise, it's better to do a constpool load.
4256       return SDValue();
4257
4258     // Otherwise, if this is a vector with i32 or f32 elements, and the element
4259     // is a non-constant being inserted into an element other than the low one,
4260     // we can't use a constant pool load.  Instead, use SCALAR_TO_VECTOR (aka
4261     // movd/movss) to move this into the low element, then shuffle it into
4262     // place.
4263     if (EVTBits == 32) {
4264       Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
4265
4266       // Turn it into a shuffle of zero and zero-extended scalar to vector.
4267       Item = getShuffleVectorZeroOrUndef(Item, 0, NumZero > 0,
4268                                          Subtarget->hasSSE2(), DAG);
4269       SmallVector<int, 8> MaskVec;
4270       for (unsigned i = 0; i < NumElems; i++)
4271         MaskVec.push_back(i == Idx ? 0 : 1);
4272       return DAG.getVectorShuffle(VT, dl, Item, DAG.getUNDEF(VT), &MaskVec[0]);
4273     }
4274   }
4275
4276   // Splat is obviously ok. Let legalizer expand it to a shuffle.
4277   if (Values.size() == 1) {
4278     if (EVTBits == 32) {
4279       // Instead of a shuffle like this:
4280       // shuffle (scalar_to_vector (load (ptr + 4))), undef, <0, 0, 0, 0>
4281       // Check if it's possible to issue this instead.
4282       // shuffle (vload ptr)), undef, <1, 1, 1, 1>
4283       unsigned Idx = CountTrailingZeros_32(NonZeros);
4284       SDValue Item = Op.getOperand(Idx);
4285       if (Op.getNode()->isOnlyUserOf(Item.getNode()))
4286         return LowerAsSplatVectorLoad(Item, VT, dl, DAG);
4287     }
4288     return SDValue();
4289   }
4290
4291   // A vector full of immediates; various special cases are already
4292   // handled, so this is best done with a single constant-pool load.
4293   if (IsAllConstants)
4294     return SDValue();
4295
4296   // Let legalizer expand 2-wide build_vectors.
4297   if (EVTBits == 64) {
4298     if (NumNonZero == 1) {
4299       // One half is zero or undef.
4300       unsigned Idx = CountTrailingZeros_32(NonZeros);
4301       SDValue V2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT,
4302                                  Op.getOperand(Idx));
4303       return getShuffleVectorZeroOrUndef(V2, Idx, true,
4304                                          Subtarget->hasSSE2(), DAG);
4305     }
4306     return SDValue();
4307   }
4308
4309   // If element VT is < 32 bits, convert it to inserts into a zero vector.
4310   if (EVTBits == 8 && NumElems == 16) {
4311     SDValue V = LowerBuildVectorv16i8(Op, NonZeros,NumNonZero,NumZero, DAG,
4312                                         *this);
4313     if (V.getNode()) return V;
4314   }
4315
4316   if (EVTBits == 16 && NumElems == 8) {
4317     SDValue V = LowerBuildVectorv8i16(Op, NonZeros,NumNonZero,NumZero, DAG,
4318                                       *this);
4319     if (V.getNode()) return V;
4320   }
4321
4322   // If element VT is == 32 bits, turn it into a number of shuffles.
4323   SmallVector<SDValue, 8> V;
4324   V.resize(NumElems);
4325   if (NumElems == 4 && NumZero > 0) {
4326     for (unsigned i = 0; i < 4; ++i) {
4327       bool isZero = !(NonZeros & (1 << i));
4328       if (isZero)
4329         V[i] = getZeroVector(VT, Subtarget->hasSSE2(), DAG, dl);
4330       else
4331         V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
4332     }
4333
4334     for (unsigned i = 0; i < 2; ++i) {
4335       switch ((NonZeros & (0x3 << i*2)) >> (i*2)) {
4336         default: break;
4337         case 0:
4338           V[i] = V[i*2];  // Must be a zero vector.
4339           break;
4340         case 1:
4341           V[i] = getMOVL(DAG, dl, VT, V[i*2+1], V[i*2]);
4342           break;
4343         case 2:
4344           V[i] = getMOVL(DAG, dl, VT, V[i*2], V[i*2+1]);
4345           break;
4346         case 3:
4347           V[i] = getUnpackl(DAG, dl, VT, V[i*2], V[i*2+1]);
4348           break;
4349       }
4350     }
4351
4352     SmallVector<int, 8> MaskVec;
4353     bool Reverse = (NonZeros & 0x3) == 2;
4354     for (unsigned i = 0; i < 2; ++i)
4355       MaskVec.push_back(Reverse ? 1-i : i);
4356     Reverse = ((NonZeros & (0x3 << 2)) >> 2) == 2;
4357     for (unsigned i = 0; i < 2; ++i)
4358       MaskVec.push_back(Reverse ? 1-i+NumElems : i+NumElems);
4359     return DAG.getVectorShuffle(VT, dl, V[0], V[1], &MaskVec[0]);
4360   }
4361
4362   if (Values.size() > 1 && VT.getSizeInBits() == 128) {
4363     // Check for a build vector of consecutive loads.
4364     for (unsigned i = 0; i < NumElems; ++i)
4365       V[i] = Op.getOperand(i);
4366
4367     // Check for elements which are consecutive loads.
4368     SDValue LD = EltsFromConsecutiveLoads(VT, V, dl, DAG);
4369     if (LD.getNode())
4370       return LD;
4371
4372     // For SSE 4.1, use insertps to put the high elements into the low element.
4373     if (getSubtarget()->hasSSE41()) {
4374       SDValue Result;
4375       if (Op.getOperand(0).getOpcode() != ISD::UNDEF)
4376         Result = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(0));
4377       else
4378         Result = DAG.getUNDEF(VT);
4379
4380       for (unsigned i = 1; i < NumElems; ++i) {
4381         if (Op.getOperand(i).getOpcode() == ISD::UNDEF) continue;
4382         Result = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Result,
4383                              Op.getOperand(i), DAG.getIntPtrConstant(i));
4384       }
4385       return Result;
4386     }
4387
4388     // Otherwise, expand into a number of unpckl*, start by extending each of
4389     // our (non-undef) elements to the full vector width with the element in the
4390     // bottom slot of the vector (which generates no code for SSE).
4391     for (unsigned i = 0; i < NumElems; ++i) {
4392       if (Op.getOperand(i).getOpcode() != ISD::UNDEF)
4393         V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
4394       else
4395         V[i] = DAG.getUNDEF(VT);
4396     }
4397
4398     // Next, we iteratively mix elements, e.g. for v4f32:
4399     //   Step 1: unpcklps 0, 2 ==> X: <?, ?, 2, 0>
4400     //         : unpcklps 1, 3 ==> Y: <?, ?, 3, 1>
4401     //   Step 2: unpcklps X, Y ==>    <3, 2, 1, 0>
4402     unsigned EltStride = NumElems >> 1;
4403     while (EltStride != 0) {
4404       for (unsigned i = 0; i < EltStride; ++i) {
4405         // If V[i+EltStride] is undef and this is the first round of mixing,
4406         // then it is safe to just drop this shuffle: V[i] is already in the
4407         // right place, the one element (since it's the first round) being
4408         // inserted as undef can be dropped.  This isn't safe for successive
4409         // rounds because they will permute elements within both vectors.
4410         if (V[i+EltStride].getOpcode() == ISD::UNDEF &&
4411             EltStride == NumElems/2)
4412           continue;
4413
4414         V[i] = getUnpackl(DAG, dl, VT, V[i], V[i + EltStride]);
4415       }
4416       EltStride >>= 1;
4417     }
4418     return V[0];
4419   }
4420   return SDValue();
4421 }
4422
4423 SDValue
4424 X86TargetLowering::LowerCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) const {
4425   // We support concatenate two MMX registers and place them in a MMX
4426   // register.  This is better than doing a stack convert.
4427   DebugLoc dl = Op.getDebugLoc();
4428   EVT ResVT = Op.getValueType();
4429   assert(Op.getNumOperands() == 2);
4430   assert(ResVT == MVT::v2i64 || ResVT == MVT::v4i32 ||
4431          ResVT == MVT::v8i16 || ResVT == MVT::v16i8);
4432   int Mask[2];
4433   SDValue InVec = DAG.getNode(ISD::BITCAST,dl, MVT::v1i64, Op.getOperand(0));
4434   SDValue VecOp = DAG.getNode(X86ISD::MOVQ2DQ, dl, MVT::v2i64, InVec);
4435   InVec = Op.getOperand(1);
4436   if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR) {
4437     unsigned NumElts = ResVT.getVectorNumElements();
4438     VecOp = DAG.getNode(ISD::BITCAST, dl, ResVT, VecOp);
4439     VecOp = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, ResVT, VecOp,
4440                        InVec.getOperand(0), DAG.getIntPtrConstant(NumElts/2+1));
4441   } else {
4442     InVec = DAG.getNode(ISD::BITCAST, dl, MVT::v1i64, InVec);
4443     SDValue VecOp2 = DAG.getNode(X86ISD::MOVQ2DQ, dl, MVT::v2i64, InVec);
4444     Mask[0] = 0; Mask[1] = 2;
4445     VecOp = DAG.getVectorShuffle(MVT::v2i64, dl, VecOp, VecOp2, Mask);
4446   }
4447   return DAG.getNode(ISD::BITCAST, dl, ResVT, VecOp);
4448 }
4449
4450 // v8i16 shuffles - Prefer shuffles in the following order:
4451 // 1. [all]   pshuflw, pshufhw, optional move
4452 // 2. [ssse3] 1 x pshufb
4453 // 3. [ssse3] 2 x pshufb + 1 x por
4454 // 4. [all]   mov + pshuflw + pshufhw + N x (pextrw + pinsrw)
4455 SDValue
4456 X86TargetLowering::LowerVECTOR_SHUFFLEv8i16(SDValue Op,
4457                                             SelectionDAG &DAG) const {
4458   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
4459   SDValue V1 = SVOp->getOperand(0);
4460   SDValue V2 = SVOp->getOperand(1);
4461   DebugLoc dl = SVOp->getDebugLoc();
4462   SmallVector<int, 8> MaskVals;
4463
4464   // Determine if more than 1 of the words in each of the low and high quadwords
4465   // of the result come from the same quadword of one of the two inputs.  Undef
4466   // mask values count as coming from any quadword, for better codegen.
4467   SmallVector<unsigned, 4> LoQuad(4);
4468   SmallVector<unsigned, 4> HiQuad(4);
4469   BitVector InputQuads(4);
4470   for (unsigned i = 0; i < 8; ++i) {
4471     SmallVectorImpl<unsigned> &Quad = i < 4 ? LoQuad : HiQuad;
4472     int EltIdx = SVOp->getMaskElt(i);
4473     MaskVals.push_back(EltIdx);
4474     if (EltIdx < 0) {
4475       ++Quad[0];
4476       ++Quad[1];
4477       ++Quad[2];
4478       ++Quad[3];
4479       continue;
4480     }
4481     ++Quad[EltIdx / 4];
4482     InputQuads.set(EltIdx / 4);
4483   }
4484
4485   int BestLoQuad = -1;
4486   unsigned MaxQuad = 1;
4487   for (unsigned i = 0; i < 4; ++i) {
4488     if (LoQuad[i] > MaxQuad) {
4489       BestLoQuad = i;
4490       MaxQuad = LoQuad[i];
4491     }
4492   }
4493
4494   int BestHiQuad = -1;
4495   MaxQuad = 1;
4496   for (unsigned i = 0; i < 4; ++i) {
4497     if (HiQuad[i] > MaxQuad) {
4498       BestHiQuad = i;
4499       MaxQuad = HiQuad[i];
4500     }
4501   }
4502
4503   // For SSSE3, If all 8 words of the result come from only 1 quadword of each
4504   // of the two input vectors, shuffle them into one input vector so only a
4505   // single pshufb instruction is necessary. If There are more than 2 input
4506   // quads, disable the next transformation since it does not help SSSE3.
4507   bool V1Used = InputQuads[0] || InputQuads[1];
4508   bool V2Used = InputQuads[2] || InputQuads[3];
4509   if (Subtarget->hasSSSE3()) {
4510     if (InputQuads.count() == 2 && V1Used && V2Used) {
4511       BestLoQuad = InputQuads.find_first();
4512       BestHiQuad = InputQuads.find_next(BestLoQuad);
4513     }
4514     if (InputQuads.count() > 2) {
4515       BestLoQuad = -1;
4516       BestHiQuad = -1;
4517     }
4518   }
4519
4520   // If BestLoQuad or BestHiQuad are set, shuffle the quads together and update
4521   // the shuffle mask.  If a quad is scored as -1, that means that it contains
4522   // words from all 4 input quadwords.
4523   SDValue NewV;
4524   if (BestLoQuad >= 0 || BestHiQuad >= 0) {
4525     SmallVector<int, 8> MaskV;
4526     MaskV.push_back(BestLoQuad < 0 ? 0 : BestLoQuad);
4527     MaskV.push_back(BestHiQuad < 0 ? 1 : BestHiQuad);
4528     NewV = DAG.getVectorShuffle(MVT::v2i64, dl,
4529                   DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V1),
4530                   DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V2), &MaskV[0]);
4531     NewV = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, NewV);
4532
4533     // Rewrite the MaskVals and assign NewV to V1 if NewV now contains all the
4534     // source words for the shuffle, to aid later transformations.
4535     bool AllWordsInNewV = true;
4536     bool InOrder[2] = { true, true };
4537     for (unsigned i = 0; i != 8; ++i) {
4538       int idx = MaskVals[i];
4539       if (idx != (int)i)
4540         InOrder[i/4] = false;
4541       if (idx < 0 || (idx/4) == BestLoQuad || (idx/4) == BestHiQuad)
4542         continue;
4543       AllWordsInNewV = false;
4544       break;
4545     }
4546
4547     bool pshuflw = AllWordsInNewV, pshufhw = AllWordsInNewV;
4548     if (AllWordsInNewV) {
4549       for (int i = 0; i != 8; ++i) {
4550         int idx = MaskVals[i];
4551         if (idx < 0)
4552           continue;
4553         idx = MaskVals[i] = (idx / 4) == BestLoQuad ? (idx & 3) : (idx & 3) + 4;
4554         if ((idx != i) && idx < 4)
4555           pshufhw = false;
4556         if ((idx != i) && idx > 3)
4557           pshuflw = false;
4558       }
4559       V1 = NewV;
4560       V2Used = false;
4561       BestLoQuad = 0;
4562       BestHiQuad = 1;
4563     }
4564
4565     // If we've eliminated the use of V2, and the new mask is a pshuflw or
4566     // pshufhw, that's as cheap as it gets.  Return the new shuffle.
4567     if ((pshufhw && InOrder[0]) || (pshuflw && InOrder[1])) {
4568       unsigned Opc = pshufhw ? X86ISD::PSHUFHW : X86ISD::PSHUFLW;
4569       unsigned TargetMask = 0;
4570       NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV,
4571                                   DAG.getUNDEF(MVT::v8i16), &MaskVals[0]);
4572       TargetMask = pshufhw ? X86::getShufflePSHUFHWImmediate(NewV.getNode()):
4573                              X86::getShufflePSHUFLWImmediate(NewV.getNode());
4574       V1 = NewV.getOperand(0);
4575       return getTargetShuffleNode(Opc, dl, MVT::v8i16, V1, TargetMask, DAG);
4576     }
4577   }
4578
4579   // If we have SSSE3, and all words of the result are from 1 input vector,
4580   // case 2 is generated, otherwise case 3 is generated.  If no SSSE3
4581   // is present, fall back to case 4.
4582   if (Subtarget->hasSSSE3()) {
4583     SmallVector<SDValue,16> pshufbMask;
4584
4585     // If we have elements from both input vectors, set the high bit of the
4586     // shuffle mask element to zero out elements that come from V2 in the V1
4587     // mask, and elements that come from V1 in the V2 mask, so that the two
4588     // results can be OR'd together.
4589     bool TwoInputs = V1Used && V2Used;
4590     for (unsigned i = 0; i != 8; ++i) {
4591       int EltIdx = MaskVals[i] * 2;
4592       if (TwoInputs && (EltIdx >= 16)) {
4593         pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
4594         pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
4595         continue;
4596       }
4597       pshufbMask.push_back(DAG.getConstant(EltIdx,   MVT::i8));
4598       pshufbMask.push_back(DAG.getConstant(EltIdx+1, MVT::i8));
4599     }
4600     V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, V1);
4601     V1 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V1,
4602                      DAG.getNode(ISD::BUILD_VECTOR, dl,
4603                                  MVT::v16i8, &pshufbMask[0], 16));
4604     if (!TwoInputs)
4605       return DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
4606
4607     // Calculate the shuffle mask for the second input, shuffle it, and
4608     // OR it with the first shuffled input.
4609     pshufbMask.clear();
4610     for (unsigned i = 0; i != 8; ++i) {
4611       int EltIdx = MaskVals[i] * 2;
4612       if (EltIdx < 16) {
4613         pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
4614         pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
4615         continue;
4616       }
4617       pshufbMask.push_back(DAG.getConstant(EltIdx - 16, MVT::i8));
4618       pshufbMask.push_back(DAG.getConstant(EltIdx - 15, MVT::i8));
4619     }
4620     V2 = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, V2);
4621     V2 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V2,
4622                      DAG.getNode(ISD::BUILD_VECTOR, dl,
4623                                  MVT::v16i8, &pshufbMask[0], 16));
4624     V1 = DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2);
4625     return DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
4626   }
4627
4628   // If BestLoQuad >= 0, generate a pshuflw to put the low elements in order,
4629   // and update MaskVals with new element order.
4630   BitVector InOrder(8);
4631   if (BestLoQuad >= 0) {
4632     SmallVector<int, 8> MaskV;
4633     for (int i = 0; i != 4; ++i) {
4634       int idx = MaskVals[i];
4635       if (idx < 0) {
4636         MaskV.push_back(-1);
4637         InOrder.set(i);
4638       } else if ((idx / 4) == BestLoQuad) {
4639         MaskV.push_back(idx & 3);
4640         InOrder.set(i);
4641       } else {
4642         MaskV.push_back(-1);
4643       }
4644     }
4645     for (unsigned i = 4; i != 8; ++i)
4646       MaskV.push_back(i);
4647     NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::v8i16),
4648                                 &MaskV[0]);
4649
4650     if (NewV.getOpcode() == ISD::VECTOR_SHUFFLE && Subtarget->hasSSSE3())
4651       NewV = getTargetShuffleNode(X86ISD::PSHUFLW, dl, MVT::v8i16,
4652                                NewV.getOperand(0),
4653                                X86::getShufflePSHUFLWImmediate(NewV.getNode()),
4654                                DAG);
4655   }
4656
4657   // If BestHi >= 0, generate a pshufhw to put the high elements in order,
4658   // and update MaskVals with the new element order.
4659   if (BestHiQuad >= 0) {
4660     SmallVector<int, 8> MaskV;
4661     for (unsigned i = 0; i != 4; ++i)
4662       MaskV.push_back(i);
4663     for (unsigned i = 4; i != 8; ++i) {
4664       int idx = MaskVals[i];
4665       if (idx < 0) {
4666         MaskV.push_back(-1);
4667         InOrder.set(i);
4668       } else if ((idx / 4) == BestHiQuad) {
4669         MaskV.push_back((idx & 3) + 4);
4670         InOrder.set(i);
4671       } else {
4672         MaskV.push_back(-1);
4673       }
4674     }
4675     NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::v8i16),
4676                                 &MaskV[0]);
4677
4678     if (NewV.getOpcode() == ISD::VECTOR_SHUFFLE && Subtarget->hasSSSE3())
4679       NewV = getTargetShuffleNode(X86ISD::PSHUFHW, dl, MVT::v8i16,
4680                               NewV.getOperand(0),
4681                               X86::getShufflePSHUFHWImmediate(NewV.getNode()),
4682                               DAG);
4683   }
4684
4685   // In case BestHi & BestLo were both -1, which means each quadword has a word
4686   // from each of the four input quadwords, calculate the InOrder bitvector now
4687   // before falling through to the insert/extract cleanup.
4688   if (BestLoQuad == -1 && BestHiQuad == -1) {
4689     NewV = V1;
4690     for (int i = 0; i != 8; ++i)
4691       if (MaskVals[i] < 0 || MaskVals[i] == i)
4692         InOrder.set(i);
4693   }
4694
4695   // The other elements are put in the right place using pextrw and pinsrw.
4696   for (unsigned i = 0; i != 8; ++i) {
4697     if (InOrder[i])
4698       continue;
4699     int EltIdx = MaskVals[i];
4700     if (EltIdx < 0)
4701       continue;
4702     SDValue ExtOp = (EltIdx < 8)
4703     ? DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V1,
4704                   DAG.getIntPtrConstant(EltIdx))
4705     : DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V2,
4706                   DAG.getIntPtrConstant(EltIdx - 8));
4707     NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, ExtOp,
4708                        DAG.getIntPtrConstant(i));
4709   }
4710   return NewV;
4711 }
4712
4713 // v16i8 shuffles - Prefer shuffles in the following order:
4714 // 1. [ssse3] 1 x pshufb
4715 // 2. [ssse3] 2 x pshufb + 1 x por
4716 // 3. [all]   v8i16 shuffle + N x pextrw + rotate + pinsrw
4717 static
4718 SDValue LowerVECTOR_SHUFFLEv16i8(ShuffleVectorSDNode *SVOp,
4719                                  SelectionDAG &DAG,
4720                                  const X86TargetLowering &TLI) {
4721   SDValue V1 = SVOp->getOperand(0);
4722   SDValue V2 = SVOp->getOperand(1);
4723   DebugLoc dl = SVOp->getDebugLoc();
4724   SmallVector<int, 16> MaskVals;
4725   SVOp->getMask(MaskVals);
4726
4727   // If we have SSSE3, case 1 is generated when all result bytes come from
4728   // one of  the inputs.  Otherwise, case 2 is generated.  If no SSSE3 is
4729   // present, fall back to case 3.
4730   // FIXME: kill V2Only once shuffles are canonizalized by getNode.
4731   bool V1Only = true;
4732   bool V2Only = true;
4733   for (unsigned i = 0; i < 16; ++i) {
4734     int EltIdx = MaskVals[i];
4735     if (EltIdx < 0)
4736       continue;
4737     if (EltIdx < 16)
4738       V2Only = false;
4739     else
4740       V1Only = false;
4741   }
4742
4743   // If SSSE3, use 1 pshufb instruction per vector with elements in the result.
4744   if (TLI.getSubtarget()->hasSSSE3()) {
4745     SmallVector<SDValue,16> pshufbMask;
4746
4747     // If all result elements are from one input vector, then only translate
4748     // undef mask values to 0x80 (zero out result) in the pshufb mask.
4749     //
4750     // Otherwise, we have elements from both input vectors, and must zero out
4751     // elements that come from V2 in the first mask, and V1 in the second mask
4752     // so that we can OR them together.
4753     bool TwoInputs = !(V1Only || V2Only);
4754     for (unsigned i = 0; i != 16; ++i) {
4755       int EltIdx = MaskVals[i];
4756       if (EltIdx < 0 || (TwoInputs && EltIdx >= 16)) {
4757         pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
4758         continue;
4759       }
4760       pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8));
4761     }
4762     // If all the elements are from V2, assign it to V1 and return after
4763     // building the first pshufb.
4764     if (V2Only)
4765       V1 = V2;
4766     V1 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V1,
4767                      DAG.getNode(ISD::BUILD_VECTOR, dl,
4768                                  MVT::v16i8, &pshufbMask[0], 16));
4769     if (!TwoInputs)
4770       return V1;
4771
4772     // Calculate the shuffle mask for the second input, shuffle it, and
4773     // OR it with the first shuffled input.
4774     pshufbMask.clear();
4775     for (unsigned i = 0; i != 16; ++i) {
4776       int EltIdx = MaskVals[i];
4777       if (EltIdx < 16) {
4778         pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
4779         continue;
4780       }
4781       pshufbMask.push_back(DAG.getConstant(EltIdx - 16, MVT::i8));
4782     }
4783     V2 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V2,
4784                      DAG.getNode(ISD::BUILD_VECTOR, dl,
4785                                  MVT::v16i8, &pshufbMask[0], 16));
4786     return DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2);
4787   }
4788
4789   // No SSSE3 - Calculate in place words and then fix all out of place words
4790   // With 0-16 extracts & inserts.  Worst case is 16 bytes out of order from
4791   // the 16 different words that comprise the two doublequadword input vectors.
4792   V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
4793   V2 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V2);
4794   SDValue NewV = V2Only ? V2 : V1;
4795   for (int i = 0; i != 8; ++i) {
4796     int Elt0 = MaskVals[i*2];
4797     int Elt1 = MaskVals[i*2+1];
4798
4799     // This word of the result is all undef, skip it.
4800     if (Elt0 < 0 && Elt1 < 0)
4801       continue;
4802
4803     // This word of the result is already in the correct place, skip it.
4804     if (V1Only && (Elt0 == i*2) && (Elt1 == i*2+1))
4805       continue;
4806     if (V2Only && (Elt0 == i*2+16) && (Elt1 == i*2+17))
4807       continue;
4808
4809     SDValue Elt0Src = Elt0 < 16 ? V1 : V2;
4810     SDValue Elt1Src = Elt1 < 16 ? V1 : V2;
4811     SDValue InsElt;
4812
4813     // If Elt0 and Elt1 are defined, are consecutive, and can be load
4814     // using a single extract together, load it and store it.
4815     if ((Elt0 >= 0) && ((Elt0 + 1) == Elt1) && ((Elt0 & 1) == 0)) {
4816       InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src,
4817                            DAG.getIntPtrConstant(Elt1 / 2));
4818       NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt,
4819                         DAG.getIntPtrConstant(i));
4820       continue;
4821     }
4822
4823     // If Elt1 is defined, extract it from the appropriate source.  If the
4824     // source byte is not also odd, shift the extracted word left 8 bits
4825     // otherwise clear the bottom 8 bits if we need to do an or.
4826     if (Elt1 >= 0) {
4827       InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src,
4828                            DAG.getIntPtrConstant(Elt1 / 2));
4829       if ((Elt1 & 1) == 0)
4830         InsElt = DAG.getNode(ISD::SHL, dl, MVT::i16, InsElt,
4831                              DAG.getConstant(8, TLI.getShiftAmountTy()));
4832       else if (Elt0 >= 0)
4833         InsElt = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt,
4834                              DAG.getConstant(0xFF00, MVT::i16));
4835     }
4836     // If Elt0 is defined, extract it from the appropriate source.  If the
4837     // source byte is not also even, shift the extracted word right 8 bits. If
4838     // Elt1 was also defined, OR the extracted values together before
4839     // inserting them in the result.
4840     if (Elt0 >= 0) {
4841       SDValue InsElt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16,
4842                                     Elt0Src, DAG.getIntPtrConstant(Elt0 / 2));
4843       if ((Elt0 & 1) != 0)
4844         InsElt0 = DAG.getNode(ISD::SRL, dl, MVT::i16, InsElt0,
4845                               DAG.getConstant(8, TLI.getShiftAmountTy()));
4846       else if (Elt1 >= 0)
4847         InsElt0 = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt0,
4848                              DAG.getConstant(0x00FF, MVT::i16));
4849       InsElt = Elt1 >= 0 ? DAG.getNode(ISD::OR, dl, MVT::i16, InsElt, InsElt0)
4850                          : InsElt0;
4851     }
4852     NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt,
4853                        DAG.getIntPtrConstant(i));
4854   }
4855   return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, NewV);
4856 }
4857
4858 /// RewriteAsNarrowerShuffle - Try rewriting v8i16 and v16i8 shuffles as 4 wide
4859 /// ones, or rewriting v4i32 / v4f32 as 2 wide ones if possible. This can be
4860 /// done when every pair / quad of shuffle mask elements point to elements in
4861 /// the right sequence. e.g.
4862 /// vector_shuffle X, Y, <2, 3, | 10, 11, | 0, 1, | 14, 15>
4863 static
4864 SDValue RewriteAsNarrowerShuffle(ShuffleVectorSDNode *SVOp,
4865                                  SelectionDAG &DAG, DebugLoc dl) {
4866   EVT VT = SVOp->getValueType(0);
4867   SDValue V1 = SVOp->getOperand(0);
4868   SDValue V2 = SVOp->getOperand(1);
4869   unsigned NumElems = VT.getVectorNumElements();
4870   unsigned NewWidth = (NumElems == 4) ? 2 : 4;
4871   EVT NewVT;
4872   switch (VT.getSimpleVT().SimpleTy) {
4873   default: assert(false && "Unexpected!");
4874   case MVT::v4f32: NewVT = MVT::v2f64; break;
4875   case MVT::v4i32: NewVT = MVT::v2i64; break;
4876   case MVT::v8i16: NewVT = MVT::v4i32; break;
4877   case MVT::v16i8: NewVT = MVT::v4i32; break;
4878   }
4879
4880   int Scale = NumElems / NewWidth;
4881   SmallVector<int, 8> MaskVec;
4882   for (unsigned i = 0; i < NumElems; i += Scale) {
4883     int StartIdx = -1;
4884     for (int j = 0; j < Scale; ++j) {
4885       int EltIdx = SVOp->getMaskElt(i+j);
4886       if (EltIdx < 0)
4887         continue;
4888       if (StartIdx == -1)
4889         StartIdx = EltIdx - (EltIdx % Scale);
4890       if (EltIdx != StartIdx + j)
4891         return SDValue();
4892     }
4893     if (StartIdx == -1)
4894       MaskVec.push_back(-1);
4895     else
4896       MaskVec.push_back(StartIdx / Scale);
4897   }
4898
4899   V1 = DAG.getNode(ISD::BITCAST, dl, NewVT, V1);
4900   V2 = DAG.getNode(ISD::BITCAST, dl, NewVT, V2);
4901   return DAG.getVectorShuffle(NewVT, dl, V1, V2, &MaskVec[0]);
4902 }
4903
4904 /// getVZextMovL - Return a zero-extending vector move low node.
4905 ///
4906 static SDValue getVZextMovL(EVT VT, EVT OpVT,
4907                             SDValue SrcOp, SelectionDAG &DAG,
4908                             const X86Subtarget *Subtarget, DebugLoc dl) {
4909   if (VT == MVT::v2f64 || VT == MVT::v4f32) {
4910     LoadSDNode *LD = NULL;
4911     if (!isScalarLoadToVector(SrcOp.getNode(), &LD))
4912       LD = dyn_cast<LoadSDNode>(SrcOp);
4913     if (!LD) {
4914       // movssrr and movsdrr do not clear top bits. Try to use movd, movq
4915       // instead.
4916       MVT ExtVT = (OpVT == MVT::v2f64) ? MVT::i64 : MVT::i32;
4917       if ((ExtVT != MVT::i64 || Subtarget->is64Bit()) &&
4918           SrcOp.getOpcode() == ISD::SCALAR_TO_VECTOR &&
4919           SrcOp.getOperand(0).getOpcode() == ISD::BITCAST &&
4920           SrcOp.getOperand(0).getOperand(0).getValueType() == ExtVT) {
4921         // PR2108
4922         OpVT = (OpVT == MVT::v2f64) ? MVT::v2i64 : MVT::v4i32;
4923         return DAG.getNode(ISD::BITCAST, dl, VT,
4924                            DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT,
4925                                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
4926                                                    OpVT,
4927                                                    SrcOp.getOperand(0)
4928                                                           .getOperand(0))));
4929       }
4930     }
4931   }
4932
4933   return DAG.getNode(ISD::BITCAST, dl, VT,
4934                      DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT,
4935                                  DAG.getNode(ISD::BITCAST, dl,
4936                                              OpVT, SrcOp)));
4937 }
4938
4939 /// LowerVECTOR_SHUFFLE_4wide - Handle all 4 wide cases with a number of
4940 /// shuffles.
4941 static SDValue
4942 LowerVECTOR_SHUFFLE_4wide(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
4943   SDValue V1 = SVOp->getOperand(0);
4944   SDValue V2 = SVOp->getOperand(1);
4945   DebugLoc dl = SVOp->getDebugLoc();
4946   EVT VT = SVOp->getValueType(0);
4947
4948   SmallVector<std::pair<int, int>, 8> Locs;
4949   Locs.resize(4);
4950   SmallVector<int, 8> Mask1(4U, -1);
4951   SmallVector<int, 8> PermMask;
4952   SVOp->getMask(PermMask);
4953
4954   unsigned NumHi = 0;
4955   unsigned NumLo = 0;
4956   for (unsigned i = 0; i != 4; ++i) {
4957     int Idx = PermMask[i];
4958     if (Idx < 0) {
4959       Locs[i] = std::make_pair(-1, -1);
4960     } else {
4961       assert(Idx < 8 && "Invalid VECTOR_SHUFFLE index!");
4962       if (Idx < 4) {
4963         Locs[i] = std::make_pair(0, NumLo);
4964         Mask1[NumLo] = Idx;
4965         NumLo++;
4966       } else {
4967         Locs[i] = std::make_pair(1, NumHi);
4968         if (2+NumHi < 4)
4969           Mask1[2+NumHi] = Idx;
4970         NumHi++;
4971       }
4972     }
4973   }
4974
4975   if (NumLo <= 2 && NumHi <= 2) {
4976     // If no more than two elements come from either vector. This can be
4977     // implemented with two shuffles. First shuffle gather the elements.
4978     // The second shuffle, which takes the first shuffle as both of its
4979     // vector operands, put the elements into the right order.
4980     V1 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
4981
4982     SmallVector<int, 8> Mask2(4U, -1);
4983
4984     for (unsigned i = 0; i != 4; ++i) {
4985       if (Locs[i].first == -1)
4986         continue;
4987       else {
4988         unsigned Idx = (i < 2) ? 0 : 4;
4989         Idx += Locs[i].first * 2 + Locs[i].second;
4990         Mask2[i] = Idx;
4991       }
4992     }
4993
4994     return DAG.getVectorShuffle(VT, dl, V1, V1, &Mask2[0]);
4995   } else if (NumLo == 3 || NumHi == 3) {
4996     // Otherwise, we must have three elements from one vector, call it X, and
4997     // one element from the other, call it Y.  First, use a shufps to build an
4998     // intermediate vector with the one element from Y and the element from X
4999     // that will be in the same half in the final destination (the indexes don't
5000     // matter). Then, use a shufps to build the final vector, taking the half
5001     // containing the element from Y from the intermediate, and the other half
5002     // from X.
5003     if (NumHi == 3) {
5004       // Normalize it so the 3 elements come from V1.
5005       CommuteVectorShuffleMask(PermMask, VT);
5006       std::swap(V1, V2);
5007     }
5008
5009     // Find the element from V2.
5010     unsigned HiIndex;
5011     for (HiIndex = 0; HiIndex < 3; ++HiIndex) {
5012       int Val = PermMask[HiIndex];
5013       if (Val < 0)
5014         continue;
5015       if (Val >= 4)
5016         break;
5017     }
5018
5019     Mask1[0] = PermMask[HiIndex];
5020     Mask1[1] = -1;
5021     Mask1[2] = PermMask[HiIndex^1];
5022     Mask1[3] = -1;
5023     V2 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
5024
5025     if (HiIndex >= 2) {
5026       Mask1[0] = PermMask[0];
5027       Mask1[1] = PermMask[1];
5028       Mask1[2] = HiIndex & 1 ? 6 : 4;
5029       Mask1[3] = HiIndex & 1 ? 4 : 6;
5030       return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
5031     } else {
5032       Mask1[0] = HiIndex & 1 ? 2 : 0;
5033       Mask1[1] = HiIndex & 1 ? 0 : 2;
5034       Mask1[2] = PermMask[2];
5035       Mask1[3] = PermMask[3];
5036       if (Mask1[2] >= 0)
5037         Mask1[2] += 4;
5038       if (Mask1[3] >= 0)
5039         Mask1[3] += 4;
5040       return DAG.getVectorShuffle(VT, dl, V2, V1, &Mask1[0]);
5041     }
5042   }
5043
5044   // Break it into (shuffle shuffle_hi, shuffle_lo).
5045   Locs.clear();
5046   SmallVector<int,8> LoMask(4U, -1);
5047   SmallVector<int,8> HiMask(4U, -1);
5048
5049   SmallVector<int,8> *MaskPtr = &LoMask;
5050   unsigned MaskIdx = 0;
5051   unsigned LoIdx = 0;
5052   unsigned HiIdx = 2;
5053   for (unsigned i = 0; i != 4; ++i) {
5054     if (i == 2) {
5055       MaskPtr = &HiMask;
5056       MaskIdx = 1;
5057       LoIdx = 0;
5058       HiIdx = 2;
5059     }
5060     int Idx = PermMask[i];
5061     if (Idx < 0) {
5062       Locs[i] = std::make_pair(-1, -1);
5063     } else if (Idx < 4) {
5064       Locs[i] = std::make_pair(MaskIdx, LoIdx);
5065       (*MaskPtr)[LoIdx] = Idx;
5066       LoIdx++;
5067     } else {
5068       Locs[i] = std::make_pair(MaskIdx, HiIdx);
5069       (*MaskPtr)[HiIdx] = Idx;
5070       HiIdx++;
5071     }
5072   }
5073
5074   SDValue LoShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &LoMask[0]);
5075   SDValue HiShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &HiMask[0]);
5076   SmallVector<int, 8> MaskOps;
5077   for (unsigned i = 0; i != 4; ++i) {
5078     if (Locs[i].first == -1) {
5079       MaskOps.push_back(-1);
5080     } else {
5081       unsigned Idx = Locs[i].first * 4 + Locs[i].second;
5082       MaskOps.push_back(Idx);
5083     }
5084   }
5085   return DAG.getVectorShuffle(VT, dl, LoShuffle, HiShuffle, &MaskOps[0]);
5086 }
5087
5088 static bool MayFoldVectorLoad(SDValue V) {
5089   if (V.hasOneUse() && V.getOpcode() == ISD::BITCAST)
5090     V = V.getOperand(0);
5091   if (V.hasOneUse() && V.getOpcode() == ISD::SCALAR_TO_VECTOR)
5092     V = V.getOperand(0);
5093   if (MayFoldLoad(V))
5094     return true;
5095   return false;
5096 }
5097
5098 // FIXME: the version above should always be used. Since there's
5099 // a bug where several vector shuffles can't be folded because the
5100 // DAG is not updated during lowering and a node claims to have two
5101 // uses while it only has one, use this version, and let isel match
5102 // another instruction if the load really happens to have more than
5103 // one use. Remove this version after this bug get fixed.
5104 // rdar://8434668, PR8156
5105 static bool RelaxedMayFoldVectorLoad(SDValue V) {
5106   if (V.hasOneUse() && V.getOpcode() == ISD::BITCAST)
5107     V = V.getOperand(0);
5108   if (V.hasOneUse() && V.getOpcode() == ISD::SCALAR_TO_VECTOR)
5109     V = V.getOperand(0);
5110   if (ISD::isNormalLoad(V.getNode()))
5111     return true;
5112   return false;
5113 }
5114
5115 /// CanFoldShuffleIntoVExtract - Check if the current shuffle is used by
5116 /// a vector extract, and if both can be later optimized into a single load.
5117 /// This is done in visitEXTRACT_VECTOR_ELT and the conditions are checked
5118 /// here because otherwise a target specific shuffle node is going to be
5119 /// emitted for this shuffle, and the optimization not done.
5120 /// FIXME: This is probably not the best approach, but fix the problem
5121 /// until the right path is decided.
5122 static
5123 bool CanXFormVExtractWithShuffleIntoLoad(SDValue V, SelectionDAG &DAG,
5124                                          const TargetLowering &TLI) {
5125   EVT VT = V.getValueType();
5126   ShuffleVectorSDNode *SVOp = dyn_cast<ShuffleVectorSDNode>(V);
5127
5128   // Be sure that the vector shuffle is present in a pattern like this:
5129   // (vextract (v4f32 shuffle (load $addr), <1,u,u,u>), c) -> (f32 load $addr)
5130   if (!V.hasOneUse())
5131     return false;
5132
5133   SDNode *N = *V.getNode()->use_begin();
5134   if (N->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
5135     return false;
5136
5137   SDValue EltNo = N->getOperand(1);
5138   if (!isa<ConstantSDNode>(EltNo))
5139     return false;
5140
5141   // If the bit convert changed the number of elements, it is unsafe
5142   // to examine the mask.
5143   bool HasShuffleIntoBitcast = false;
5144   if (V.getOpcode() == ISD::BITCAST) {
5145     EVT SrcVT = V.getOperand(0).getValueType();
5146     if (SrcVT.getVectorNumElements() != VT.getVectorNumElements())
5147       return false;
5148     V = V.getOperand(0);
5149     HasShuffleIntoBitcast = true;
5150   }
5151
5152   // Select the input vector, guarding against out of range extract vector.
5153   unsigned NumElems = VT.getVectorNumElements();
5154   unsigned Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
5155   int Idx = (Elt > NumElems) ? -1 : SVOp->getMaskElt(Elt);
5156   V = (Idx < (int)NumElems) ? V.getOperand(0) : V.getOperand(1);
5157
5158   // Skip one more bit_convert if necessary
5159   if (V.getOpcode() == ISD::BITCAST)
5160     V = V.getOperand(0);
5161
5162   if (ISD::isNormalLoad(V.getNode())) {
5163     // Is the original load suitable?
5164     LoadSDNode *LN0 = cast<LoadSDNode>(V);
5165
5166     // FIXME: avoid the multi-use bug that is preventing lots of
5167     // of foldings to be detected, this is still wrong of course, but
5168     // give the temporary desired behavior, and if it happens that
5169     // the load has real more uses, during isel it will not fold, and
5170     // will generate poor code.
5171     if (!LN0 || LN0->isVolatile()) // || !LN0->hasOneUse()
5172       return false;
5173
5174     if (!HasShuffleIntoBitcast)
5175       return true;
5176
5177     // If there's a bitcast before the shuffle, check if the load type and
5178     // alignment is valid.
5179     unsigned Align = LN0->getAlignment();
5180     unsigned NewAlign =
5181       TLI.getTargetData()->getABITypeAlignment(
5182                                     VT.getTypeForEVT(*DAG.getContext()));
5183
5184     if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, VT))
5185       return false;
5186   }
5187
5188   return true;
5189 }
5190
5191 static
5192 SDValue getMOVDDup(SDValue &Op, DebugLoc &dl, SDValue V1, SelectionDAG &DAG) {
5193   EVT VT = Op.getValueType();
5194
5195   // Canonizalize to v2f64.
5196   V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, V1);
5197   return DAG.getNode(ISD::BITCAST, dl, VT,
5198                      getTargetShuffleNode(X86ISD::MOVDDUP, dl, MVT::v2f64,
5199                                           V1, DAG));
5200 }
5201
5202 static
5203 SDValue getMOVLowToHigh(SDValue &Op, DebugLoc &dl, SelectionDAG &DAG,
5204                         bool HasSSE2) {
5205   SDValue V1 = Op.getOperand(0);
5206   SDValue V2 = Op.getOperand(1);
5207   EVT VT = Op.getValueType();
5208
5209   assert(VT != MVT::v2i64 && "unsupported shuffle type");
5210
5211   if (HasSSE2 && VT == MVT::v2f64)
5212     return getTargetShuffleNode(X86ISD::MOVLHPD, dl, VT, V1, V2, DAG);
5213
5214   // v4f32 or v4i32
5215   return getTargetShuffleNode(X86ISD::MOVLHPS, dl, VT, V1, V2, DAG);
5216 }
5217
5218 static
5219 SDValue getMOVHighToLow(SDValue &Op, DebugLoc &dl, SelectionDAG &DAG) {
5220   SDValue V1 = Op.getOperand(0);
5221   SDValue V2 = Op.getOperand(1);
5222   EVT VT = Op.getValueType();
5223
5224   assert((VT == MVT::v4i32 || VT == MVT::v4f32) &&
5225          "unsupported shuffle type");
5226
5227   if (V2.getOpcode() == ISD::UNDEF)
5228     V2 = V1;
5229
5230   // v4i32 or v4f32
5231   return getTargetShuffleNode(X86ISD::MOVHLPS, dl, VT, V1, V2, DAG);
5232 }
5233
5234 static
5235 SDValue getMOVLP(SDValue &Op, DebugLoc &dl, SelectionDAG &DAG, bool HasSSE2) {
5236   SDValue V1 = Op.getOperand(0);
5237   SDValue V2 = Op.getOperand(1);
5238   EVT VT = Op.getValueType();
5239   unsigned NumElems = VT.getVectorNumElements();
5240
5241   // Use MOVLPS and MOVLPD in case V1 or V2 are loads. During isel, the second
5242   // operand of these instructions is only memory, so check if there's a
5243   // potencial load folding here, otherwise use SHUFPS or MOVSD to match the
5244   // same masks.
5245   bool CanFoldLoad = false;
5246
5247   // Trivial case, when V2 comes from a load.
5248   if (MayFoldVectorLoad(V2))
5249     CanFoldLoad = true;
5250
5251   // When V1 is a load, it can be folded later into a store in isel, example:
5252   //  (store (v4f32 (X86Movlps (load addr:$src1), VR128:$src2)), addr:$src1)
5253   //    turns into:
5254   //  (MOVLPSmr addr:$src1, VR128:$src2)
5255   // So, recognize this potential and also use MOVLPS or MOVLPD
5256   if (MayFoldVectorLoad(V1) && MayFoldIntoStore(Op))
5257     CanFoldLoad = true;
5258
5259   if (CanFoldLoad) {
5260     if (HasSSE2 && NumElems == 2)
5261       return getTargetShuffleNode(X86ISD::MOVLPD, dl, VT, V1, V2, DAG);
5262
5263     if (NumElems == 4)
5264       return getTargetShuffleNode(X86ISD::MOVLPS, dl, VT, V1, V2, DAG);
5265   }
5266
5267   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
5268   // movl and movlp will both match v2i64, but v2i64 is never matched by
5269   // movl earlier because we make it strict to avoid messing with the movlp load
5270   // folding logic (see the code above getMOVLP call). Match it here then,
5271   // this is horrible, but will stay like this until we move all shuffle
5272   // matching to x86 specific nodes. Note that for the 1st condition all
5273   // types are matched with movsd.
5274   if ((HasSSE2 && NumElems == 2) || !X86::isMOVLMask(SVOp))
5275     return getTargetShuffleNode(X86ISD::MOVSD, dl, VT, V1, V2, DAG);
5276   else if (HasSSE2)
5277     return getTargetShuffleNode(X86ISD::MOVSS, dl, VT, V1, V2, DAG);
5278
5279
5280   assert(VT != MVT::v4i32 && "unsupported shuffle type");
5281
5282   // Invert the operand order and use SHUFPS to match it.
5283   return getTargetShuffleNode(X86ISD::SHUFPS, dl, VT, V2, V1,
5284                               X86::getShuffleSHUFImmediate(SVOp), DAG);
5285 }
5286
5287 static inline unsigned getUNPCKLOpcode(EVT VT) {
5288   switch(VT.getSimpleVT().SimpleTy) {
5289   case MVT::v4i32: return X86ISD::PUNPCKLDQ;
5290   case MVT::v2i64: return X86ISD::PUNPCKLQDQ;
5291   case MVT::v4f32: return X86ISD::UNPCKLPS;
5292   case MVT::v2f64: return X86ISD::UNPCKLPD;
5293   case MVT::v16i8: return X86ISD::PUNPCKLBW;
5294   case MVT::v8i16: return X86ISD::PUNPCKLWD;
5295   default:
5296     llvm_unreachable("Unknow type for unpckl");
5297   }
5298   return 0;
5299 }
5300
5301 static inline unsigned getUNPCKHOpcode(EVT VT) {
5302   switch(VT.getSimpleVT().SimpleTy) {
5303   case MVT::v4i32: return X86ISD::PUNPCKHDQ;
5304   case MVT::v2i64: return X86ISD::PUNPCKHQDQ;
5305   case MVT::v4f32: return X86ISD::UNPCKHPS;
5306   case MVT::v2f64: return X86ISD::UNPCKHPD;
5307   case MVT::v16i8: return X86ISD::PUNPCKHBW;
5308   case MVT::v8i16: return X86ISD::PUNPCKHWD;
5309   default:
5310     llvm_unreachable("Unknow type for unpckh");
5311   }
5312   return 0;
5313 }
5314
5315 static
5316 SDValue NormalizeVectorShuffle(SDValue Op, SelectionDAG &DAG,
5317                                const TargetLowering &TLI,
5318                                const X86Subtarget *Subtarget) {
5319   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
5320   EVT VT = Op.getValueType();
5321   DebugLoc dl = Op.getDebugLoc();
5322   SDValue V1 = Op.getOperand(0);
5323   SDValue V2 = Op.getOperand(1);
5324
5325   if (isZeroShuffle(SVOp))
5326     return getZeroVector(VT, Subtarget->hasSSE2(), DAG, dl);
5327
5328   // Handle splat operations
5329   if (SVOp->isSplat()) {
5330     // Special case, this is the only place now where it's
5331     // allowed to return a vector_shuffle operation without
5332     // using a target specific node, because *hopefully* it
5333     // will be optimized away by the dag combiner.
5334     if (VT.getVectorNumElements() <= 4 &&
5335         CanXFormVExtractWithShuffleIntoLoad(Op, DAG, TLI))
5336       return Op;
5337
5338     // Handle splats by matching through known masks
5339     if (VT.getVectorNumElements() <= 4)
5340       return SDValue();
5341
5342     // Canonicalize all of the remaining to v4f32.
5343     return PromoteSplat(SVOp, DAG);
5344   }
5345
5346   // If the shuffle can be profitably rewritten as a narrower shuffle, then
5347   // do it!
5348   if (VT == MVT::v8i16 || VT == MVT::v16i8) {
5349     SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG, dl);
5350     if (NewOp.getNode())
5351       return DAG.getNode(ISD::BITCAST, dl, VT, NewOp);
5352   } else if ((VT == MVT::v4i32 || (VT == MVT::v4f32 && Subtarget->hasSSE2()))) {
5353     // FIXME: Figure out a cleaner way to do this.
5354     // Try to make use of movq to zero out the top part.
5355     if (ISD::isBuildVectorAllZeros(V2.getNode())) {
5356       SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG, dl);
5357       if (NewOp.getNode()) {
5358         if (isCommutedMOVL(cast<ShuffleVectorSDNode>(NewOp), true, false))
5359           return getVZextMovL(VT, NewOp.getValueType(), NewOp.getOperand(0),
5360                               DAG, Subtarget, dl);
5361       }
5362     } else if (ISD::isBuildVectorAllZeros(V1.getNode())) {
5363       SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG, dl);
5364       if (NewOp.getNode() && X86::isMOVLMask(cast<ShuffleVectorSDNode>(NewOp)))
5365         return getVZextMovL(VT, NewOp.getValueType(), NewOp.getOperand(1),
5366                             DAG, Subtarget, dl);
5367     }
5368   }
5369   return SDValue();
5370 }
5371
5372 SDValue
5373 X86TargetLowering::LowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG) const {
5374   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
5375   SDValue V1 = Op.getOperand(0);
5376   SDValue V2 = Op.getOperand(1);
5377   EVT VT = Op.getValueType();
5378   DebugLoc dl = Op.getDebugLoc();
5379   unsigned NumElems = VT.getVectorNumElements();
5380   bool isMMX = VT.getSizeInBits() == 64;
5381   bool V1IsUndef = V1.getOpcode() == ISD::UNDEF;
5382   bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
5383   bool V1IsSplat = false;
5384   bool V2IsSplat = false;
5385   bool HasSSE2 = Subtarget->hasSSE2() || Subtarget->hasAVX();
5386   bool HasSSE3 = Subtarget->hasSSE3() || Subtarget->hasAVX();
5387   bool HasSSSE3 = Subtarget->hasSSSE3() || Subtarget->hasAVX();
5388   MachineFunction &MF = DAG.getMachineFunction();
5389   bool OptForSize = MF.getFunction()->hasFnAttr(Attribute::OptimizeForSize);
5390
5391   // Shuffle operations on MMX not supported.
5392   if (isMMX)
5393     return Op;
5394
5395   // Vector shuffle lowering takes 3 steps:
5396   //
5397   // 1) Normalize the input vectors. Here splats, zeroed vectors, profitable
5398   //    narrowing and commutation of operands should be handled.
5399   // 2) Matching of shuffles with known shuffle masks to x86 target specific
5400   //    shuffle nodes.
5401   // 3) Rewriting of unmatched masks into new generic shuffle operations,
5402   //    so the shuffle can be broken into other shuffles and the legalizer can
5403   //    try the lowering again.
5404   //
5405   // The general ideia is that no vector_shuffle operation should be left to
5406   // be matched during isel, all of them must be converted to a target specific
5407   // node here.
5408
5409   // Normalize the input vectors. Here splats, zeroed vectors, profitable
5410   // narrowing and commutation of operands should be handled. The actual code
5411   // doesn't include all of those, work in progress...
5412   SDValue NewOp = NormalizeVectorShuffle(Op, DAG, *this, Subtarget);
5413   if (NewOp.getNode())
5414     return NewOp;
5415
5416   // NOTE: isPSHUFDMask can also match both masks below (unpckl_undef and
5417   // unpckh_undef). Only use pshufd if speed is more important than size.
5418   if (OptForSize && X86::isUNPCKL_v_undef_Mask(SVOp))
5419     if (VT != MVT::v2i64 && VT != MVT::v2f64)
5420       return getTargetShuffleNode(getUNPCKLOpcode(VT), dl, VT, V1, V1, DAG);
5421   if (OptForSize && X86::isUNPCKH_v_undef_Mask(SVOp))
5422     if (VT != MVT::v2i64 && VT != MVT::v2f64)
5423       return getTargetShuffleNode(getUNPCKHOpcode(VT), dl, VT, V1, V1, DAG);
5424
5425   if (X86::isMOVDDUPMask(SVOp) && HasSSE3 && V2IsUndef &&
5426       RelaxedMayFoldVectorLoad(V1))
5427     return getMOVDDup(Op, dl, V1, DAG);
5428
5429   if (X86::isMOVHLPS_v_undef_Mask(SVOp))
5430     return getMOVHighToLow(Op, dl, DAG);
5431
5432   // Use to match splats
5433   if (HasSSE2 && X86::isUNPCKHMask(SVOp) && V2IsUndef &&
5434       (VT == MVT::v2f64 || VT == MVT::v2i64))
5435     return getTargetShuffleNode(getUNPCKHOpcode(VT), dl, VT, V1, V1, DAG);
5436
5437   if (X86::isPSHUFDMask(SVOp)) {
5438     // The actual implementation will match the mask in the if above and then
5439     // during isel it can match several different instructions, not only pshufd
5440     // as its name says, sad but true, emulate the behavior for now...
5441     if (X86::isMOVDDUPMask(SVOp) && ((VT == MVT::v4f32 || VT == MVT::v2i64)))
5442         return getTargetShuffleNode(X86ISD::MOVLHPS, dl, VT, V1, V1, DAG);
5443
5444     unsigned TargetMask = X86::getShuffleSHUFImmediate(SVOp);
5445
5446     if (HasSSE2 && (VT == MVT::v4f32 || VT == MVT::v4i32))
5447       return getTargetShuffleNode(X86ISD::PSHUFD, dl, VT, V1, TargetMask, DAG);
5448
5449     if (HasSSE2 && (VT == MVT::v2i64 || VT == MVT::v2f64))
5450       return getTargetShuffleNode(X86ISD::SHUFPD, dl, VT, V1, V1,
5451                                   TargetMask, DAG);
5452
5453     if (VT == MVT::v4f32)
5454       return getTargetShuffleNode(X86ISD::SHUFPS, dl, VT, V1, V1,
5455                                   TargetMask, DAG);
5456   }
5457
5458   // Check if this can be converted into a logical shift.
5459   bool isLeft = false;
5460   unsigned ShAmt = 0;
5461   SDValue ShVal;
5462   bool isShift = getSubtarget()->hasSSE2() &&
5463     isVectorShift(SVOp, DAG, isLeft, ShVal, ShAmt);
5464   if (isShift && ShVal.hasOneUse()) {
5465     // If the shifted value has multiple uses, it may be cheaper to use
5466     // v_set0 + movlhps or movhlps, etc.
5467     EVT EltVT = VT.getVectorElementType();
5468     ShAmt *= EltVT.getSizeInBits();
5469     return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
5470   }
5471
5472   if (X86::isMOVLMask(SVOp)) {
5473     if (V1IsUndef)
5474       return V2;
5475     if (ISD::isBuildVectorAllZeros(V1.getNode()))
5476       return getVZextMovL(VT, VT, V2, DAG, Subtarget, dl);
5477     if (!X86::isMOVLPMask(SVOp)) {
5478       if (HasSSE2 && (VT == MVT::v2i64 || VT == MVT::v2f64))
5479         return getTargetShuffleNode(X86ISD::MOVSD, dl, VT, V1, V2, DAG);
5480
5481       if (VT == MVT::v4i32 || VT == MVT::v4f32)
5482         return getTargetShuffleNode(X86ISD::MOVSS, dl, VT, V1, V2, DAG);
5483     }
5484   }
5485
5486   // FIXME: fold these into legal mask.
5487   if (X86::isMOVLHPSMask(SVOp) && !X86::isUNPCKLMask(SVOp))
5488     return getMOVLowToHigh(Op, dl, DAG, HasSSE2);
5489
5490   if (X86::isMOVHLPSMask(SVOp))
5491     return getMOVHighToLow(Op, dl, DAG);
5492
5493   if (X86::isMOVSHDUPMask(SVOp) && HasSSE3 && V2IsUndef && NumElems == 4)
5494     return getTargetShuffleNode(X86ISD::MOVSHDUP, dl, VT, V1, DAG);
5495
5496   if (X86::isMOVSLDUPMask(SVOp) && HasSSE3 && V2IsUndef && NumElems == 4)
5497     return getTargetShuffleNode(X86ISD::MOVSLDUP, dl, VT, V1, DAG);
5498
5499   if (X86::isMOVLPMask(SVOp))
5500     return getMOVLP(Op, dl, DAG, HasSSE2);
5501
5502   if (ShouldXformToMOVHLPS(SVOp) ||
5503       ShouldXformToMOVLP(V1.getNode(), V2.getNode(), SVOp))
5504     return CommuteVectorShuffle(SVOp, DAG);
5505
5506   if (isShift) {
5507     // No better options. Use a vshl / vsrl.
5508     EVT EltVT = VT.getVectorElementType();
5509     ShAmt *= EltVT.getSizeInBits();
5510     return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
5511   }
5512
5513   bool Commuted = false;
5514   // FIXME: This should also accept a bitcast of a splat?  Be careful, not
5515   // 1,1,1,1 -> v8i16 though.
5516   V1IsSplat = isSplatVector(V1.getNode());
5517   V2IsSplat = isSplatVector(V2.getNode());
5518
5519   // Canonicalize the splat or undef, if present, to be on the RHS.
5520   if ((V1IsSplat || V1IsUndef) && !(V2IsSplat || V2IsUndef)) {
5521     Op = CommuteVectorShuffle(SVOp, DAG);
5522     SVOp = cast<ShuffleVectorSDNode>(Op);
5523     V1 = SVOp->getOperand(0);
5524     V2 = SVOp->getOperand(1);
5525     std::swap(V1IsSplat, V2IsSplat);
5526     std::swap(V1IsUndef, V2IsUndef);
5527     Commuted = true;
5528   }
5529
5530   if (isCommutedMOVL(SVOp, V2IsSplat, V2IsUndef)) {
5531     // Shuffling low element of v1 into undef, just return v1.
5532     if (V2IsUndef)
5533       return V1;
5534     // If V2 is a splat, the mask may be malformed such as <4,3,3,3>, which
5535     // the instruction selector will not match, so get a canonical MOVL with
5536     // swapped operands to undo the commute.
5537     return getMOVL(DAG, dl, VT, V2, V1);
5538   }
5539
5540   if (X86::isUNPCKLMask(SVOp))
5541     return getTargetShuffleNode(getUNPCKLOpcode(VT), dl, VT, V1, V2, DAG);
5542
5543   if (X86::isUNPCKHMask(SVOp))
5544     return getTargetShuffleNode(getUNPCKHOpcode(VT), dl, VT, V1, V2, DAG);
5545
5546   if (V2IsSplat) {
5547     // Normalize mask so all entries that point to V2 points to its first
5548     // element then try to match unpck{h|l} again. If match, return a
5549     // new vector_shuffle with the corrected mask.
5550     SDValue NewMask = NormalizeMask(SVOp, DAG);
5551     ShuffleVectorSDNode *NSVOp = cast<ShuffleVectorSDNode>(NewMask);
5552     if (NSVOp != SVOp) {
5553       if (X86::isUNPCKLMask(NSVOp, true)) {
5554         return NewMask;
5555       } else if (X86::isUNPCKHMask(NSVOp, true)) {
5556         return NewMask;
5557       }
5558     }
5559   }
5560
5561   if (Commuted) {
5562     // Commute is back and try unpck* again.
5563     // FIXME: this seems wrong.
5564     SDValue NewOp = CommuteVectorShuffle(SVOp, DAG);
5565     ShuffleVectorSDNode *NewSVOp = cast<ShuffleVectorSDNode>(NewOp);
5566
5567     if (X86::isUNPCKLMask(NewSVOp))
5568       return getTargetShuffleNode(getUNPCKLOpcode(VT), dl, VT, V2, V1, DAG);
5569
5570     if (X86::isUNPCKHMask(NewSVOp))
5571       return getTargetShuffleNode(getUNPCKHOpcode(VT), dl, VT, V2, V1, DAG);
5572   }
5573
5574   // Normalize the node to match x86 shuffle ops if needed
5575   if (V2.getOpcode() != ISD::UNDEF && isCommutedSHUFP(SVOp))
5576     return CommuteVectorShuffle(SVOp, DAG);
5577
5578   // The checks below are all present in isShuffleMaskLegal, but they are
5579   // inlined here right now to enable us to directly emit target specific
5580   // nodes, and remove one by one until they don't return Op anymore.
5581   SmallVector<int, 16> M;
5582   SVOp->getMask(M);
5583
5584   if (isPALIGNRMask(M, VT, HasSSSE3))
5585     return getTargetShuffleNode(X86ISD::PALIGN, dl, VT, V1, V2,
5586                                 X86::getShufflePALIGNRImmediate(SVOp),
5587                                 DAG);
5588
5589   if (ShuffleVectorSDNode::isSplatMask(&M[0], VT) &&
5590       SVOp->getSplatIndex() == 0 && V2IsUndef) {
5591     if (VT == MVT::v2f64)
5592       return getTargetShuffleNode(X86ISD::UNPCKLPD, dl, VT, V1, V1, DAG);
5593     if (VT == MVT::v2i64)
5594       return getTargetShuffleNode(X86ISD::PUNPCKLQDQ, dl, VT, V1, V1, DAG);
5595   }
5596
5597   if (isPSHUFHWMask(M, VT))
5598     return getTargetShuffleNode(X86ISD::PSHUFHW, dl, VT, V1,
5599                                 X86::getShufflePSHUFHWImmediate(SVOp),
5600                                 DAG);
5601
5602   if (isPSHUFLWMask(M, VT))
5603     return getTargetShuffleNode(X86ISD::PSHUFLW, dl, VT, V1,
5604                                 X86::getShufflePSHUFLWImmediate(SVOp),
5605                                 DAG);
5606
5607   if (isSHUFPMask(M, VT)) {
5608     unsigned TargetMask = X86::getShuffleSHUFImmediate(SVOp);
5609     if (VT == MVT::v4f32 || VT == MVT::v4i32)
5610       return getTargetShuffleNode(X86ISD::SHUFPS, dl, VT, V1, V2,
5611                                   TargetMask, DAG);
5612     if (VT == MVT::v2f64 || VT == MVT::v2i64)
5613       return getTargetShuffleNode(X86ISD::SHUFPD, dl, VT, V1, V2,
5614                                   TargetMask, DAG);
5615   }
5616
5617   if (X86::isUNPCKL_v_undef_Mask(SVOp))
5618     if (VT != MVT::v2i64 && VT != MVT::v2f64)
5619       return getTargetShuffleNode(getUNPCKLOpcode(VT), dl, VT, V1, V1, DAG);
5620   if (X86::isUNPCKH_v_undef_Mask(SVOp))
5621     if (VT != MVT::v2i64 && VT != MVT::v2f64)
5622       return getTargetShuffleNode(getUNPCKHOpcode(VT), dl, VT, V1, V1, DAG);
5623
5624   // Handle v8i16 specifically since SSE can do byte extraction and insertion.
5625   if (VT == MVT::v8i16) {
5626     SDValue NewOp = LowerVECTOR_SHUFFLEv8i16(Op, DAG);
5627     if (NewOp.getNode())
5628       return NewOp;
5629   }
5630
5631   if (VT == MVT::v16i8) {
5632     SDValue NewOp = LowerVECTOR_SHUFFLEv16i8(SVOp, DAG, *this);
5633     if (NewOp.getNode())
5634       return NewOp;
5635   }
5636
5637   // Handle all 4 wide cases with a number of shuffles.
5638   if (NumElems == 4)
5639     return LowerVECTOR_SHUFFLE_4wide(SVOp, DAG);
5640
5641   return SDValue();
5642 }
5643
5644 SDValue
5645 X86TargetLowering::LowerEXTRACT_VECTOR_ELT_SSE4(SDValue Op,
5646                                                 SelectionDAG &DAG) const {
5647   EVT VT = Op.getValueType();
5648   DebugLoc dl = Op.getDebugLoc();
5649   if (VT.getSizeInBits() == 8) {
5650     SDValue Extract = DAG.getNode(X86ISD::PEXTRB, dl, MVT::i32,
5651                                     Op.getOperand(0), Op.getOperand(1));
5652     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
5653                                     DAG.getValueType(VT));
5654     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
5655   } else if (VT.getSizeInBits() == 16) {
5656     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
5657     // If Idx is 0, it's cheaper to do a move instead of a pextrw.
5658     if (Idx == 0)
5659       return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
5660                          DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
5661                                      DAG.getNode(ISD::BITCAST, dl,
5662                                                  MVT::v4i32,
5663                                                  Op.getOperand(0)),
5664                                      Op.getOperand(1)));
5665     SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, MVT::i32,
5666                                     Op.getOperand(0), Op.getOperand(1));
5667     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
5668                                     DAG.getValueType(VT));
5669     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
5670   } else if (VT == MVT::f32) {
5671     // EXTRACTPS outputs to a GPR32 register which will require a movd to copy
5672     // the result back to FR32 register. It's only worth matching if the
5673     // result has a single use which is a store or a bitcast to i32.  And in
5674     // the case of a store, it's not worth it if the index is a constant 0,
5675     // because a MOVSSmr can be used instead, which is smaller and faster.
5676     if (!Op.hasOneUse())
5677       return SDValue();
5678     SDNode *User = *Op.getNode()->use_begin();
5679     if ((User->getOpcode() != ISD::STORE ||
5680          (isa<ConstantSDNode>(Op.getOperand(1)) &&
5681           cast<ConstantSDNode>(Op.getOperand(1))->isNullValue())) &&
5682         (User->getOpcode() != ISD::BITCAST ||
5683          User->getValueType(0) != MVT::i32))
5684       return SDValue();
5685     SDValue Extract = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
5686                                   DAG.getNode(ISD::BITCAST, dl, MVT::v4i32,
5687                                               Op.getOperand(0)),
5688                                               Op.getOperand(1));
5689     return DAG.getNode(ISD::BITCAST, dl, MVT::f32, Extract);
5690   } else if (VT == MVT::i32) {
5691     // ExtractPS works with constant index.
5692     if (isa<ConstantSDNode>(Op.getOperand(1)))
5693       return Op;
5694   }
5695   return SDValue();
5696 }
5697
5698
5699 SDValue
5700 X86TargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op,
5701                                            SelectionDAG &DAG) const {
5702   if (!isa<ConstantSDNode>(Op.getOperand(1)))
5703     return SDValue();
5704
5705   if (Subtarget->hasSSE41()) {
5706     SDValue Res = LowerEXTRACT_VECTOR_ELT_SSE4(Op, DAG);
5707     if (Res.getNode())
5708       return Res;
5709   }
5710
5711   EVT VT = Op.getValueType();
5712   DebugLoc dl = Op.getDebugLoc();
5713   // TODO: handle v16i8.
5714   if (VT.getSizeInBits() == 16) {
5715     SDValue Vec = Op.getOperand(0);
5716     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
5717     if (Idx == 0)
5718       return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
5719                          DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
5720                                      DAG.getNode(ISD::BITCAST, dl,
5721                                                  MVT::v4i32, Vec),
5722                                      Op.getOperand(1)));
5723     // Transform it so it match pextrw which produces a 32-bit result.
5724     EVT EltVT = MVT::i32;
5725     SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, EltVT,
5726                                     Op.getOperand(0), Op.getOperand(1));
5727     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, EltVT, Extract,
5728                                     DAG.getValueType(VT));
5729     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
5730   } else if (VT.getSizeInBits() == 32) {
5731     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
5732     if (Idx == 0)
5733       return Op;
5734
5735     // SHUFPS the element to the lowest double word, then movss.
5736     int Mask[4] = { Idx, -1, -1, -1 };
5737     EVT VVT = Op.getOperand(0).getValueType();
5738     SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
5739                                        DAG.getUNDEF(VVT), Mask);
5740     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
5741                        DAG.getIntPtrConstant(0));
5742   } else if (VT.getSizeInBits() == 64) {
5743     // FIXME: .td only matches this for <2 x f64>, not <2 x i64> on 32b
5744     // FIXME: seems like this should be unnecessary if mov{h,l}pd were taught
5745     //        to match extract_elt for f64.
5746     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
5747     if (Idx == 0)
5748       return Op;
5749
5750     // UNPCKHPD the element to the lowest double word, then movsd.
5751     // Note if the lower 64 bits of the result of the UNPCKHPD is then stored
5752     // to a f64mem, the whole operation is folded into a single MOVHPDmr.
5753     int Mask[2] = { 1, -1 };
5754     EVT VVT = Op.getOperand(0).getValueType();
5755     SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
5756                                        DAG.getUNDEF(VVT), Mask);
5757     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
5758                        DAG.getIntPtrConstant(0));
5759   }
5760
5761   return SDValue();
5762 }
5763
5764 SDValue
5765 X86TargetLowering::LowerINSERT_VECTOR_ELT_SSE4(SDValue Op,
5766                                                SelectionDAG &DAG) const {
5767   EVT VT = Op.getValueType();
5768   EVT EltVT = VT.getVectorElementType();
5769   DebugLoc dl = Op.getDebugLoc();
5770
5771   SDValue N0 = Op.getOperand(0);
5772   SDValue N1 = Op.getOperand(1);
5773   SDValue N2 = Op.getOperand(2);
5774
5775   if ((EltVT.getSizeInBits() == 8 || EltVT.getSizeInBits() == 16) &&
5776       isa<ConstantSDNode>(N2)) {
5777     unsigned Opc;
5778     if (VT == MVT::v8i16)
5779       Opc = X86ISD::PINSRW;
5780     else if (VT == MVT::v16i8)
5781       Opc = X86ISD::PINSRB;
5782     else
5783       Opc = X86ISD::PINSRB;
5784
5785     // Transform it so it match pinsr{b,w} which expects a GR32 as its second
5786     // argument.
5787     if (N1.getValueType() != MVT::i32)
5788       N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
5789     if (N2.getValueType() != MVT::i32)
5790       N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue());
5791     return DAG.getNode(Opc, dl, VT, N0, N1, N2);
5792   } else if (EltVT == MVT::f32 && isa<ConstantSDNode>(N2)) {
5793     // Bits [7:6] of the constant are the source select.  This will always be
5794     //  zero here.  The DAG Combiner may combine an extract_elt index into these
5795     //  bits.  For example (insert (extract, 3), 2) could be matched by putting
5796     //  the '3' into bits [7:6] of X86ISD::INSERTPS.
5797     // Bits [5:4] of the constant are the destination select.  This is the
5798     //  value of the incoming immediate.
5799     // Bits [3:0] of the constant are the zero mask.  The DAG Combiner may
5800     //   combine either bitwise AND or insert of float 0.0 to set these bits.
5801     N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue() << 4);
5802     // Create this as a scalar to vector..
5803     N1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4f32, N1);
5804     return DAG.getNode(X86ISD::INSERTPS, dl, VT, N0, N1, N2);
5805   } else if (EltVT == MVT::i32 && isa<ConstantSDNode>(N2)) {
5806     // PINSR* works with constant index.
5807     return Op;
5808   }
5809   return SDValue();
5810 }
5811
5812 SDValue
5813 X86TargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) const {
5814   EVT VT = Op.getValueType();
5815   EVT EltVT = VT.getVectorElementType();
5816
5817   if (Subtarget->hasSSE41())
5818     return LowerINSERT_VECTOR_ELT_SSE4(Op, DAG);
5819
5820   if (EltVT == MVT::i8)
5821     return SDValue();
5822
5823   DebugLoc dl = Op.getDebugLoc();
5824   SDValue N0 = Op.getOperand(0);
5825   SDValue N1 = Op.getOperand(1);
5826   SDValue N2 = Op.getOperand(2);
5827
5828   if (EltVT.getSizeInBits() == 16 && isa<ConstantSDNode>(N2)) {
5829     // Transform it so it match pinsrw which expects a 16-bit value in a GR32
5830     // as its second argument.
5831     if (N1.getValueType() != MVT::i32)
5832       N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
5833     if (N2.getValueType() != MVT::i32)
5834       N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue());
5835     return DAG.getNode(X86ISD::PINSRW, dl, VT, N0, N1, N2);
5836   }
5837   return SDValue();
5838 }
5839
5840 SDValue
5841 X86TargetLowering::LowerSCALAR_TO_VECTOR(SDValue Op, SelectionDAG &DAG) const {
5842   DebugLoc dl = Op.getDebugLoc();
5843
5844   if (Op.getValueType() == MVT::v1i64 &&
5845       Op.getOperand(0).getValueType() == MVT::i64)
5846     return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v1i64, Op.getOperand(0));
5847
5848   SDValue AnyExt = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, Op.getOperand(0));
5849   assert(Op.getValueType().getSimpleVT().getSizeInBits() == 128 &&
5850          "Expected an SSE type!");
5851   return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(),
5852                      DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,AnyExt));
5853 }
5854
5855 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
5856 // their target countpart wrapped in the X86ISD::Wrapper node. Suppose N is
5857 // one of the above mentioned nodes. It has to be wrapped because otherwise
5858 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
5859 // be used to form addressing mode. These wrapped nodes will be selected
5860 // into MOV32ri.
5861 SDValue
5862 X86TargetLowering::LowerConstantPool(SDValue Op, SelectionDAG &DAG) const {
5863   ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
5864
5865   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
5866   // global base reg.
5867   unsigned char OpFlag = 0;
5868   unsigned WrapperKind = X86ISD::Wrapper;
5869   CodeModel::Model M = getTargetMachine().getCodeModel();
5870
5871   if (Subtarget->isPICStyleRIPRel() &&
5872       (M == CodeModel::Small || M == CodeModel::Kernel))
5873     WrapperKind = X86ISD::WrapperRIP;
5874   else if (Subtarget->isPICStyleGOT())
5875     OpFlag = X86II::MO_GOTOFF;
5876   else if (Subtarget->isPICStyleStubPIC())
5877     OpFlag = X86II::MO_PIC_BASE_OFFSET;
5878
5879   SDValue Result = DAG.getTargetConstantPool(CP->getConstVal(), getPointerTy(),
5880                                              CP->getAlignment(),
5881                                              CP->getOffset(), OpFlag);
5882   DebugLoc DL = CP->getDebugLoc();
5883   Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
5884   // With PIC, the address is actually $g + Offset.
5885   if (OpFlag) {
5886     Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
5887                          DAG.getNode(X86ISD::GlobalBaseReg,
5888                                      DebugLoc(), getPointerTy()),
5889                          Result);
5890   }
5891
5892   return Result;
5893 }
5894
5895 SDValue X86TargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) const {
5896   JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
5897
5898   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
5899   // global base reg.
5900   unsigned char OpFlag = 0;
5901   unsigned WrapperKind = X86ISD::Wrapper;
5902   CodeModel::Model M = getTargetMachine().getCodeModel();
5903
5904   if (Subtarget->isPICStyleRIPRel() &&
5905       (M == CodeModel::Small || M == CodeModel::Kernel))
5906     WrapperKind = X86ISD::WrapperRIP;
5907   else if (Subtarget->isPICStyleGOT())
5908     OpFlag = X86II::MO_GOTOFF;
5909   else if (Subtarget->isPICStyleStubPIC())
5910     OpFlag = X86II::MO_PIC_BASE_OFFSET;
5911
5912   SDValue Result = DAG.getTargetJumpTable(JT->getIndex(), getPointerTy(),
5913                                           OpFlag);
5914   DebugLoc DL = JT->getDebugLoc();
5915   Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
5916
5917   // With PIC, the address is actually $g + Offset.
5918   if (OpFlag)
5919     Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
5920                          DAG.getNode(X86ISD::GlobalBaseReg,
5921                                      DebugLoc(), getPointerTy()),
5922                          Result);
5923
5924   return Result;
5925 }
5926
5927 SDValue
5928 X86TargetLowering::LowerExternalSymbol(SDValue Op, SelectionDAG &DAG) const {
5929   const char *Sym = cast<ExternalSymbolSDNode>(Op)->getSymbol();
5930
5931   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
5932   // global base reg.
5933   unsigned char OpFlag = 0;
5934   unsigned WrapperKind = X86ISD::Wrapper;
5935   CodeModel::Model M = getTargetMachine().getCodeModel();
5936
5937   if (Subtarget->isPICStyleRIPRel() &&
5938       (M == CodeModel::Small || M == CodeModel::Kernel))
5939     WrapperKind = X86ISD::WrapperRIP;
5940   else if (Subtarget->isPICStyleGOT())
5941     OpFlag = X86II::MO_GOTOFF;
5942   else if (Subtarget->isPICStyleStubPIC())
5943     OpFlag = X86II::MO_PIC_BASE_OFFSET;
5944
5945   SDValue Result = DAG.getTargetExternalSymbol(Sym, getPointerTy(), OpFlag);
5946
5947   DebugLoc DL = Op.getDebugLoc();
5948   Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
5949
5950
5951   // With PIC, the address is actually $g + Offset.
5952   if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
5953       !Subtarget->is64Bit()) {
5954     Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
5955                          DAG.getNode(X86ISD::GlobalBaseReg,
5956                                      DebugLoc(), getPointerTy()),
5957                          Result);
5958   }
5959
5960   return Result;
5961 }
5962
5963 SDValue
5964 X86TargetLowering::LowerBlockAddress(SDValue Op, SelectionDAG &DAG) const {
5965   // Create the TargetBlockAddressAddress node.
5966   unsigned char OpFlags =
5967     Subtarget->ClassifyBlockAddressReference();
5968   CodeModel::Model M = getTargetMachine().getCodeModel();
5969   const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
5970   DebugLoc dl = Op.getDebugLoc();
5971   SDValue Result = DAG.getBlockAddress(BA, getPointerTy(),
5972                                        /*isTarget=*/true, OpFlags);
5973
5974   if (Subtarget->isPICStyleRIPRel() &&
5975       (M == CodeModel::Small || M == CodeModel::Kernel))
5976     Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
5977   else
5978     Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
5979
5980   // With PIC, the address is actually $g + Offset.
5981   if (isGlobalRelativeToPICBase(OpFlags)) {
5982     Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
5983                          DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
5984                          Result);
5985   }
5986
5987   return Result;
5988 }
5989
5990 SDValue
5991 X86TargetLowering::LowerGlobalAddress(const GlobalValue *GV, DebugLoc dl,
5992                                       int64_t Offset,
5993                                       SelectionDAG &DAG) const {
5994   // Create the TargetGlobalAddress node, folding in the constant
5995   // offset if it is legal.
5996   unsigned char OpFlags =
5997     Subtarget->ClassifyGlobalReference(GV, getTargetMachine());
5998   CodeModel::Model M = getTargetMachine().getCodeModel();
5999   SDValue Result;
6000   if (OpFlags == X86II::MO_NO_FLAG &&
6001       X86::isOffsetSuitableForCodeModel(Offset, M)) {
6002     // A direct static reference to a global.
6003     Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), Offset);
6004     Offset = 0;
6005   } else {
6006     Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), 0, OpFlags);
6007   }
6008
6009   if (Subtarget->isPICStyleRIPRel() &&
6010       (M == CodeModel::Small || M == CodeModel::Kernel))
6011     Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
6012   else
6013     Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
6014
6015   // With PIC, the address is actually $g + Offset.
6016   if (isGlobalRelativeToPICBase(OpFlags)) {
6017     Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
6018                          DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
6019                          Result);
6020   }
6021
6022   // For globals that require a load from a stub to get the address, emit the
6023   // load.
6024   if (isGlobalStubReference(OpFlags))
6025     Result = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Result,
6026                          MachinePointerInfo::getGOT(), false, false, 0);
6027
6028   // If there was a non-zero offset that we didn't fold, create an explicit
6029   // addition for it.
6030   if (Offset != 0)
6031     Result = DAG.getNode(ISD::ADD, dl, getPointerTy(), Result,
6032                          DAG.getConstant(Offset, getPointerTy()));
6033
6034   return Result;
6035 }
6036
6037 SDValue
6038 X86TargetLowering::LowerGlobalAddress(SDValue Op, SelectionDAG &DAG) const {
6039   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
6040   int64_t Offset = cast<GlobalAddressSDNode>(Op)->getOffset();
6041   return LowerGlobalAddress(GV, Op.getDebugLoc(), Offset, DAG);
6042 }
6043
6044 static SDValue
6045 GetTLSADDR(SelectionDAG &DAG, SDValue Chain, GlobalAddressSDNode *GA,
6046            SDValue *InFlag, const EVT PtrVT, unsigned ReturnReg,
6047            unsigned char OperandFlags) {
6048   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
6049   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Flag);
6050   DebugLoc dl = GA->getDebugLoc();
6051   SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
6052                                            GA->getValueType(0),
6053                                            GA->getOffset(),
6054                                            OperandFlags);
6055   if (InFlag) {
6056     SDValue Ops[] = { Chain,  TGA, *InFlag };
6057     Chain = DAG.getNode(X86ISD::TLSADDR, dl, NodeTys, Ops, 3);
6058   } else {
6059     SDValue Ops[]  = { Chain, TGA };
6060     Chain = DAG.getNode(X86ISD::TLSADDR, dl, NodeTys, Ops, 2);
6061   }
6062
6063   // TLSADDR will be codegen'ed as call. Inform MFI that function has calls.
6064   MFI->setAdjustsStack(true);
6065
6066   SDValue Flag = Chain.getValue(1);
6067   return DAG.getCopyFromReg(Chain, dl, ReturnReg, PtrVT, Flag);
6068 }
6069
6070 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 32 bit
6071 static SDValue
6072 LowerToTLSGeneralDynamicModel32(GlobalAddressSDNode *GA, SelectionDAG &DAG,
6073                                 const EVT PtrVT) {
6074   SDValue InFlag;
6075   DebugLoc dl = GA->getDebugLoc();  // ? function entry point might be better
6076   SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
6077                                      DAG.getNode(X86ISD::GlobalBaseReg,
6078                                                  DebugLoc(), PtrVT), InFlag);
6079   InFlag = Chain.getValue(1);
6080
6081   return GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX, X86II::MO_TLSGD);
6082 }
6083
6084 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 64 bit
6085 static SDValue
6086 LowerToTLSGeneralDynamicModel64(GlobalAddressSDNode *GA, SelectionDAG &DAG,
6087                                 const EVT PtrVT) {
6088   return GetTLSADDR(DAG, DAG.getEntryNode(), GA, NULL, PtrVT,
6089                     X86::RAX, X86II::MO_TLSGD);
6090 }
6091
6092 // Lower ISD::GlobalTLSAddress using the "initial exec" (for no-pic) or
6093 // "local exec" model.
6094 static SDValue LowerToTLSExecModel(GlobalAddressSDNode *GA, SelectionDAG &DAG,
6095                                    const EVT PtrVT, TLSModel::Model model,
6096                                    bool is64Bit) {
6097   DebugLoc dl = GA->getDebugLoc();
6098
6099   // Get the Thread Pointer, which is %gs:0 (32-bit) or %fs:0 (64-bit).
6100   Value *Ptr = Constant::getNullValue(Type::getInt8PtrTy(*DAG.getContext(),
6101                                                          is64Bit ? 257 : 256));
6102
6103   SDValue ThreadPointer = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
6104                                       DAG.getIntPtrConstant(0),
6105                                       MachinePointerInfo(Ptr), false, false, 0);
6106
6107   unsigned char OperandFlags = 0;
6108   // Most TLS accesses are not RIP relative, even on x86-64.  One exception is
6109   // initialexec.
6110   unsigned WrapperKind = X86ISD::Wrapper;
6111   if (model == TLSModel::LocalExec) {
6112     OperandFlags = is64Bit ? X86II::MO_TPOFF : X86II::MO_NTPOFF;
6113   } else if (is64Bit) {
6114     assert(model == TLSModel::InitialExec);
6115     OperandFlags = X86II::MO_GOTTPOFF;
6116     WrapperKind = X86ISD::WrapperRIP;
6117   } else {
6118     assert(model == TLSModel::InitialExec);
6119     OperandFlags = X86II::MO_INDNTPOFF;
6120   }
6121
6122   // emit "addl x@ntpoff,%eax" (local exec) or "addl x@indntpoff,%eax" (initial
6123   // exec)
6124   SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
6125                                            GA->getValueType(0),
6126                                            GA->getOffset(), OperandFlags);
6127   SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
6128
6129   if (model == TLSModel::InitialExec)
6130     Offset = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Offset,
6131                          MachinePointerInfo::getGOT(), false, false, 0);
6132
6133   // The address of the thread local variable is the add of the thread
6134   // pointer with the offset of the variable.
6135   return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
6136 }
6137
6138 SDValue
6139 X86TargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const {
6140
6141   GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
6142   const GlobalValue *GV = GA->getGlobal();
6143
6144   if (Subtarget->isTargetELF()) {
6145     // TODO: implement the "local dynamic" model
6146     // TODO: implement the "initial exec"model for pic executables
6147
6148     // If GV is an alias then use the aliasee for determining
6149     // thread-localness.
6150     if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(GV))
6151       GV = GA->resolveAliasedGlobal(false);
6152
6153     TLSModel::Model model
6154       = getTLSModel(GV, getTargetMachine().getRelocationModel());
6155
6156     switch (model) {
6157       case TLSModel::GeneralDynamic:
6158       case TLSModel::LocalDynamic: // not implemented
6159         if (Subtarget->is64Bit())
6160           return LowerToTLSGeneralDynamicModel64(GA, DAG, getPointerTy());
6161         return LowerToTLSGeneralDynamicModel32(GA, DAG, getPointerTy());
6162
6163       case TLSModel::InitialExec:
6164       case TLSModel::LocalExec:
6165         return LowerToTLSExecModel(GA, DAG, getPointerTy(), model,
6166                                    Subtarget->is64Bit());
6167     }
6168   } else if (Subtarget->isTargetDarwin()) {
6169     // Darwin only has one model of TLS.  Lower to that.
6170     unsigned char OpFlag = 0;
6171     unsigned WrapperKind = Subtarget->isPICStyleRIPRel() ?
6172                            X86ISD::WrapperRIP : X86ISD::Wrapper;
6173
6174     // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
6175     // global base reg.
6176     bool PIC32 = (getTargetMachine().getRelocationModel() == Reloc::PIC_) &&
6177                   !Subtarget->is64Bit();
6178     if (PIC32)
6179       OpFlag = X86II::MO_TLVP_PIC_BASE;
6180     else
6181       OpFlag = X86II::MO_TLVP;
6182     DebugLoc DL = Op.getDebugLoc();
6183     SDValue Result = DAG.getTargetGlobalAddress(GA->getGlobal(), DL,
6184                                                 GA->getValueType(0),
6185                                                 GA->getOffset(), OpFlag);
6186     SDValue Offset = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
6187
6188     // With PIC32, the address is actually $g + Offset.
6189     if (PIC32)
6190       Offset = DAG.getNode(ISD::ADD, DL, getPointerTy(),
6191                            DAG.getNode(X86ISD::GlobalBaseReg,
6192                                        DebugLoc(), getPointerTy()),
6193                            Offset);
6194
6195     // Lowering the machine isd will make sure everything is in the right
6196     // location.
6197     SDValue Chain = DAG.getEntryNode();
6198     SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Flag);
6199     SDValue Args[] = { Chain, Offset };
6200     Chain = DAG.getNode(X86ISD::TLSCALL, DL, NodeTys, Args, 2);
6201
6202     // TLSCALL will be codegen'ed as call. Inform MFI that function has calls.
6203     MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
6204     MFI->setAdjustsStack(true);
6205     
6206     // And our return value (tls address) is in the standard call return value
6207     // location.
6208     unsigned Reg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
6209     return DAG.getCopyFromReg(Chain, DL, Reg, getPointerTy());
6210   }
6211
6212   assert(false &&
6213          "TLS not implemented for this target.");
6214
6215   llvm_unreachable("Unreachable");
6216   return SDValue();
6217 }
6218
6219
6220 /// LowerShift - Lower SRA_PARTS and friends, which return two i32 values and
6221 /// take a 2 x i32 value to shift plus a shift amount.
6222 SDValue X86TargetLowering::LowerShift(SDValue Op, SelectionDAG &DAG) const {
6223   assert(Op.getNumOperands() == 3 && "Not a double-shift!");
6224   EVT VT = Op.getValueType();
6225   unsigned VTBits = VT.getSizeInBits();
6226   DebugLoc dl = Op.getDebugLoc();
6227   bool isSRA = Op.getOpcode() == ISD::SRA_PARTS;
6228   SDValue ShOpLo = Op.getOperand(0);
6229   SDValue ShOpHi = Op.getOperand(1);
6230   SDValue ShAmt  = Op.getOperand(2);
6231   SDValue Tmp1 = isSRA ? DAG.getNode(ISD::SRA, dl, VT, ShOpHi,
6232                                      DAG.getConstant(VTBits - 1, MVT::i8))
6233                        : DAG.getConstant(0, VT);
6234
6235   SDValue Tmp2, Tmp3;
6236   if (Op.getOpcode() == ISD::SHL_PARTS) {
6237     Tmp2 = DAG.getNode(X86ISD::SHLD, dl, VT, ShOpHi, ShOpLo, ShAmt);
6238     Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ShAmt);
6239   } else {
6240     Tmp2 = DAG.getNode(X86ISD::SHRD, dl, VT, ShOpLo, ShOpHi, ShAmt);
6241     Tmp3 = DAG.getNode(isSRA ? ISD::SRA : ISD::SRL, dl, VT, ShOpHi, ShAmt);
6242   }
6243
6244   SDValue AndNode = DAG.getNode(ISD::AND, dl, MVT::i8, ShAmt,
6245                                 DAG.getConstant(VTBits, MVT::i8));
6246   SDValue Cond = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
6247                              AndNode, DAG.getConstant(0, MVT::i8));
6248
6249   SDValue Hi, Lo;
6250   SDValue CC = DAG.getConstant(X86::COND_NE, MVT::i8);
6251   SDValue Ops0[4] = { Tmp2, Tmp3, CC, Cond };
6252   SDValue Ops1[4] = { Tmp3, Tmp1, CC, Cond };
6253
6254   if (Op.getOpcode() == ISD::SHL_PARTS) {
6255     Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0, 4);
6256     Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1, 4);
6257   } else {
6258     Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0, 4);
6259     Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1, 4);
6260   }
6261
6262   SDValue Ops[2] = { Lo, Hi };
6263   return DAG.getMergeValues(Ops, 2, dl);
6264 }
6265
6266 SDValue X86TargetLowering::LowerSINT_TO_FP(SDValue Op,
6267                                            SelectionDAG &DAG) const {
6268   EVT SrcVT = Op.getOperand(0).getValueType();
6269
6270   if (SrcVT.isVector())
6271     return SDValue();
6272
6273   assert(SrcVT.getSimpleVT() <= MVT::i64 && SrcVT.getSimpleVT() >= MVT::i16 &&
6274          "Unknown SINT_TO_FP to lower!");
6275
6276   // These are really Legal; return the operand so the caller accepts it as
6277   // Legal.
6278   if (SrcVT == MVT::i32 && isScalarFPTypeInSSEReg(Op.getValueType()))
6279     return Op;
6280   if (SrcVT == MVT::i64 && isScalarFPTypeInSSEReg(Op.getValueType()) &&
6281       Subtarget->is64Bit()) {
6282     return Op;
6283   }
6284
6285   DebugLoc dl = Op.getDebugLoc();
6286   unsigned Size = SrcVT.getSizeInBits()/8;
6287   MachineFunction &MF = DAG.getMachineFunction();
6288   int SSFI = MF.getFrameInfo()->CreateStackObject(Size, Size, false);
6289   SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
6290   SDValue Chain = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
6291                                StackSlot,
6292                                MachinePointerInfo::getFixedStack(SSFI),
6293                                false, false, 0);
6294   return BuildFILD(Op, SrcVT, Chain, StackSlot, DAG);
6295 }
6296
6297 SDValue X86TargetLowering::BuildFILD(SDValue Op, EVT SrcVT, SDValue Chain,
6298                                      SDValue StackSlot,
6299                                      SelectionDAG &DAG) const {
6300   // Build the FILD
6301   DebugLoc DL = Op.getDebugLoc();
6302   SDVTList Tys;
6303   bool useSSE = isScalarFPTypeInSSEReg(Op.getValueType());
6304   if (useSSE)
6305     Tys = DAG.getVTList(MVT::f64, MVT::Other, MVT::Flag);
6306   else
6307     Tys = DAG.getVTList(Op.getValueType(), MVT::Other);
6308
6309   unsigned ByteSize = SrcVT.getSizeInBits()/8;
6310
6311   int SSFI = cast<FrameIndexSDNode>(StackSlot)->getIndex();
6312   MachineMemOperand *MMO =
6313     DAG.getMachineFunction()
6314     .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
6315                           MachineMemOperand::MOLoad, ByteSize, ByteSize);
6316
6317   SDValue Ops[] = { Chain, StackSlot, DAG.getValueType(SrcVT) };
6318   SDValue Result = DAG.getMemIntrinsicNode(useSSE ? X86ISD::FILD_FLAG :
6319                                            X86ISD::FILD, DL,
6320                                            Tys, Ops, array_lengthof(Ops),
6321                                            SrcVT, MMO);
6322
6323   if (useSSE) {
6324     Chain = Result.getValue(1);
6325     SDValue InFlag = Result.getValue(2);
6326
6327     // FIXME: Currently the FST is flagged to the FILD_FLAG. This
6328     // shouldn't be necessary except that RFP cannot be live across
6329     // multiple blocks. When stackifier is fixed, they can be uncoupled.
6330     MachineFunction &MF = DAG.getMachineFunction();
6331     unsigned SSFISize = Op.getValueType().getSizeInBits()/8;
6332     int SSFI = MF.getFrameInfo()->CreateStackObject(SSFISize, SSFISize, false);
6333     SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
6334     Tys = DAG.getVTList(MVT::Other);
6335     SDValue Ops[] = {
6336       Chain, Result, StackSlot, DAG.getValueType(Op.getValueType()), InFlag
6337     };
6338     MachineMemOperand *MMO =
6339       DAG.getMachineFunction()
6340       .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
6341                             MachineMemOperand::MOStore, SSFISize, SSFISize);
6342
6343     Chain = DAG.getMemIntrinsicNode(X86ISD::FST, DL, Tys,
6344                                     Ops, array_lengthof(Ops),
6345                                     Op.getValueType(), MMO);
6346     Result = DAG.getLoad(Op.getValueType(), DL, Chain, StackSlot,
6347                          MachinePointerInfo::getFixedStack(SSFI),
6348                          false, false, 0);
6349   }
6350
6351   return Result;
6352 }
6353
6354 // LowerUINT_TO_FP_i64 - 64-bit unsigned integer to double expansion.
6355 SDValue X86TargetLowering::LowerUINT_TO_FP_i64(SDValue Op,
6356                                                SelectionDAG &DAG) const {
6357   // This algorithm is not obvious. Here it is in C code, more or less:
6358   /*
6359     double uint64_to_double( uint32_t hi, uint32_t lo ) {
6360       static const __m128i exp = { 0x4330000045300000ULL, 0 };
6361       static const __m128d bias = { 0x1.0p84, 0x1.0p52 };
6362
6363       // Copy ints to xmm registers.
6364       __m128i xh = _mm_cvtsi32_si128( hi );
6365       __m128i xl = _mm_cvtsi32_si128( lo );
6366
6367       // Combine into low half of a single xmm register.
6368       __m128i x = _mm_unpacklo_epi32( xh, xl );
6369       __m128d d;
6370       double sd;
6371
6372       // Merge in appropriate exponents to give the integer bits the right
6373       // magnitude.
6374       x = _mm_unpacklo_epi32( x, exp );
6375
6376       // Subtract away the biases to deal with the IEEE-754 double precision
6377       // implicit 1.
6378       d = _mm_sub_pd( (__m128d) x, bias );
6379
6380       // All conversions up to here are exact. The correctly rounded result is
6381       // calculated using the current rounding mode using the following
6382       // horizontal add.
6383       d = _mm_add_sd( d, _mm_unpackhi_pd( d, d ) );
6384       _mm_store_sd( &sd, d );   // Because we are returning doubles in XMM, this
6385                                 // store doesn't really need to be here (except
6386                                 // maybe to zero the other double)
6387       return sd;
6388     }
6389   */
6390
6391   DebugLoc dl = Op.getDebugLoc();
6392   LLVMContext *Context = DAG.getContext();
6393
6394   // Build some magic constants.
6395   std::vector<Constant*> CV0;
6396   CV0.push_back(ConstantInt::get(*Context, APInt(32, 0x45300000)));
6397   CV0.push_back(ConstantInt::get(*Context, APInt(32, 0x43300000)));
6398   CV0.push_back(ConstantInt::get(*Context, APInt(32, 0)));
6399   CV0.push_back(ConstantInt::get(*Context, APInt(32, 0)));
6400   Constant *C0 = ConstantVector::get(CV0);
6401   SDValue CPIdx0 = DAG.getConstantPool(C0, getPointerTy(), 16);
6402
6403   std::vector<Constant*> CV1;
6404   CV1.push_back(
6405     ConstantFP::get(*Context, APFloat(APInt(64, 0x4530000000000000ULL))));
6406   CV1.push_back(
6407     ConstantFP::get(*Context, APFloat(APInt(64, 0x4330000000000000ULL))));
6408   Constant *C1 = ConstantVector::get(CV1);
6409   SDValue CPIdx1 = DAG.getConstantPool(C1, getPointerTy(), 16);
6410
6411   SDValue XR1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
6412                             DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
6413                                         Op.getOperand(0),
6414                                         DAG.getIntPtrConstant(1)));
6415   SDValue XR2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
6416                             DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
6417                                         Op.getOperand(0),
6418                                         DAG.getIntPtrConstant(0)));
6419   SDValue Unpck1 = getUnpackl(DAG, dl, MVT::v4i32, XR1, XR2);
6420   SDValue CLod0 = DAG.getLoad(MVT::v4i32, dl, DAG.getEntryNode(), CPIdx0,
6421                               MachinePointerInfo::getConstantPool(),
6422                               false, false, 16);
6423   SDValue Unpck2 = getUnpackl(DAG, dl, MVT::v4i32, Unpck1, CLod0);
6424   SDValue XR2F = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Unpck2);
6425   SDValue CLod1 = DAG.getLoad(MVT::v2f64, dl, CLod0.getValue(1), CPIdx1,
6426                               MachinePointerInfo::getConstantPool(),
6427                               false, false, 16);
6428   SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, XR2F, CLod1);
6429
6430   // Add the halves; easiest way is to swap them into another reg first.
6431   int ShufMask[2] = { 1, -1 };
6432   SDValue Shuf = DAG.getVectorShuffle(MVT::v2f64, dl, Sub,
6433                                       DAG.getUNDEF(MVT::v2f64), ShufMask);
6434   SDValue Add = DAG.getNode(ISD::FADD, dl, MVT::v2f64, Shuf, Sub);
6435   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Add,
6436                      DAG.getIntPtrConstant(0));
6437 }
6438
6439 // LowerUINT_TO_FP_i32 - 32-bit unsigned integer to float expansion.
6440 SDValue X86TargetLowering::LowerUINT_TO_FP_i32(SDValue Op,
6441                                                SelectionDAG &DAG) const {
6442   DebugLoc dl = Op.getDebugLoc();
6443   // FP constant to bias correct the final result.
6444   SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL),
6445                                    MVT::f64);
6446
6447   // Load the 32-bit value into an XMM register.
6448   SDValue Load = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
6449                              DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
6450                                          Op.getOperand(0),
6451                                          DAG.getIntPtrConstant(0)));
6452
6453   Load = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
6454                      DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Load),
6455                      DAG.getIntPtrConstant(0));
6456
6457   // Or the load with the bias.
6458   SDValue Or = DAG.getNode(ISD::OR, dl, MVT::v2i64,
6459                            DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
6460                                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
6461                                                    MVT::v2f64, Load)),
6462                            DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
6463                                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
6464                                                    MVT::v2f64, Bias)));
6465   Or = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
6466                    DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Or),
6467                    DAG.getIntPtrConstant(0));
6468
6469   // Subtract the bias.
6470   SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::f64, Or, Bias);
6471
6472   // Handle final rounding.
6473   EVT DestVT = Op.getValueType();
6474
6475   if (DestVT.bitsLT(MVT::f64)) {
6476     return DAG.getNode(ISD::FP_ROUND, dl, DestVT, Sub,
6477                        DAG.getIntPtrConstant(0));
6478   } else if (DestVT.bitsGT(MVT::f64)) {
6479     return DAG.getNode(ISD::FP_EXTEND, dl, DestVT, Sub);
6480   }
6481
6482   // Handle final rounding.
6483   return Sub;
6484 }
6485
6486 SDValue X86TargetLowering::LowerUINT_TO_FP(SDValue Op,
6487                                            SelectionDAG &DAG) const {
6488   SDValue N0 = Op.getOperand(0);
6489   DebugLoc dl = Op.getDebugLoc();
6490
6491   // Since UINT_TO_FP is legal (it's marked custom), dag combiner won't
6492   // optimize it to a SINT_TO_FP when the sign bit is known zero. Perform
6493   // the optimization here.
6494   if (DAG.SignBitIsZero(N0))
6495     return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(), N0);
6496
6497   EVT SrcVT = N0.getValueType();
6498   EVT DstVT = Op.getValueType();
6499   if (SrcVT == MVT::i64 && DstVT == MVT::f64 && X86ScalarSSEf64)
6500     return LowerUINT_TO_FP_i64(Op, DAG);
6501   else if (SrcVT == MVT::i32 && X86ScalarSSEf64)
6502     return LowerUINT_TO_FP_i32(Op, DAG);
6503
6504   // Make a 64-bit buffer, and use it to build an FILD.
6505   SDValue StackSlot = DAG.CreateStackTemporary(MVT::i64);
6506   if (SrcVT == MVT::i32) {
6507     SDValue WordOff = DAG.getConstant(4, getPointerTy());
6508     SDValue OffsetSlot = DAG.getNode(ISD::ADD, dl,
6509                                      getPointerTy(), StackSlot, WordOff);
6510     SDValue Store1 = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
6511                                   StackSlot, MachinePointerInfo(),
6512                                   false, false, 0);
6513     SDValue Store2 = DAG.getStore(Store1, dl, DAG.getConstant(0, MVT::i32),
6514                                   OffsetSlot, MachinePointerInfo(),
6515                                   false, false, 0);
6516     SDValue Fild = BuildFILD(Op, MVT::i64, Store2, StackSlot, DAG);
6517     return Fild;
6518   }
6519
6520   assert(SrcVT == MVT::i64 && "Unexpected type in UINT_TO_FP");
6521   SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
6522                                 StackSlot, MachinePointerInfo(),
6523                                false, false, 0);
6524   // For i64 source, we need to add the appropriate power of 2 if the input
6525   // was negative.  This is the same as the optimization in
6526   // DAGTypeLegalizer::ExpandIntOp_UNIT_TO_FP, and for it to be safe here,
6527   // we must be careful to do the computation in x87 extended precision, not
6528   // in SSE. (The generic code can't know it's OK to do this, or how to.)
6529   int SSFI = cast<FrameIndexSDNode>(StackSlot)->getIndex();
6530   MachineMemOperand *MMO =
6531     DAG.getMachineFunction()
6532     .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
6533                           MachineMemOperand::MOLoad, 8, 8);
6534
6535   SDVTList Tys = DAG.getVTList(MVT::f80, MVT::Other);
6536   SDValue Ops[] = { Store, StackSlot, DAG.getValueType(MVT::i64) };
6537   SDValue Fild = DAG.getMemIntrinsicNode(X86ISD::FILD, dl, Tys, Ops, 3,
6538                                          MVT::i64, MMO);
6539
6540   APInt FF(32, 0x5F800000ULL);
6541
6542   // Check whether the sign bit is set.
6543   SDValue SignSet = DAG.getSetCC(dl, getSetCCResultType(MVT::i64),
6544                                  Op.getOperand(0), DAG.getConstant(0, MVT::i64),
6545                                  ISD::SETLT);
6546
6547   // Build a 64 bit pair (0, FF) in the constant pool, with FF in the lo bits.
6548   SDValue FudgePtr = DAG.getConstantPool(
6549                              ConstantInt::get(*DAG.getContext(), FF.zext(64)),
6550                                          getPointerTy());
6551
6552   // Get a pointer to FF if the sign bit was set, or to 0 otherwise.
6553   SDValue Zero = DAG.getIntPtrConstant(0);
6554   SDValue Four = DAG.getIntPtrConstant(4);
6555   SDValue Offset = DAG.getNode(ISD::SELECT, dl, Zero.getValueType(), SignSet,
6556                                Zero, Four);
6557   FudgePtr = DAG.getNode(ISD::ADD, dl, getPointerTy(), FudgePtr, Offset);
6558
6559   // Load the value out, extending it from f32 to f80.
6560   // FIXME: Avoid the extend by constructing the right constant pool?
6561   SDValue Fudge = DAG.getExtLoad(ISD::EXTLOAD, MVT::f80, dl, DAG.getEntryNode(),
6562                                  FudgePtr, MachinePointerInfo::getConstantPool(),
6563                                  MVT::f32, false, false, 4);
6564   // Extend everything to 80 bits to force it to be done on x87.
6565   SDValue Add = DAG.getNode(ISD::FADD, dl, MVT::f80, Fild, Fudge);
6566   return DAG.getNode(ISD::FP_ROUND, dl, DstVT, Add, DAG.getIntPtrConstant(0));
6567 }
6568
6569 std::pair<SDValue,SDValue> X86TargetLowering::
6570 FP_TO_INTHelper(SDValue Op, SelectionDAG &DAG, bool IsSigned) const {
6571   DebugLoc DL = Op.getDebugLoc();
6572
6573   EVT DstTy = Op.getValueType();
6574
6575   if (!IsSigned) {
6576     assert(DstTy == MVT::i32 && "Unexpected FP_TO_UINT");
6577     DstTy = MVT::i64;
6578   }
6579
6580   assert(DstTy.getSimpleVT() <= MVT::i64 &&
6581          DstTy.getSimpleVT() >= MVT::i16 &&
6582          "Unknown FP_TO_SINT to lower!");
6583
6584   // These are really Legal.
6585   if (DstTy == MVT::i32 &&
6586       isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
6587     return std::make_pair(SDValue(), SDValue());
6588   if (Subtarget->is64Bit() &&
6589       DstTy == MVT::i64 &&
6590       isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
6591     return std::make_pair(SDValue(), SDValue());
6592
6593   // We lower FP->sint64 into FISTP64, followed by a load, all to a temporary
6594   // stack slot.
6595   MachineFunction &MF = DAG.getMachineFunction();
6596   unsigned MemSize = DstTy.getSizeInBits()/8;
6597   int SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
6598   SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
6599
6600
6601
6602   unsigned Opc;
6603   switch (DstTy.getSimpleVT().SimpleTy) {
6604   default: llvm_unreachable("Invalid FP_TO_SINT to lower!");
6605   case MVT::i16: Opc = X86ISD::FP_TO_INT16_IN_MEM; break;
6606   case MVT::i32: Opc = X86ISD::FP_TO_INT32_IN_MEM; break;
6607   case MVT::i64: Opc = X86ISD::FP_TO_INT64_IN_MEM; break;
6608   }
6609
6610   SDValue Chain = DAG.getEntryNode();
6611   SDValue Value = Op.getOperand(0);
6612   EVT TheVT = Op.getOperand(0).getValueType();
6613   if (isScalarFPTypeInSSEReg(TheVT)) {
6614     assert(DstTy == MVT::i64 && "Invalid FP_TO_SINT to lower!");
6615     Chain = DAG.getStore(Chain, DL, Value, StackSlot,
6616                          MachinePointerInfo::getFixedStack(SSFI),
6617                          false, false, 0);
6618     SDVTList Tys = DAG.getVTList(Op.getOperand(0).getValueType(), MVT::Other);
6619     SDValue Ops[] = {
6620       Chain, StackSlot, DAG.getValueType(TheVT)
6621     };
6622
6623     MachineMemOperand *MMO =
6624       MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
6625                               MachineMemOperand::MOLoad, MemSize, MemSize);
6626     Value = DAG.getMemIntrinsicNode(X86ISD::FLD, DL, Tys, Ops, 3,
6627                                     DstTy, MMO);
6628     Chain = Value.getValue(1);
6629     SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
6630     StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
6631   }
6632
6633   MachineMemOperand *MMO =
6634     MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
6635                             MachineMemOperand::MOStore, MemSize, MemSize);
6636
6637   // Build the FP_TO_INT*_IN_MEM
6638   SDValue Ops[] = { Chain, Value, StackSlot };
6639   SDValue FIST = DAG.getMemIntrinsicNode(Opc, DL, DAG.getVTList(MVT::Other),
6640                                          Ops, 3, DstTy, MMO);
6641
6642   return std::make_pair(FIST, StackSlot);
6643 }
6644
6645 SDValue X86TargetLowering::LowerFP_TO_SINT(SDValue Op,
6646                                            SelectionDAG &DAG) const {
6647   if (Op.getValueType().isVector())
6648     return SDValue();
6649
6650   std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG, true);
6651   SDValue FIST = Vals.first, StackSlot = Vals.second;
6652   // If FP_TO_INTHelper failed, the node is actually supposed to be Legal.
6653   if (FIST.getNode() == 0) return Op;
6654
6655   // Load the result.
6656   return DAG.getLoad(Op.getValueType(), Op.getDebugLoc(),
6657                      FIST, StackSlot, MachinePointerInfo(), false, false, 0);
6658 }
6659
6660 SDValue X86TargetLowering::LowerFP_TO_UINT(SDValue Op,
6661                                            SelectionDAG &DAG) const {
6662   std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG, false);
6663   SDValue FIST = Vals.first, StackSlot = Vals.second;
6664   assert(FIST.getNode() && "Unexpected failure");
6665
6666   // Load the result.
6667   return DAG.getLoad(Op.getValueType(), Op.getDebugLoc(),
6668                      FIST, StackSlot, MachinePointerInfo(), false, false, 0);
6669 }
6670
6671 SDValue X86TargetLowering::LowerFABS(SDValue Op,
6672                                      SelectionDAG &DAG) const {
6673   LLVMContext *Context = DAG.getContext();
6674   DebugLoc dl = Op.getDebugLoc();
6675   EVT VT = Op.getValueType();
6676   EVT EltVT = VT;
6677   if (VT.isVector())
6678     EltVT = VT.getVectorElementType();
6679   std::vector<Constant*> CV;
6680   if (EltVT == MVT::f64) {
6681     Constant *C = ConstantFP::get(*Context, APFloat(APInt(64, ~(1ULL << 63))));
6682     CV.push_back(C);
6683     CV.push_back(C);
6684   } else {
6685     Constant *C = ConstantFP::get(*Context, APFloat(APInt(32, ~(1U << 31))));
6686     CV.push_back(C);
6687     CV.push_back(C);
6688     CV.push_back(C);
6689     CV.push_back(C);
6690   }
6691   Constant *C = ConstantVector::get(CV);
6692   SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
6693   SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
6694                              MachinePointerInfo::getConstantPool(),
6695                              false, false, 16);
6696   return DAG.getNode(X86ISD::FAND, dl, VT, Op.getOperand(0), Mask);
6697 }
6698
6699 SDValue X86TargetLowering::LowerFNEG(SDValue Op, SelectionDAG &DAG) const {
6700   LLVMContext *Context = DAG.getContext();
6701   DebugLoc dl = Op.getDebugLoc();
6702   EVT VT = Op.getValueType();
6703   EVT EltVT = VT;
6704   if (VT.isVector())
6705     EltVT = VT.getVectorElementType();
6706   std::vector<Constant*> CV;
6707   if (EltVT == MVT::f64) {
6708     Constant *C = ConstantFP::get(*Context, APFloat(APInt(64, 1ULL << 63)));
6709     CV.push_back(C);
6710     CV.push_back(C);
6711   } else {
6712     Constant *C = ConstantFP::get(*Context, APFloat(APInt(32, 1U << 31)));
6713     CV.push_back(C);
6714     CV.push_back(C);
6715     CV.push_back(C);
6716     CV.push_back(C);
6717   }
6718   Constant *C = ConstantVector::get(CV);
6719   SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
6720   SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
6721                              MachinePointerInfo::getConstantPool(),
6722                              false, false, 16);
6723   if (VT.isVector()) {
6724     return DAG.getNode(ISD::BITCAST, dl, VT,
6725                        DAG.getNode(ISD::XOR, dl, MVT::v2i64,
6726                     DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
6727                                 Op.getOperand(0)),
6728                     DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, Mask)));
6729   } else {
6730     return DAG.getNode(X86ISD::FXOR, dl, VT, Op.getOperand(0), Mask);
6731   }
6732 }
6733
6734 SDValue X86TargetLowering::LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) const {
6735   LLVMContext *Context = DAG.getContext();
6736   SDValue Op0 = Op.getOperand(0);
6737   SDValue Op1 = Op.getOperand(1);
6738   DebugLoc dl = Op.getDebugLoc();
6739   EVT VT = Op.getValueType();
6740   EVT SrcVT = Op1.getValueType();
6741
6742   // If second operand is smaller, extend it first.
6743   if (SrcVT.bitsLT(VT)) {
6744     Op1 = DAG.getNode(ISD::FP_EXTEND, dl, VT, Op1);
6745     SrcVT = VT;
6746   }
6747   // And if it is bigger, shrink it first.
6748   if (SrcVT.bitsGT(VT)) {
6749     Op1 = DAG.getNode(ISD::FP_ROUND, dl, VT, Op1, DAG.getIntPtrConstant(1));
6750     SrcVT = VT;
6751   }
6752
6753   // At this point the operands and the result should have the same
6754   // type, and that won't be f80 since that is not custom lowered.
6755
6756   // First get the sign bit of second operand.
6757   std::vector<Constant*> CV;
6758   if (SrcVT == MVT::f64) {
6759     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, 1ULL << 63))));
6760     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, 0))));
6761   } else {
6762     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 1U << 31))));
6763     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
6764     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
6765     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
6766   }
6767   Constant *C = ConstantVector::get(CV);
6768   SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
6769   SDValue Mask1 = DAG.getLoad(SrcVT, dl, DAG.getEntryNode(), CPIdx,
6770                               MachinePointerInfo::getConstantPool(),
6771                               false, false, 16);
6772   SDValue SignBit = DAG.getNode(X86ISD::FAND, dl, SrcVT, Op1, Mask1);
6773
6774   // Shift sign bit right or left if the two operands have different types.
6775   if (SrcVT.bitsGT(VT)) {
6776     // Op0 is MVT::f32, Op1 is MVT::f64.
6777     SignBit = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f64, SignBit);
6778     SignBit = DAG.getNode(X86ISD::FSRL, dl, MVT::v2f64, SignBit,
6779                           DAG.getConstant(32, MVT::i32));
6780     SignBit = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, SignBit);
6781     SignBit = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f32, SignBit,
6782                           DAG.getIntPtrConstant(0));
6783   }
6784
6785   // Clear first operand sign bit.
6786   CV.clear();
6787   if (VT == MVT::f64) {
6788     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, ~(1ULL << 63)))));
6789     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, 0))));
6790   } else {
6791     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, ~(1U << 31)))));
6792     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
6793     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
6794     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
6795   }
6796   C = ConstantVector::get(CV);
6797   CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
6798   SDValue Mask2 = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
6799                               MachinePointerInfo::getConstantPool(),
6800                               false, false, 16);
6801   SDValue Val = DAG.getNode(X86ISD::FAND, dl, VT, Op0, Mask2);
6802
6803   // Or the value with the sign bit.
6804   return DAG.getNode(X86ISD::FOR, dl, VT, Val, SignBit);
6805 }
6806
6807 /// Emit nodes that will be selected as "test Op0,Op0", or something
6808 /// equivalent.
6809 SDValue X86TargetLowering::EmitTest(SDValue Op, unsigned X86CC,
6810                                     SelectionDAG &DAG) const {
6811   DebugLoc dl = Op.getDebugLoc();
6812
6813   // CF and OF aren't always set the way we want. Determine which
6814   // of these we need.
6815   bool NeedCF = false;
6816   bool NeedOF = false;
6817   switch (X86CC) {
6818   default: break;
6819   case X86::COND_A: case X86::COND_AE:
6820   case X86::COND_B: case X86::COND_BE:
6821     NeedCF = true;
6822     break;
6823   case X86::COND_G: case X86::COND_GE:
6824   case X86::COND_L: case X86::COND_LE:
6825   case X86::COND_O: case X86::COND_NO:
6826     NeedOF = true;
6827     break;
6828   }
6829
6830   // See if we can use the EFLAGS value from the operand instead of
6831   // doing a separate TEST. TEST always sets OF and CF to 0, so unless
6832   // we prove that the arithmetic won't overflow, we can't use OF or CF.
6833   if (Op.getResNo() != 0 || NeedOF || NeedCF)
6834     // Emit a CMP with 0, which is the TEST pattern.
6835     return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
6836                        DAG.getConstant(0, Op.getValueType()));
6837
6838   unsigned Opcode = 0;
6839   unsigned NumOperands = 0;
6840   switch (Op.getNode()->getOpcode()) {
6841   case ISD::ADD:
6842     // Due to an isel shortcoming, be conservative if this add is likely to be
6843     // selected as part of a load-modify-store instruction. When the root node
6844     // in a match is a store, isel doesn't know how to remap non-chain non-flag
6845     // uses of other nodes in the match, such as the ADD in this case. This
6846     // leads to the ADD being left around and reselected, with the result being
6847     // two adds in the output.  Alas, even if none our users are stores, that
6848     // doesn't prove we're O.K.  Ergo, if we have any parents that aren't
6849     // CopyToReg or SETCC, eschew INC/DEC.  A better fix seems to require
6850     // climbing the DAG back to the root, and it doesn't seem to be worth the
6851     // effort.
6852     for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
6853            UE = Op.getNode()->use_end(); UI != UE; ++UI)
6854       if (UI->getOpcode() != ISD::CopyToReg && UI->getOpcode() != ISD::SETCC)
6855         goto default_case;
6856
6857     if (ConstantSDNode *C =
6858         dyn_cast<ConstantSDNode>(Op.getNode()->getOperand(1))) {
6859       // An add of one will be selected as an INC.
6860       if (C->getAPIntValue() == 1) {
6861         Opcode = X86ISD::INC;
6862         NumOperands = 1;
6863         break;
6864       }
6865
6866       // An add of negative one (subtract of one) will be selected as a DEC.
6867       if (C->getAPIntValue().isAllOnesValue()) {
6868         Opcode = X86ISD::DEC;
6869         NumOperands = 1;
6870         break;
6871       }
6872     }
6873
6874     // Otherwise use a regular EFLAGS-setting add.
6875     Opcode = X86ISD::ADD;
6876     NumOperands = 2;
6877     break;
6878   case ISD::AND: {
6879     // If the primary and result isn't used, don't bother using X86ISD::AND,
6880     // because a TEST instruction will be better.
6881     bool NonFlagUse = false;
6882     for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
6883            UE = Op.getNode()->use_end(); UI != UE; ++UI) {
6884       SDNode *User = *UI;
6885       unsigned UOpNo = UI.getOperandNo();
6886       if (User->getOpcode() == ISD::TRUNCATE && User->hasOneUse()) {
6887         // Look pass truncate.
6888         UOpNo = User->use_begin().getOperandNo();
6889         User = *User->use_begin();
6890       }
6891
6892       if (User->getOpcode() != ISD::BRCOND &&
6893           User->getOpcode() != ISD::SETCC &&
6894           (User->getOpcode() != ISD::SELECT || UOpNo != 0)) {
6895         NonFlagUse = true;
6896         break;
6897       }
6898     }
6899
6900     if (!NonFlagUse)
6901       break;
6902   }
6903     // FALL THROUGH
6904   case ISD::SUB:
6905   case ISD::OR:
6906   case ISD::XOR:
6907     // Due to the ISEL shortcoming noted above, be conservative if this op is
6908     // likely to be selected as part of a load-modify-store instruction.
6909     for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
6910            UE = Op.getNode()->use_end(); UI != UE; ++UI)
6911       if (UI->getOpcode() == ISD::STORE)
6912         goto default_case;
6913
6914     // Otherwise use a regular EFLAGS-setting instruction.
6915     switch (Op.getNode()->getOpcode()) {
6916     default: llvm_unreachable("unexpected operator!");
6917     case ISD::SUB: Opcode = X86ISD::SUB; break;
6918     case ISD::OR:  Opcode = X86ISD::OR;  break;
6919     case ISD::XOR: Opcode = X86ISD::XOR; break;
6920     case ISD::AND: Opcode = X86ISD::AND; break;
6921     }
6922
6923     NumOperands = 2;
6924     break;
6925   case X86ISD::ADD:
6926   case X86ISD::SUB:
6927   case X86ISD::INC:
6928   case X86ISD::DEC:
6929   case X86ISD::OR:
6930   case X86ISD::XOR:
6931   case X86ISD::AND:
6932     return SDValue(Op.getNode(), 1);
6933   default:
6934   default_case:
6935     break;
6936   }
6937
6938   if (Opcode == 0)
6939     // Emit a CMP with 0, which is the TEST pattern.
6940     return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
6941                        DAG.getConstant(0, Op.getValueType()));
6942
6943   SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
6944   SmallVector<SDValue, 4> Ops;
6945   for (unsigned i = 0; i != NumOperands; ++i)
6946     Ops.push_back(Op.getOperand(i));
6947
6948   SDValue New = DAG.getNode(Opcode, dl, VTs, &Ops[0], NumOperands);
6949   DAG.ReplaceAllUsesWith(Op, New);
6950   return SDValue(New.getNode(), 1);
6951 }
6952
6953 /// Emit nodes that will be selected as "cmp Op0,Op1", or something
6954 /// equivalent.
6955 SDValue X86TargetLowering::EmitCmp(SDValue Op0, SDValue Op1, unsigned X86CC,
6956                                    SelectionDAG &DAG) const {
6957   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op1))
6958     if (C->getAPIntValue() == 0)
6959       return EmitTest(Op0, X86CC, DAG);
6960
6961   DebugLoc dl = Op0.getDebugLoc();
6962   return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op0, Op1);
6963 }
6964
6965 /// LowerToBT - Result of 'and' is compared against zero. Turn it into a BT node
6966 /// if it's possible.
6967 SDValue X86TargetLowering::LowerToBT(SDValue And, ISD::CondCode CC,
6968                                      DebugLoc dl, SelectionDAG &DAG) const {
6969   SDValue Op0 = And.getOperand(0);
6970   SDValue Op1 = And.getOperand(1);
6971   if (Op0.getOpcode() == ISD::TRUNCATE)
6972     Op0 = Op0.getOperand(0);
6973   if (Op1.getOpcode() == ISD::TRUNCATE)
6974     Op1 = Op1.getOperand(0);
6975
6976   SDValue LHS, RHS;
6977   if (Op1.getOpcode() == ISD::SHL)
6978     std::swap(Op0, Op1);
6979   if (Op0.getOpcode() == ISD::SHL) {
6980     if (ConstantSDNode *And00C = dyn_cast<ConstantSDNode>(Op0.getOperand(0)))
6981       if (And00C->getZExtValue() == 1) {
6982         // If we looked past a truncate, check that it's only truncating away
6983         // known zeros.
6984         unsigned BitWidth = Op0.getValueSizeInBits();
6985         unsigned AndBitWidth = And.getValueSizeInBits();
6986         if (BitWidth > AndBitWidth) {
6987           APInt Mask = APInt::getAllOnesValue(BitWidth), Zeros, Ones;
6988           DAG.ComputeMaskedBits(Op0, Mask, Zeros, Ones);
6989           if (Zeros.countLeadingOnes() < BitWidth - AndBitWidth)
6990             return SDValue();
6991         }
6992         LHS = Op1;
6993         RHS = Op0.getOperand(1);
6994       }
6995   } else if (Op1.getOpcode() == ISD::Constant) {
6996     ConstantSDNode *AndRHS = cast<ConstantSDNode>(Op1);
6997     SDValue AndLHS = Op0;
6998     if (AndRHS->getZExtValue() == 1 && AndLHS.getOpcode() == ISD::SRL) {
6999       LHS = AndLHS.getOperand(0);
7000       RHS = AndLHS.getOperand(1);
7001     }
7002   }
7003
7004   if (LHS.getNode()) {
7005     // If LHS is i8, promote it to i32 with any_extend.  There is no i8 BT
7006     // instruction.  Since the shift amount is in-range-or-undefined, we know
7007     // that doing a bittest on the i32 value is ok.  We extend to i32 because
7008     // the encoding for the i16 version is larger than the i32 version.
7009     // Also promote i16 to i32 for performance / code size reason.
7010     if (LHS.getValueType() == MVT::i8 ||
7011         LHS.getValueType() == MVT::i16)
7012       LHS = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, LHS);
7013
7014     // If the operand types disagree, extend the shift amount to match.  Since
7015     // BT ignores high bits (like shifts) we can use anyextend.
7016     if (LHS.getValueType() != RHS.getValueType())
7017       RHS = DAG.getNode(ISD::ANY_EXTEND, dl, LHS.getValueType(), RHS);
7018
7019     SDValue BT = DAG.getNode(X86ISD::BT, dl, MVT::i32, LHS, RHS);
7020     unsigned Cond = CC == ISD::SETEQ ? X86::COND_AE : X86::COND_B;
7021     return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
7022                        DAG.getConstant(Cond, MVT::i8), BT);
7023   }
7024
7025   return SDValue();
7026 }
7027
7028 SDValue X86TargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
7029   assert(Op.getValueType() == MVT::i8 && "SetCC type must be 8-bit integer");
7030   SDValue Op0 = Op.getOperand(0);
7031   SDValue Op1 = Op.getOperand(1);
7032   DebugLoc dl = Op.getDebugLoc();
7033   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
7034
7035   // Optimize to BT if possible.
7036   // Lower (X & (1 << N)) == 0 to BT(X, N).
7037   // Lower ((X >>u N) & 1) != 0 to BT(X, N).
7038   // Lower ((X >>s N) & 1) != 0 to BT(X, N).
7039   if (Op0.getOpcode() == ISD::AND &&
7040       Op0.hasOneUse() &&
7041       Op1.getOpcode() == ISD::Constant &&
7042       cast<ConstantSDNode>(Op1)->isNullValue() &&
7043       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
7044     SDValue NewSetCC = LowerToBT(Op0, CC, dl, DAG);
7045     if (NewSetCC.getNode())
7046       return NewSetCC;
7047   }
7048
7049   // Look for "(setcc) == / != 1" to avoid unnecessary setcc.
7050   if (Op0.getOpcode() == X86ISD::SETCC &&
7051       Op1.getOpcode() == ISD::Constant &&
7052       (cast<ConstantSDNode>(Op1)->getZExtValue() == 1 ||
7053        cast<ConstantSDNode>(Op1)->isNullValue()) &&
7054       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
7055     X86::CondCode CCode = (X86::CondCode)Op0.getConstantOperandVal(0);
7056     bool Invert = (CC == ISD::SETNE) ^
7057       cast<ConstantSDNode>(Op1)->isNullValue();
7058     if (Invert)
7059       CCode = X86::GetOppositeBranchCondition(CCode);
7060     return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
7061                        DAG.getConstant(CCode, MVT::i8), Op0.getOperand(1));
7062   }
7063
7064   bool isFP = Op1.getValueType().isFloatingPoint();
7065   unsigned X86CC = TranslateX86CC(CC, isFP, Op0, Op1, DAG);
7066   if (X86CC == X86::COND_INVALID)
7067     return SDValue();
7068
7069   SDValue Cond = EmitCmp(Op0, Op1, X86CC, DAG);
7070
7071   // Use sbb x, x to materialize carry bit into a GPR.
7072   if (X86CC == X86::COND_B)
7073     return DAG.getNode(ISD::AND, dl, MVT::i8,
7074                        DAG.getNode(X86ISD::SETCC_CARRY, dl, MVT::i8,
7075                                    DAG.getConstant(X86CC, MVT::i8), Cond),
7076                        DAG.getConstant(1, MVT::i8));
7077
7078   return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
7079                      DAG.getConstant(X86CC, MVT::i8), Cond);
7080 }
7081
7082 SDValue X86TargetLowering::LowerVSETCC(SDValue Op, SelectionDAG &DAG) const {
7083   SDValue Cond;
7084   SDValue Op0 = Op.getOperand(0);
7085   SDValue Op1 = Op.getOperand(1);
7086   SDValue CC = Op.getOperand(2);
7087   EVT VT = Op.getValueType();
7088   ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
7089   bool isFP = Op.getOperand(1).getValueType().isFloatingPoint();
7090   DebugLoc dl = Op.getDebugLoc();
7091
7092   if (isFP) {
7093     unsigned SSECC = 8;
7094     EVT VT0 = Op0.getValueType();
7095     assert(VT0 == MVT::v4f32 || VT0 == MVT::v2f64);
7096     unsigned Opc = VT0 == MVT::v4f32 ? X86ISD::CMPPS : X86ISD::CMPPD;
7097     bool Swap = false;
7098
7099     switch (SetCCOpcode) {
7100     default: break;
7101     case ISD::SETOEQ:
7102     case ISD::SETEQ:  SSECC = 0; break;
7103     case ISD::SETOGT:
7104     case ISD::SETGT: Swap = true; // Fallthrough
7105     case ISD::SETLT:
7106     case ISD::SETOLT: SSECC = 1; break;
7107     case ISD::SETOGE:
7108     case ISD::SETGE: Swap = true; // Fallthrough
7109     case ISD::SETLE:
7110     case ISD::SETOLE: SSECC = 2; break;
7111     case ISD::SETUO:  SSECC = 3; break;
7112     case ISD::SETUNE:
7113     case ISD::SETNE:  SSECC = 4; break;
7114     case ISD::SETULE: Swap = true;
7115     case ISD::SETUGE: SSECC = 5; break;
7116     case ISD::SETULT: Swap = true;
7117     case ISD::SETUGT: SSECC = 6; break;
7118     case ISD::SETO:   SSECC = 7; break;
7119     }
7120     if (Swap)
7121       std::swap(Op0, Op1);
7122
7123     // In the two special cases we can't handle, emit two comparisons.
7124     if (SSECC == 8) {
7125       if (SetCCOpcode == ISD::SETUEQ) {
7126         SDValue UNORD, EQ;
7127         UNORD = DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(3, MVT::i8));
7128         EQ = DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(0, MVT::i8));
7129         return DAG.getNode(ISD::OR, dl, VT, UNORD, EQ);
7130       }
7131       else if (SetCCOpcode == ISD::SETONE) {
7132         SDValue ORD, NEQ;
7133         ORD = DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(7, MVT::i8));
7134         NEQ = DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(4, MVT::i8));
7135         return DAG.getNode(ISD::AND, dl, VT, ORD, NEQ);
7136       }
7137       llvm_unreachable("Illegal FP comparison");
7138     }
7139     // Handle all other FP comparisons here.
7140     return DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(SSECC, MVT::i8));
7141   }
7142
7143   // We are handling one of the integer comparisons here.  Since SSE only has
7144   // GT and EQ comparisons for integer, swapping operands and multiple
7145   // operations may be required for some comparisons.
7146   unsigned Opc = 0, EQOpc = 0, GTOpc = 0;
7147   bool Swap = false, Invert = false, FlipSigns = false;
7148
7149   switch (VT.getSimpleVT().SimpleTy) {
7150   default: break;
7151   case MVT::v16i8: EQOpc = X86ISD::PCMPEQB; GTOpc = X86ISD::PCMPGTB; break;
7152   case MVT::v8i16: EQOpc = X86ISD::PCMPEQW; GTOpc = X86ISD::PCMPGTW; break;
7153   case MVT::v4i32: EQOpc = X86ISD::PCMPEQD; GTOpc = X86ISD::PCMPGTD; break;
7154   case MVT::v2i64: EQOpc = X86ISD::PCMPEQQ; GTOpc = X86ISD::PCMPGTQ; break;
7155   }
7156
7157   switch (SetCCOpcode) {
7158   default: break;
7159   case ISD::SETNE:  Invert = true;
7160   case ISD::SETEQ:  Opc = EQOpc; break;
7161   case ISD::SETLT:  Swap = true;
7162   case ISD::SETGT:  Opc = GTOpc; break;
7163   case ISD::SETGE:  Swap = true;
7164   case ISD::SETLE:  Opc = GTOpc; Invert = true; break;
7165   case ISD::SETULT: Swap = true;
7166   case ISD::SETUGT: Opc = GTOpc; FlipSigns = true; break;
7167   case ISD::SETUGE: Swap = true;
7168   case ISD::SETULE: Opc = GTOpc; FlipSigns = true; Invert = true; break;
7169   }
7170   if (Swap)
7171     std::swap(Op0, Op1);
7172
7173   // Since SSE has no unsigned integer comparisons, we need to flip  the sign
7174   // bits of the inputs before performing those operations.
7175   if (FlipSigns) {
7176     EVT EltVT = VT.getVectorElementType();
7177     SDValue SignBit = DAG.getConstant(APInt::getSignBit(EltVT.getSizeInBits()),
7178                                       EltVT);
7179     std::vector<SDValue> SignBits(VT.getVectorNumElements(), SignBit);
7180     SDValue SignVec = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &SignBits[0],
7181                                     SignBits.size());
7182     Op0 = DAG.getNode(ISD::XOR, dl, VT, Op0, SignVec);
7183     Op1 = DAG.getNode(ISD::XOR, dl, VT, Op1, SignVec);
7184   }
7185
7186   SDValue Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
7187
7188   // If the logical-not of the result is required, perform that now.
7189   if (Invert)
7190     Result = DAG.getNOT(dl, Result, VT);
7191
7192   return Result;
7193 }
7194
7195 // isX86LogicalCmp - Return true if opcode is a X86 logical comparison.
7196 static bool isX86LogicalCmp(SDValue Op) {
7197   unsigned Opc = Op.getNode()->getOpcode();
7198   if (Opc == X86ISD::CMP || Opc == X86ISD::COMI || Opc == X86ISD::UCOMI)
7199     return true;
7200   if (Op.getResNo() == 1 &&
7201       (Opc == X86ISD::ADD ||
7202        Opc == X86ISD::SUB ||
7203        Opc == X86ISD::SMUL ||
7204        Opc == X86ISD::UMUL ||
7205        Opc == X86ISD::INC ||
7206        Opc == X86ISD::DEC ||
7207        Opc == X86ISD::OR ||
7208        Opc == X86ISD::XOR ||
7209        Opc == X86ISD::AND))
7210     return true;
7211
7212   if (Op.getResNo() == 2 && Opc == X86ISD::UMUL)
7213     return true;
7214     
7215   return false;
7216 }
7217
7218 static bool isZero(SDValue V) {
7219   ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
7220   return C && C->isNullValue();
7221 }
7222
7223 static bool isAllOnes(SDValue V) {
7224   ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
7225   return C && C->isAllOnesValue();
7226 }
7227
7228 SDValue X86TargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
7229   bool addTest = true;
7230   SDValue Cond  = Op.getOperand(0);
7231   SDValue Op1 = Op.getOperand(1);
7232   SDValue Op2 = Op.getOperand(2);
7233   DebugLoc DL = Op.getDebugLoc();
7234   SDValue CC;
7235
7236   if (Cond.getOpcode() == ISD::SETCC) {
7237     SDValue NewCond = LowerSETCC(Cond, DAG);
7238     if (NewCond.getNode())
7239       Cond = NewCond;
7240   }
7241
7242   // (select (x == 0), -1, y) -> (sign_bit (x - 1)) | y
7243   // (select (x == 0), y, -1) -> ~(sign_bit (x - 1)) | y
7244   // (select (x != 0), y, -1) -> (sign_bit (x - 1)) | y
7245   // (select (x != 0), -1, y) -> ~(sign_bit (x - 1)) | y
7246   if (Cond.getOpcode() == X86ISD::SETCC &&
7247       Cond.getOperand(1).getOpcode() == X86ISD::CMP &&
7248       isZero(Cond.getOperand(1).getOperand(1))) {
7249     SDValue Cmp = Cond.getOperand(1);
7250     
7251     unsigned CondCode =cast<ConstantSDNode>(Cond.getOperand(0))->getZExtValue();
7252     
7253     if ((isAllOnes(Op1) || isAllOnes(Op2)) && 
7254         (CondCode == X86::COND_E || CondCode == X86::COND_NE)) {
7255       SDValue Y = isAllOnes(Op2) ? Op1 : Op2;
7256
7257       SDValue CmpOp0 = Cmp.getOperand(0);
7258       Cmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32,
7259                         CmpOp0, DAG.getConstant(1, CmpOp0.getValueType()));
7260       
7261       SDValue Res =   // Res = 0 or -1.
7262         DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
7263                     DAG.getConstant(X86::COND_B, MVT::i8), Cmp);
7264       
7265       if (isAllOnes(Op1) != (CondCode == X86::COND_E))
7266         Res = DAG.getNOT(DL, Res, Res.getValueType());
7267       
7268       ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(Op2);
7269       if (N2C == 0 || !N2C->isNullValue())
7270         Res = DAG.getNode(ISD::OR, DL, Res.getValueType(), Res, Y);
7271       return Res;
7272     }
7273   }
7274
7275   // Look past (and (setcc_carry (cmp ...)), 1).
7276   if (Cond.getOpcode() == ISD::AND &&
7277       Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
7278     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
7279     if (C && C->getAPIntValue() == 1)
7280       Cond = Cond.getOperand(0);
7281   }
7282
7283   // If condition flag is set by a X86ISD::CMP, then use it as the condition
7284   // setting operand in place of the X86ISD::SETCC.
7285   if (Cond.getOpcode() == X86ISD::SETCC ||
7286       Cond.getOpcode() == X86ISD::SETCC_CARRY) {
7287     CC = Cond.getOperand(0);
7288
7289     SDValue Cmp = Cond.getOperand(1);
7290     unsigned Opc = Cmp.getOpcode();
7291     EVT VT = Op.getValueType();
7292
7293     bool IllegalFPCMov = false;
7294     if (VT.isFloatingPoint() && !VT.isVector() &&
7295         !isScalarFPTypeInSSEReg(VT))  // FPStack?
7296       IllegalFPCMov = !hasFPCMov(cast<ConstantSDNode>(CC)->getSExtValue());
7297
7298     if ((isX86LogicalCmp(Cmp) && !IllegalFPCMov) ||
7299         Opc == X86ISD::BT) { // FIXME
7300       Cond = Cmp;
7301       addTest = false;
7302     }
7303   }
7304
7305   if (addTest) {
7306     // Look pass the truncate.
7307     if (Cond.getOpcode() == ISD::TRUNCATE)
7308       Cond = Cond.getOperand(0);
7309
7310     // We know the result of AND is compared against zero. Try to match
7311     // it to BT.
7312     if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
7313       SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, DL, DAG);
7314       if (NewSetCC.getNode()) {
7315         CC = NewSetCC.getOperand(0);
7316         Cond = NewSetCC.getOperand(1);
7317         addTest = false;
7318       }
7319     }
7320   }
7321
7322   if (addTest) {
7323     CC = DAG.getConstant(X86::COND_NE, MVT::i8);
7324     Cond = EmitTest(Cond, X86::COND_NE, DAG);
7325   }
7326
7327   // X86ISD::CMOV means set the result (which is operand 1) to the RHS if
7328   // condition is true.
7329   SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::Flag);
7330   SDValue Ops[] = { Op2, Op1, CC, Cond };
7331   return DAG.getNode(X86ISD::CMOV, DL, VTs, Ops, array_lengthof(Ops));
7332 }
7333
7334 // isAndOrOfSingleUseSetCCs - Return true if node is an ISD::AND or
7335 // ISD::OR of two X86ISD::SETCC nodes each of which has no other use apart
7336 // from the AND / OR.
7337 static bool isAndOrOfSetCCs(SDValue Op, unsigned &Opc) {
7338   Opc = Op.getOpcode();
7339   if (Opc != ISD::OR && Opc != ISD::AND)
7340     return false;
7341   return (Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
7342           Op.getOperand(0).hasOneUse() &&
7343           Op.getOperand(1).getOpcode() == X86ISD::SETCC &&
7344           Op.getOperand(1).hasOneUse());
7345 }
7346
7347 // isXor1OfSetCC - Return true if node is an ISD::XOR of a X86ISD::SETCC and
7348 // 1 and that the SETCC node has a single use.
7349 static bool isXor1OfSetCC(SDValue Op) {
7350   if (Op.getOpcode() != ISD::XOR)
7351     return false;
7352   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
7353   if (N1C && N1C->getAPIntValue() == 1) {
7354     return Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
7355       Op.getOperand(0).hasOneUse();
7356   }
7357   return false;
7358 }
7359
7360 SDValue X86TargetLowering::LowerBRCOND(SDValue Op, SelectionDAG &DAG) const {
7361   bool addTest = true;
7362   SDValue Chain = Op.getOperand(0);
7363   SDValue Cond  = Op.getOperand(1);
7364   SDValue Dest  = Op.getOperand(2);
7365   DebugLoc dl = Op.getDebugLoc();
7366   SDValue CC;
7367
7368   if (Cond.getOpcode() == ISD::SETCC) {
7369     SDValue NewCond = LowerSETCC(Cond, DAG);
7370     if (NewCond.getNode())
7371       Cond = NewCond;
7372   }
7373 #if 0
7374   // FIXME: LowerXALUO doesn't handle these!!
7375   else if (Cond.getOpcode() == X86ISD::ADD  ||
7376            Cond.getOpcode() == X86ISD::SUB  ||
7377            Cond.getOpcode() == X86ISD::SMUL ||
7378            Cond.getOpcode() == X86ISD::UMUL)
7379     Cond = LowerXALUO(Cond, DAG);
7380 #endif
7381
7382   // Look pass (and (setcc_carry (cmp ...)), 1).
7383   if (Cond.getOpcode() == ISD::AND &&
7384       Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
7385     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
7386     if (C && C->getAPIntValue() == 1)
7387       Cond = Cond.getOperand(0);
7388   }
7389
7390   // If condition flag is set by a X86ISD::CMP, then use it as the condition
7391   // setting operand in place of the X86ISD::SETCC.
7392   if (Cond.getOpcode() == X86ISD::SETCC ||
7393       Cond.getOpcode() == X86ISD::SETCC_CARRY) {
7394     CC = Cond.getOperand(0);
7395
7396     SDValue Cmp = Cond.getOperand(1);
7397     unsigned Opc = Cmp.getOpcode();
7398     // FIXME: WHY THE SPECIAL CASING OF LogicalCmp??
7399     if (isX86LogicalCmp(Cmp) || Opc == X86ISD::BT) {
7400       Cond = Cmp;
7401       addTest = false;
7402     } else {
7403       switch (cast<ConstantSDNode>(CC)->getZExtValue()) {
7404       default: break;
7405       case X86::COND_O:
7406       case X86::COND_B:
7407         // These can only come from an arithmetic instruction with overflow,
7408         // e.g. SADDO, UADDO.
7409         Cond = Cond.getNode()->getOperand(1);
7410         addTest = false;
7411         break;
7412       }
7413     }
7414   } else {
7415     unsigned CondOpc;
7416     if (Cond.hasOneUse() && isAndOrOfSetCCs(Cond, CondOpc)) {
7417       SDValue Cmp = Cond.getOperand(0).getOperand(1);
7418       if (CondOpc == ISD::OR) {
7419         // Also, recognize the pattern generated by an FCMP_UNE. We can emit
7420         // two branches instead of an explicit OR instruction with a
7421         // separate test.
7422         if (Cmp == Cond.getOperand(1).getOperand(1) &&
7423             isX86LogicalCmp(Cmp)) {
7424           CC = Cond.getOperand(0).getOperand(0);
7425           Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
7426                               Chain, Dest, CC, Cmp);
7427           CC = Cond.getOperand(1).getOperand(0);
7428           Cond = Cmp;
7429           addTest = false;
7430         }
7431       } else { // ISD::AND
7432         // Also, recognize the pattern generated by an FCMP_OEQ. We can emit
7433         // two branches instead of an explicit AND instruction with a
7434         // separate test. However, we only do this if this block doesn't
7435         // have a fall-through edge, because this requires an explicit
7436         // jmp when the condition is false.
7437         if (Cmp == Cond.getOperand(1).getOperand(1) &&
7438             isX86LogicalCmp(Cmp) &&
7439             Op.getNode()->hasOneUse()) {
7440           X86::CondCode CCode =
7441             (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
7442           CCode = X86::GetOppositeBranchCondition(CCode);
7443           CC = DAG.getConstant(CCode, MVT::i8);
7444           SDNode *User = *Op.getNode()->use_begin();
7445           // Look for an unconditional branch following this conditional branch.
7446           // We need this because we need to reverse the successors in order
7447           // to implement FCMP_OEQ.
7448           if (User->getOpcode() == ISD::BR) {
7449             SDValue FalseBB = User->getOperand(1);
7450             SDNode *NewBR =
7451               DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
7452             assert(NewBR == User);
7453             (void)NewBR;
7454             Dest = FalseBB;
7455
7456             Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
7457                                 Chain, Dest, CC, Cmp);
7458             X86::CondCode CCode =
7459               (X86::CondCode)Cond.getOperand(1).getConstantOperandVal(0);
7460             CCode = X86::GetOppositeBranchCondition(CCode);
7461             CC = DAG.getConstant(CCode, MVT::i8);
7462             Cond = Cmp;
7463             addTest = false;
7464           }
7465         }
7466       }
7467     } else if (Cond.hasOneUse() && isXor1OfSetCC(Cond)) {
7468       // Recognize for xorb (setcc), 1 patterns. The xor inverts the condition.
7469       // It should be transformed during dag combiner except when the condition
7470       // is set by a arithmetics with overflow node.
7471       X86::CondCode CCode =
7472         (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
7473       CCode = X86::GetOppositeBranchCondition(CCode);
7474       CC = DAG.getConstant(CCode, MVT::i8);
7475       Cond = Cond.getOperand(0).getOperand(1);
7476       addTest = false;
7477     }
7478   }
7479
7480   if (addTest) {
7481     // Look pass the truncate.
7482     if (Cond.getOpcode() == ISD::TRUNCATE)
7483       Cond = Cond.getOperand(0);
7484
7485     // We know the result of AND is compared against zero. Try to match
7486     // it to BT.
7487     if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
7488       SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, dl, DAG);
7489       if (NewSetCC.getNode()) {
7490         CC = NewSetCC.getOperand(0);
7491         Cond = NewSetCC.getOperand(1);
7492         addTest = false;
7493       }
7494     }
7495   }
7496
7497   if (addTest) {
7498     CC = DAG.getConstant(X86::COND_NE, MVT::i8);
7499     Cond = EmitTest(Cond, X86::COND_NE, DAG);
7500   }
7501   return DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
7502                      Chain, Dest, CC, Cond);
7503 }
7504
7505
7506 // Lower dynamic stack allocation to _alloca call for Cygwin/Mingw targets.
7507 // Calls to _alloca is needed to probe the stack when allocating more than 4k
7508 // bytes in one go. Touching the stack at 4K increments is necessary to ensure
7509 // that the guard pages used by the OS virtual memory manager are allocated in
7510 // correct sequence.
7511 SDValue
7512 X86TargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
7513                                            SelectionDAG &DAG) const {
7514   assert((Subtarget->isTargetCygMing() || Subtarget->isTargetWindows()) &&
7515          "This should be used only on Windows targets");
7516   DebugLoc dl = Op.getDebugLoc();
7517
7518   // Get the inputs.
7519   SDValue Chain = Op.getOperand(0);
7520   SDValue Size  = Op.getOperand(1);
7521   // FIXME: Ensure alignment here
7522
7523   SDValue Flag;
7524
7525   EVT SPTy = Subtarget->is64Bit() ? MVT::i64 : MVT::i32;
7526
7527   Chain = DAG.getCopyToReg(Chain, dl, X86::EAX, Size, Flag);
7528   Flag = Chain.getValue(1);
7529
7530   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Flag);
7531
7532   Chain = DAG.getNode(X86ISD::WIN_ALLOCA, dl, NodeTys, Chain, Flag);
7533   Flag = Chain.getValue(1);
7534
7535   Chain = DAG.getCopyFromReg(Chain, dl, X86StackPtr, SPTy).getValue(1);
7536
7537   SDValue Ops1[2] = { Chain.getValue(0), Chain };
7538   return DAG.getMergeValues(Ops1, 2, dl);
7539 }
7540
7541 SDValue X86TargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) const {
7542   MachineFunction &MF = DAG.getMachineFunction();
7543   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
7544
7545   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
7546   DebugLoc DL = Op.getDebugLoc();
7547
7548   if (!Subtarget->is64Bit() || Subtarget->isTargetWin64()) {
7549     // vastart just stores the address of the VarArgsFrameIndex slot into the
7550     // memory location argument.
7551     SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
7552                                    getPointerTy());
7553     return DAG.getStore(Op.getOperand(0), DL, FR, Op.getOperand(1),
7554                         MachinePointerInfo(SV), false, false, 0);
7555   }
7556
7557   // __va_list_tag:
7558   //   gp_offset         (0 - 6 * 8)
7559   //   fp_offset         (48 - 48 + 8 * 16)
7560   //   overflow_arg_area (point to parameters coming in memory).
7561   //   reg_save_area
7562   SmallVector<SDValue, 8> MemOps;
7563   SDValue FIN = Op.getOperand(1);
7564   // Store gp_offset
7565   SDValue Store = DAG.getStore(Op.getOperand(0), DL,
7566                                DAG.getConstant(FuncInfo->getVarArgsGPOffset(),
7567                                                MVT::i32),
7568                                FIN, MachinePointerInfo(SV), false, false, 0);
7569   MemOps.push_back(Store);
7570
7571   // Store fp_offset
7572   FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
7573                     FIN, DAG.getIntPtrConstant(4));
7574   Store = DAG.getStore(Op.getOperand(0), DL,
7575                        DAG.getConstant(FuncInfo->getVarArgsFPOffset(),
7576                                        MVT::i32),
7577                        FIN, MachinePointerInfo(SV, 4), false, false, 0);
7578   MemOps.push_back(Store);
7579
7580   // Store ptr to overflow_arg_area
7581   FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
7582                     FIN, DAG.getIntPtrConstant(4));
7583   SDValue OVFIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
7584                                     getPointerTy());
7585   Store = DAG.getStore(Op.getOperand(0), DL, OVFIN, FIN,
7586                        MachinePointerInfo(SV, 8),
7587                        false, false, 0);
7588   MemOps.push_back(Store);
7589
7590   // Store ptr to reg_save_area.
7591   FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
7592                     FIN, DAG.getIntPtrConstant(8));
7593   SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
7594                                     getPointerTy());
7595   Store = DAG.getStore(Op.getOperand(0), DL, RSFIN, FIN,
7596                        MachinePointerInfo(SV, 16), false, false, 0);
7597   MemOps.push_back(Store);
7598   return DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
7599                      &MemOps[0], MemOps.size());
7600 }
7601
7602 SDValue X86TargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) const {
7603   assert(Subtarget->is64Bit() &&
7604          "LowerVAARG only handles 64-bit va_arg!");
7605   assert((Subtarget->isTargetLinux() ||
7606           Subtarget->isTargetDarwin()) &&
7607           "Unhandled target in LowerVAARG");
7608   assert(Op.getNode()->getNumOperands() == 4);
7609   SDValue Chain = Op.getOperand(0);
7610   SDValue SrcPtr = Op.getOperand(1);
7611   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
7612   unsigned Align = Op.getConstantOperandVal(3);
7613   DebugLoc dl = Op.getDebugLoc();
7614
7615   EVT ArgVT = Op.getNode()->getValueType(0);
7616   const Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
7617   uint32_t ArgSize = getTargetData()->getTypeAllocSize(ArgTy);
7618   uint8_t ArgMode;
7619
7620   // Decide which area this value should be read from.
7621   // TODO: Implement the AMD64 ABI in its entirety. This simple
7622   // selection mechanism works only for the basic types.
7623   if (ArgVT == MVT::f80) {
7624     llvm_unreachable("va_arg for f80 not yet implemented");
7625   } else if (ArgVT.isFloatingPoint() && ArgSize <= 16 /*bytes*/) {
7626     ArgMode = 2;  // Argument passed in XMM register. Use fp_offset.
7627   } else if (ArgVT.isInteger() && ArgSize <= 32 /*bytes*/) {
7628     ArgMode = 1;  // Argument passed in GPR64 register(s). Use gp_offset.
7629   } else {
7630     llvm_unreachable("Unhandled argument type in LowerVAARG");
7631   }
7632
7633   if (ArgMode == 2) {
7634     // Sanity Check: Make sure using fp_offset makes sense.
7635     assert(!UseSoftFloat &&
7636            !(DAG.getMachineFunction()
7637                 .getFunction()->hasFnAttr(Attribute::NoImplicitFloat)) &&
7638            Subtarget->hasXMM());
7639   }
7640
7641   // Insert VAARG_64 node into the DAG
7642   // VAARG_64 returns two values: Variable Argument Address, Chain
7643   SmallVector<SDValue, 11> InstOps;
7644   InstOps.push_back(Chain);
7645   InstOps.push_back(SrcPtr);
7646   InstOps.push_back(DAG.getConstant(ArgSize, MVT::i32));
7647   InstOps.push_back(DAG.getConstant(ArgMode, MVT::i8));
7648   InstOps.push_back(DAG.getConstant(Align, MVT::i32));
7649   SDVTList VTs = DAG.getVTList(getPointerTy(), MVT::Other);
7650   SDValue VAARG = DAG.getMemIntrinsicNode(X86ISD::VAARG_64, dl,
7651                                           VTs, &InstOps[0], InstOps.size(),
7652                                           MVT::i64,
7653                                           MachinePointerInfo(SV),
7654                                           /*Align=*/0,
7655                                           /*Volatile=*/false,
7656                                           /*ReadMem=*/true,
7657                                           /*WriteMem=*/true);
7658   Chain = VAARG.getValue(1);
7659
7660   // Load the next argument and return it
7661   return DAG.getLoad(ArgVT, dl,
7662                      Chain,
7663                      VAARG,
7664                      MachinePointerInfo(),
7665                      false, false, 0);
7666 }
7667
7668 SDValue X86TargetLowering::LowerVACOPY(SDValue Op, SelectionDAG &DAG) const {
7669   // X86-64 va_list is a struct { i32, i32, i8*, i8* }.
7670   assert(Subtarget->is64Bit() && "This code only handles 64-bit va_copy!");
7671   SDValue Chain = Op.getOperand(0);
7672   SDValue DstPtr = Op.getOperand(1);
7673   SDValue SrcPtr = Op.getOperand(2);
7674   const Value *DstSV = cast<SrcValueSDNode>(Op.getOperand(3))->getValue();
7675   const Value *SrcSV = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
7676   DebugLoc DL = Op.getDebugLoc();
7677
7678   return DAG.getMemcpy(Chain, DL, DstPtr, SrcPtr,
7679                        DAG.getIntPtrConstant(24), 8, /*isVolatile*/false,
7680                        false,
7681                        MachinePointerInfo(DstSV), MachinePointerInfo(SrcSV));
7682 }
7683
7684 SDValue
7685 X86TargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op, SelectionDAG &DAG) const {
7686   DebugLoc dl = Op.getDebugLoc();
7687   unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
7688   switch (IntNo) {
7689   default: return SDValue();    // Don't custom lower most intrinsics.
7690   // Comparison intrinsics.
7691   case Intrinsic::x86_sse_comieq_ss:
7692   case Intrinsic::x86_sse_comilt_ss:
7693   case Intrinsic::x86_sse_comile_ss:
7694   case Intrinsic::x86_sse_comigt_ss:
7695   case Intrinsic::x86_sse_comige_ss:
7696   case Intrinsic::x86_sse_comineq_ss:
7697   case Intrinsic::x86_sse_ucomieq_ss:
7698   case Intrinsic::x86_sse_ucomilt_ss:
7699   case Intrinsic::x86_sse_ucomile_ss:
7700   case Intrinsic::x86_sse_ucomigt_ss:
7701   case Intrinsic::x86_sse_ucomige_ss:
7702   case Intrinsic::x86_sse_ucomineq_ss:
7703   case Intrinsic::x86_sse2_comieq_sd:
7704   case Intrinsic::x86_sse2_comilt_sd:
7705   case Intrinsic::x86_sse2_comile_sd:
7706   case Intrinsic::x86_sse2_comigt_sd:
7707   case Intrinsic::x86_sse2_comige_sd:
7708   case Intrinsic::x86_sse2_comineq_sd:
7709   case Intrinsic::x86_sse2_ucomieq_sd:
7710   case Intrinsic::x86_sse2_ucomilt_sd:
7711   case Intrinsic::x86_sse2_ucomile_sd:
7712   case Intrinsic::x86_sse2_ucomigt_sd:
7713   case Intrinsic::x86_sse2_ucomige_sd:
7714   case Intrinsic::x86_sse2_ucomineq_sd: {
7715     unsigned Opc = 0;
7716     ISD::CondCode CC = ISD::SETCC_INVALID;
7717     switch (IntNo) {
7718     default: break;
7719     case Intrinsic::x86_sse_comieq_ss:
7720     case Intrinsic::x86_sse2_comieq_sd:
7721       Opc = X86ISD::COMI;
7722       CC = ISD::SETEQ;
7723       break;
7724     case Intrinsic::x86_sse_comilt_ss:
7725     case Intrinsic::x86_sse2_comilt_sd:
7726       Opc = X86ISD::COMI;
7727       CC = ISD::SETLT;
7728       break;
7729     case Intrinsic::x86_sse_comile_ss:
7730     case Intrinsic::x86_sse2_comile_sd:
7731       Opc = X86ISD::COMI;
7732       CC = ISD::SETLE;
7733       break;
7734     case Intrinsic::x86_sse_comigt_ss:
7735     case Intrinsic::x86_sse2_comigt_sd:
7736       Opc = X86ISD::COMI;
7737       CC = ISD::SETGT;
7738       break;
7739     case Intrinsic::x86_sse_comige_ss:
7740     case Intrinsic::x86_sse2_comige_sd:
7741       Opc = X86ISD::COMI;
7742       CC = ISD::SETGE;
7743       break;
7744     case Intrinsic::x86_sse_comineq_ss:
7745     case Intrinsic::x86_sse2_comineq_sd:
7746       Opc = X86ISD::COMI;
7747       CC = ISD::SETNE;
7748       break;
7749     case Intrinsic::x86_sse_ucomieq_ss:
7750     case Intrinsic::x86_sse2_ucomieq_sd:
7751       Opc = X86ISD::UCOMI;
7752       CC = ISD::SETEQ;
7753       break;
7754     case Intrinsic::x86_sse_ucomilt_ss:
7755     case Intrinsic::x86_sse2_ucomilt_sd:
7756       Opc = X86ISD::UCOMI;
7757       CC = ISD::SETLT;
7758       break;
7759     case Intrinsic::x86_sse_ucomile_ss:
7760     case Intrinsic::x86_sse2_ucomile_sd:
7761       Opc = X86ISD::UCOMI;
7762       CC = ISD::SETLE;
7763       break;
7764     case Intrinsic::x86_sse_ucomigt_ss:
7765     case Intrinsic::x86_sse2_ucomigt_sd:
7766       Opc = X86ISD::UCOMI;
7767       CC = ISD::SETGT;
7768       break;
7769     case Intrinsic::x86_sse_ucomige_ss:
7770     case Intrinsic::x86_sse2_ucomige_sd:
7771       Opc = X86ISD::UCOMI;
7772       CC = ISD::SETGE;
7773       break;
7774     case Intrinsic::x86_sse_ucomineq_ss:
7775     case Intrinsic::x86_sse2_ucomineq_sd:
7776       Opc = X86ISD::UCOMI;
7777       CC = ISD::SETNE;
7778       break;
7779     }
7780
7781     SDValue LHS = Op.getOperand(1);
7782     SDValue RHS = Op.getOperand(2);
7783     unsigned X86CC = TranslateX86CC(CC, true, LHS, RHS, DAG);
7784     assert(X86CC != X86::COND_INVALID && "Unexpected illegal condition!");
7785     SDValue Cond = DAG.getNode(Opc, dl, MVT::i32, LHS, RHS);
7786     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
7787                                 DAG.getConstant(X86CC, MVT::i8), Cond);
7788     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
7789   }
7790   // ptest and testp intrinsics. The intrinsic these come from are designed to
7791   // return an integer value, not just an instruction so lower it to the ptest
7792   // or testp pattern and a setcc for the result.
7793   case Intrinsic::x86_sse41_ptestz:
7794   case Intrinsic::x86_sse41_ptestc:
7795   case Intrinsic::x86_sse41_ptestnzc:
7796   case Intrinsic::x86_avx_ptestz_256:
7797   case Intrinsic::x86_avx_ptestc_256:
7798   case Intrinsic::x86_avx_ptestnzc_256:
7799   case Intrinsic::x86_avx_vtestz_ps:
7800   case Intrinsic::x86_avx_vtestc_ps:
7801   case Intrinsic::x86_avx_vtestnzc_ps:
7802   case Intrinsic::x86_avx_vtestz_pd:
7803   case Intrinsic::x86_avx_vtestc_pd:
7804   case Intrinsic::x86_avx_vtestnzc_pd:
7805   case Intrinsic::x86_avx_vtestz_ps_256:
7806   case Intrinsic::x86_avx_vtestc_ps_256:
7807   case Intrinsic::x86_avx_vtestnzc_ps_256:
7808   case Intrinsic::x86_avx_vtestz_pd_256:
7809   case Intrinsic::x86_avx_vtestc_pd_256:
7810   case Intrinsic::x86_avx_vtestnzc_pd_256: {
7811     bool IsTestPacked = false;
7812     unsigned X86CC = 0;
7813     switch (IntNo) {
7814     default: llvm_unreachable("Bad fallthrough in Intrinsic lowering.");
7815     case Intrinsic::x86_avx_vtestz_ps:
7816     case Intrinsic::x86_avx_vtestz_pd:
7817     case Intrinsic::x86_avx_vtestz_ps_256:
7818     case Intrinsic::x86_avx_vtestz_pd_256:
7819       IsTestPacked = true; // Fallthrough
7820     case Intrinsic::x86_sse41_ptestz:
7821     case Intrinsic::x86_avx_ptestz_256:
7822       // ZF = 1
7823       X86CC = X86::COND_E;
7824       break;
7825     case Intrinsic::x86_avx_vtestc_ps:
7826     case Intrinsic::x86_avx_vtestc_pd:
7827     case Intrinsic::x86_avx_vtestc_ps_256:
7828     case Intrinsic::x86_avx_vtestc_pd_256:
7829       IsTestPacked = true; // Fallthrough
7830     case Intrinsic::x86_sse41_ptestc:
7831     case Intrinsic::x86_avx_ptestc_256:
7832       // CF = 1
7833       X86CC = X86::COND_B;
7834       break;
7835     case Intrinsic::x86_avx_vtestnzc_ps:
7836     case Intrinsic::x86_avx_vtestnzc_pd:
7837     case Intrinsic::x86_avx_vtestnzc_ps_256:
7838     case Intrinsic::x86_avx_vtestnzc_pd_256:
7839       IsTestPacked = true; // Fallthrough
7840     case Intrinsic::x86_sse41_ptestnzc:
7841     case Intrinsic::x86_avx_ptestnzc_256:
7842       // ZF and CF = 0
7843       X86CC = X86::COND_A;
7844       break;
7845     }
7846
7847     SDValue LHS = Op.getOperand(1);
7848     SDValue RHS = Op.getOperand(2);
7849     unsigned TestOpc = IsTestPacked ? X86ISD::TESTP : X86ISD::PTEST;
7850     SDValue Test = DAG.getNode(TestOpc, dl, MVT::i32, LHS, RHS);
7851     SDValue CC = DAG.getConstant(X86CC, MVT::i8);
7852     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8, CC, Test);
7853     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
7854   }
7855
7856   // Fix vector shift instructions where the last operand is a non-immediate
7857   // i32 value.
7858   case Intrinsic::x86_sse2_pslli_w:
7859   case Intrinsic::x86_sse2_pslli_d:
7860   case Intrinsic::x86_sse2_pslli_q:
7861   case Intrinsic::x86_sse2_psrli_w:
7862   case Intrinsic::x86_sse2_psrli_d:
7863   case Intrinsic::x86_sse2_psrli_q:
7864   case Intrinsic::x86_sse2_psrai_w:
7865   case Intrinsic::x86_sse2_psrai_d:
7866   case Intrinsic::x86_mmx_pslli_w:
7867   case Intrinsic::x86_mmx_pslli_d:
7868   case Intrinsic::x86_mmx_pslli_q:
7869   case Intrinsic::x86_mmx_psrli_w:
7870   case Intrinsic::x86_mmx_psrli_d:
7871   case Intrinsic::x86_mmx_psrli_q:
7872   case Intrinsic::x86_mmx_psrai_w:
7873   case Intrinsic::x86_mmx_psrai_d: {
7874     SDValue ShAmt = Op.getOperand(2);
7875     if (isa<ConstantSDNode>(ShAmt))
7876       return SDValue();
7877
7878     unsigned NewIntNo = 0;
7879     EVT ShAmtVT = MVT::v4i32;
7880     switch (IntNo) {
7881     case Intrinsic::x86_sse2_pslli_w:
7882       NewIntNo = Intrinsic::x86_sse2_psll_w;
7883       break;
7884     case Intrinsic::x86_sse2_pslli_d:
7885       NewIntNo = Intrinsic::x86_sse2_psll_d;
7886       break;
7887     case Intrinsic::x86_sse2_pslli_q:
7888       NewIntNo = Intrinsic::x86_sse2_psll_q;
7889       break;
7890     case Intrinsic::x86_sse2_psrli_w:
7891       NewIntNo = Intrinsic::x86_sse2_psrl_w;
7892       break;
7893     case Intrinsic::x86_sse2_psrli_d:
7894       NewIntNo = Intrinsic::x86_sse2_psrl_d;
7895       break;
7896     case Intrinsic::x86_sse2_psrli_q:
7897       NewIntNo = Intrinsic::x86_sse2_psrl_q;
7898       break;
7899     case Intrinsic::x86_sse2_psrai_w:
7900       NewIntNo = Intrinsic::x86_sse2_psra_w;
7901       break;
7902     case Intrinsic::x86_sse2_psrai_d:
7903       NewIntNo = Intrinsic::x86_sse2_psra_d;
7904       break;
7905     default: {
7906       ShAmtVT = MVT::v2i32;
7907       switch (IntNo) {
7908       case Intrinsic::x86_mmx_pslli_w:
7909         NewIntNo = Intrinsic::x86_mmx_psll_w;
7910         break;
7911       case Intrinsic::x86_mmx_pslli_d:
7912         NewIntNo = Intrinsic::x86_mmx_psll_d;
7913         break;
7914       case Intrinsic::x86_mmx_pslli_q:
7915         NewIntNo = Intrinsic::x86_mmx_psll_q;
7916         break;
7917       case Intrinsic::x86_mmx_psrli_w:
7918         NewIntNo = Intrinsic::x86_mmx_psrl_w;
7919         break;
7920       case Intrinsic::x86_mmx_psrli_d:
7921         NewIntNo = Intrinsic::x86_mmx_psrl_d;
7922         break;
7923       case Intrinsic::x86_mmx_psrli_q:
7924         NewIntNo = Intrinsic::x86_mmx_psrl_q;
7925         break;
7926       case Intrinsic::x86_mmx_psrai_w:
7927         NewIntNo = Intrinsic::x86_mmx_psra_w;
7928         break;
7929       case Intrinsic::x86_mmx_psrai_d:
7930         NewIntNo = Intrinsic::x86_mmx_psra_d;
7931         break;
7932       default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
7933       }
7934       break;
7935     }
7936     }
7937
7938     // The vector shift intrinsics with scalars uses 32b shift amounts but
7939     // the sse2/mmx shift instructions reads 64 bits. Set the upper 32 bits
7940     // to be zero.
7941     SDValue ShOps[4];
7942     ShOps[0] = ShAmt;
7943     ShOps[1] = DAG.getConstant(0, MVT::i32);
7944     if (ShAmtVT == MVT::v4i32) {
7945       ShOps[2] = DAG.getUNDEF(MVT::i32);
7946       ShOps[3] = DAG.getUNDEF(MVT::i32);
7947       ShAmt =  DAG.getNode(ISD::BUILD_VECTOR, dl, ShAmtVT, &ShOps[0], 4);
7948     } else {
7949       ShAmt =  DAG.getNode(ISD::BUILD_VECTOR, dl, ShAmtVT, &ShOps[0], 2);
7950 // FIXME this must be lowered to get rid of the invalid type.
7951     }
7952
7953     EVT VT = Op.getValueType();
7954     ShAmt = DAG.getNode(ISD::BITCAST, dl, VT, ShAmt);
7955     return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
7956                        DAG.getConstant(NewIntNo, MVT::i32),
7957                        Op.getOperand(1), ShAmt);
7958   }
7959   }
7960 }
7961
7962 SDValue X86TargetLowering::LowerRETURNADDR(SDValue Op,
7963                                            SelectionDAG &DAG) const {
7964   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
7965   MFI->setReturnAddressIsTaken(true);
7966
7967   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
7968   DebugLoc dl = Op.getDebugLoc();
7969
7970   if (Depth > 0) {
7971     SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
7972     SDValue Offset =
7973       DAG.getConstant(TD->getPointerSize(),
7974                       Subtarget->is64Bit() ? MVT::i64 : MVT::i32);
7975     return DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(),
7976                        DAG.getNode(ISD::ADD, dl, getPointerTy(),
7977                                    FrameAddr, Offset),
7978                        MachinePointerInfo(), false, false, 0);
7979   }
7980
7981   // Just load the return address.
7982   SDValue RetAddrFI = getReturnAddressFrameIndex(DAG);
7983   return DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(),
7984                      RetAddrFI, MachinePointerInfo(), false, false, 0);
7985 }
7986
7987 SDValue X86TargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
7988   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
7989   MFI->setFrameAddressIsTaken(true);
7990
7991   EVT VT = Op.getValueType();
7992   DebugLoc dl = Op.getDebugLoc();  // FIXME probably not meaningful
7993   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
7994   unsigned FrameReg = Subtarget->is64Bit() ? X86::RBP : X86::EBP;
7995   SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
7996   while (Depth--)
7997     FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr,
7998                             MachinePointerInfo(),
7999                             false, false, 0);
8000   return FrameAddr;
8001 }
8002
8003 SDValue X86TargetLowering::LowerFRAME_TO_ARGS_OFFSET(SDValue Op,
8004                                                      SelectionDAG &DAG) const {
8005   return DAG.getIntPtrConstant(2*TD->getPointerSize());
8006 }
8007
8008 SDValue X86TargetLowering::LowerEH_RETURN(SDValue Op, SelectionDAG &DAG) const {
8009   MachineFunction &MF = DAG.getMachineFunction();
8010   SDValue Chain     = Op.getOperand(0);
8011   SDValue Offset    = Op.getOperand(1);
8012   SDValue Handler   = Op.getOperand(2);
8013   DebugLoc dl       = Op.getDebugLoc();
8014
8015   SDValue Frame = DAG.getCopyFromReg(DAG.getEntryNode(), dl,
8016                                      Subtarget->is64Bit() ? X86::RBP : X86::EBP,
8017                                      getPointerTy());
8018   unsigned StoreAddrReg = (Subtarget->is64Bit() ? X86::RCX : X86::ECX);
8019
8020   SDValue StoreAddr = DAG.getNode(ISD::ADD, dl, getPointerTy(), Frame,
8021                                   DAG.getIntPtrConstant(TD->getPointerSize()));
8022   StoreAddr = DAG.getNode(ISD::ADD, dl, getPointerTy(), StoreAddr, Offset);
8023   Chain = DAG.getStore(Chain, dl, Handler, StoreAddr, MachinePointerInfo(),
8024                        false, false, 0);
8025   Chain = DAG.getCopyToReg(Chain, dl, StoreAddrReg, StoreAddr);
8026   MF.getRegInfo().addLiveOut(StoreAddrReg);
8027
8028   return DAG.getNode(X86ISD::EH_RETURN, dl,
8029                      MVT::Other,
8030                      Chain, DAG.getRegister(StoreAddrReg, getPointerTy()));
8031 }
8032
8033 SDValue X86TargetLowering::LowerTRAMPOLINE(SDValue Op,
8034                                              SelectionDAG &DAG) const {
8035   SDValue Root = Op.getOperand(0);
8036   SDValue Trmp = Op.getOperand(1); // trampoline
8037   SDValue FPtr = Op.getOperand(2); // nested function
8038   SDValue Nest = Op.getOperand(3); // 'nest' parameter value
8039   DebugLoc dl  = Op.getDebugLoc();
8040
8041   const Value *TrmpAddr = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
8042
8043   if (Subtarget->is64Bit()) {
8044     SDValue OutChains[6];
8045
8046     // Large code-model.
8047     const unsigned char JMP64r  = 0xFF; // 64-bit jmp through register opcode.
8048     const unsigned char MOV64ri = 0xB8; // X86::MOV64ri opcode.
8049
8050     const unsigned char N86R10 = RegInfo->getX86RegNum(X86::R10);
8051     const unsigned char N86R11 = RegInfo->getX86RegNum(X86::R11);
8052
8053     const unsigned char REX_WB = 0x40 | 0x08 | 0x01; // REX prefix
8054
8055     // Load the pointer to the nested function into R11.
8056     unsigned OpCode = ((MOV64ri | N86R11) << 8) | REX_WB; // movabsq r11
8057     SDValue Addr = Trmp;
8058     OutChains[0] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
8059                                 Addr, MachinePointerInfo(TrmpAddr),
8060                                 false, false, 0);
8061
8062     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
8063                        DAG.getConstant(2, MVT::i64));
8064     OutChains[1] = DAG.getStore(Root, dl, FPtr, Addr,
8065                                 MachinePointerInfo(TrmpAddr, 2),
8066                                 false, false, 2);
8067
8068     // Load the 'nest' parameter value into R10.
8069     // R10 is specified in X86CallingConv.td
8070     OpCode = ((MOV64ri | N86R10) << 8) | REX_WB; // movabsq r10
8071     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
8072                        DAG.getConstant(10, MVT::i64));
8073     OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
8074                                 Addr, MachinePointerInfo(TrmpAddr, 10),
8075                                 false, false, 0);
8076
8077     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
8078                        DAG.getConstant(12, MVT::i64));
8079     OutChains[3] = DAG.getStore(Root, dl, Nest, Addr,
8080                                 MachinePointerInfo(TrmpAddr, 12),
8081                                 false, false, 2);
8082
8083     // Jump to the nested function.
8084     OpCode = (JMP64r << 8) | REX_WB; // jmpq *...
8085     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
8086                        DAG.getConstant(20, MVT::i64));
8087     OutChains[4] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
8088                                 Addr, MachinePointerInfo(TrmpAddr, 20),
8089                                 false, false, 0);
8090
8091     unsigned char ModRM = N86R11 | (4 << 3) | (3 << 6); // ...r11
8092     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
8093                        DAG.getConstant(22, MVT::i64));
8094     OutChains[5] = DAG.getStore(Root, dl, DAG.getConstant(ModRM, MVT::i8), Addr,
8095                                 MachinePointerInfo(TrmpAddr, 22),
8096                                 false, false, 0);
8097
8098     SDValue Ops[] =
8099       { Trmp, DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains, 6) };
8100     return DAG.getMergeValues(Ops, 2, dl);
8101   } else {
8102     const Function *Func =
8103       cast<Function>(cast<SrcValueSDNode>(Op.getOperand(5))->getValue());
8104     CallingConv::ID CC = Func->getCallingConv();
8105     unsigned NestReg;
8106
8107     switch (CC) {
8108     default:
8109       llvm_unreachable("Unsupported calling convention");
8110     case CallingConv::C:
8111     case CallingConv::X86_StdCall: {
8112       // Pass 'nest' parameter in ECX.
8113       // Must be kept in sync with X86CallingConv.td
8114       NestReg = X86::ECX;
8115
8116       // Check that ECX wasn't needed by an 'inreg' parameter.
8117       const FunctionType *FTy = Func->getFunctionType();
8118       const AttrListPtr &Attrs = Func->getAttributes();
8119
8120       if (!Attrs.isEmpty() && !Func->isVarArg()) {
8121         unsigned InRegCount = 0;
8122         unsigned Idx = 1;
8123
8124         for (FunctionType::param_iterator I = FTy->param_begin(),
8125              E = FTy->param_end(); I != E; ++I, ++Idx)
8126           if (Attrs.paramHasAttr(Idx, Attribute::InReg))
8127             // FIXME: should only count parameters that are lowered to integers.
8128             InRegCount += (TD->getTypeSizeInBits(*I) + 31) / 32;
8129
8130         if (InRegCount > 2) {
8131           report_fatal_error("Nest register in use - reduce number of inreg"
8132                              " parameters!");
8133         }
8134       }
8135       break;
8136     }
8137     case CallingConv::X86_FastCall:
8138     case CallingConv::X86_ThisCall:
8139     case CallingConv::Fast:
8140       // Pass 'nest' parameter in EAX.
8141       // Must be kept in sync with X86CallingConv.td
8142       NestReg = X86::EAX;
8143       break;
8144     }
8145
8146     SDValue OutChains[4];
8147     SDValue Addr, Disp;
8148
8149     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
8150                        DAG.getConstant(10, MVT::i32));
8151     Disp = DAG.getNode(ISD::SUB, dl, MVT::i32, FPtr, Addr);
8152
8153     // This is storing the opcode for MOV32ri.
8154     const unsigned char MOV32ri = 0xB8; // X86::MOV32ri's opcode byte.
8155     const unsigned char N86Reg = RegInfo->getX86RegNum(NestReg);
8156     OutChains[0] = DAG.getStore(Root, dl,
8157                                 DAG.getConstant(MOV32ri|N86Reg, MVT::i8),
8158                                 Trmp, MachinePointerInfo(TrmpAddr),
8159                                 false, false, 0);
8160
8161     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
8162                        DAG.getConstant(1, MVT::i32));
8163     OutChains[1] = DAG.getStore(Root, dl, Nest, Addr,
8164                                 MachinePointerInfo(TrmpAddr, 1),
8165                                 false, false, 1);
8166
8167     const unsigned char JMP = 0xE9; // jmp <32bit dst> opcode.
8168     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
8169                        DAG.getConstant(5, MVT::i32));
8170     OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(JMP, MVT::i8), Addr,
8171                                 MachinePointerInfo(TrmpAddr, 5),
8172                                 false, false, 1);
8173
8174     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
8175                        DAG.getConstant(6, MVT::i32));
8176     OutChains[3] = DAG.getStore(Root, dl, Disp, Addr,
8177                                 MachinePointerInfo(TrmpAddr, 6),
8178                                 false, false, 1);
8179
8180     SDValue Ops[] =
8181       { Trmp, DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains, 4) };
8182     return DAG.getMergeValues(Ops, 2, dl);
8183   }
8184 }
8185
8186 SDValue X86TargetLowering::LowerFLT_ROUNDS_(SDValue Op,
8187                                             SelectionDAG &DAG) const {
8188   /*
8189    The rounding mode is in bits 11:10 of FPSR, and has the following
8190    settings:
8191      00 Round to nearest
8192      01 Round to -inf
8193      10 Round to +inf
8194      11 Round to 0
8195
8196   FLT_ROUNDS, on the other hand, expects the following:
8197     -1 Undefined
8198      0 Round to 0
8199      1 Round to nearest
8200      2 Round to +inf
8201      3 Round to -inf
8202
8203   To perform the conversion, we do:
8204     (((((FPSR & 0x800) >> 11) | ((FPSR & 0x400) >> 9)) + 1) & 3)
8205   */
8206
8207   MachineFunction &MF = DAG.getMachineFunction();
8208   const TargetMachine &TM = MF.getTarget();
8209   const TargetFrameInfo &TFI = *TM.getFrameInfo();
8210   unsigned StackAlignment = TFI.getStackAlignment();
8211   EVT VT = Op.getValueType();
8212   DebugLoc DL = Op.getDebugLoc();
8213
8214   // Save FP Control Word to stack slot
8215   int SSFI = MF.getFrameInfo()->CreateStackObject(2, StackAlignment, false);
8216   SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
8217
8218
8219   MachineMemOperand *MMO =
8220    MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
8221                            MachineMemOperand::MOStore, 2, 2);
8222
8223   SDValue Ops[] = { DAG.getEntryNode(), StackSlot };
8224   SDValue Chain = DAG.getMemIntrinsicNode(X86ISD::FNSTCW16m, DL,
8225                                           DAG.getVTList(MVT::Other),
8226                                           Ops, 2, MVT::i16, MMO);
8227
8228   // Load FP Control Word from stack slot
8229   SDValue CWD = DAG.getLoad(MVT::i16, DL, Chain, StackSlot,
8230                             MachinePointerInfo(), false, false, 0);
8231
8232   // Transform as necessary
8233   SDValue CWD1 =
8234     DAG.getNode(ISD::SRL, DL, MVT::i16,
8235                 DAG.getNode(ISD::AND, DL, MVT::i16,
8236                             CWD, DAG.getConstant(0x800, MVT::i16)),
8237                 DAG.getConstant(11, MVT::i8));
8238   SDValue CWD2 =
8239     DAG.getNode(ISD::SRL, DL, MVT::i16,
8240                 DAG.getNode(ISD::AND, DL, MVT::i16,
8241                             CWD, DAG.getConstant(0x400, MVT::i16)),
8242                 DAG.getConstant(9, MVT::i8));
8243
8244   SDValue RetVal =
8245     DAG.getNode(ISD::AND, DL, MVT::i16,
8246                 DAG.getNode(ISD::ADD, DL, MVT::i16,
8247                             DAG.getNode(ISD::OR, DL, MVT::i16, CWD1, CWD2),
8248                             DAG.getConstant(1, MVT::i16)),
8249                 DAG.getConstant(3, MVT::i16));
8250
8251
8252   return DAG.getNode((VT.getSizeInBits() < 16 ?
8253                       ISD::TRUNCATE : ISD::ZERO_EXTEND), DL, VT, RetVal);
8254 }
8255
8256 SDValue X86TargetLowering::LowerCTLZ(SDValue Op, SelectionDAG &DAG) const {
8257   EVT VT = Op.getValueType();
8258   EVT OpVT = VT;
8259   unsigned NumBits = VT.getSizeInBits();
8260   DebugLoc dl = Op.getDebugLoc();
8261
8262   Op = Op.getOperand(0);
8263   if (VT == MVT::i8) {
8264     // Zero extend to i32 since there is not an i8 bsr.
8265     OpVT = MVT::i32;
8266     Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
8267   }
8268
8269   // Issue a bsr (scan bits in reverse) which also sets EFLAGS.
8270   SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
8271   Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
8272
8273   // If src is zero (i.e. bsr sets ZF), returns NumBits.
8274   SDValue Ops[] = {
8275     Op,
8276     DAG.getConstant(NumBits+NumBits-1, OpVT),
8277     DAG.getConstant(X86::COND_E, MVT::i8),
8278     Op.getValue(1)
8279   };
8280   Op = DAG.getNode(X86ISD::CMOV, dl, OpVT, Ops, array_lengthof(Ops));
8281
8282   // Finally xor with NumBits-1.
8283   Op = DAG.getNode(ISD::XOR, dl, OpVT, Op, DAG.getConstant(NumBits-1, OpVT));
8284
8285   if (VT == MVT::i8)
8286     Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
8287   return Op;
8288 }
8289
8290 SDValue X86TargetLowering::LowerCTTZ(SDValue Op, SelectionDAG &DAG) const {
8291   EVT VT = Op.getValueType();
8292   EVT OpVT = VT;
8293   unsigned NumBits = VT.getSizeInBits();
8294   DebugLoc dl = Op.getDebugLoc();
8295
8296   Op = Op.getOperand(0);
8297   if (VT == MVT::i8) {
8298     OpVT = MVT::i32;
8299     Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
8300   }
8301
8302   // Issue a bsf (scan bits forward) which also sets EFLAGS.
8303   SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
8304   Op = DAG.getNode(X86ISD::BSF, dl, VTs, Op);
8305
8306   // If src is zero (i.e. bsf sets ZF), returns NumBits.
8307   SDValue Ops[] = {
8308     Op,
8309     DAG.getConstant(NumBits, OpVT),
8310     DAG.getConstant(X86::COND_E, MVT::i8),
8311     Op.getValue(1)
8312   };
8313   Op = DAG.getNode(X86ISD::CMOV, dl, OpVT, Ops, array_lengthof(Ops));
8314
8315   if (VT == MVT::i8)
8316     Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
8317   return Op;
8318 }
8319
8320 SDValue X86TargetLowering::LowerMUL_V2I64(SDValue Op, SelectionDAG &DAG) const {
8321   EVT VT = Op.getValueType();
8322   assert(VT == MVT::v2i64 && "Only know how to lower V2I64 multiply");
8323   DebugLoc dl = Op.getDebugLoc();
8324
8325   //  ulong2 Ahi = __builtin_ia32_psrlqi128( a, 32);
8326   //  ulong2 Bhi = __builtin_ia32_psrlqi128( b, 32);
8327   //  ulong2 AloBlo = __builtin_ia32_pmuludq128( a, b );
8328   //  ulong2 AloBhi = __builtin_ia32_pmuludq128( a, Bhi );
8329   //  ulong2 AhiBlo = __builtin_ia32_pmuludq128( Ahi, b );
8330   //
8331   //  AloBhi = __builtin_ia32_psllqi128( AloBhi, 32 );
8332   //  AhiBlo = __builtin_ia32_psllqi128( AhiBlo, 32 );
8333   //  return AloBlo + AloBhi + AhiBlo;
8334
8335   SDValue A = Op.getOperand(0);
8336   SDValue B = Op.getOperand(1);
8337
8338   SDValue Ahi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8339                        DAG.getConstant(Intrinsic::x86_sse2_psrli_q, MVT::i32),
8340                        A, DAG.getConstant(32, MVT::i32));
8341   SDValue Bhi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8342                        DAG.getConstant(Intrinsic::x86_sse2_psrli_q, MVT::i32),
8343                        B, DAG.getConstant(32, MVT::i32));
8344   SDValue AloBlo = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8345                        DAG.getConstant(Intrinsic::x86_sse2_pmulu_dq, MVT::i32),
8346                        A, B);
8347   SDValue AloBhi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8348                        DAG.getConstant(Intrinsic::x86_sse2_pmulu_dq, MVT::i32),
8349                        A, Bhi);
8350   SDValue AhiBlo = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8351                        DAG.getConstant(Intrinsic::x86_sse2_pmulu_dq, MVT::i32),
8352                        Ahi, B);
8353   AloBhi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8354                        DAG.getConstant(Intrinsic::x86_sse2_pslli_q, MVT::i32),
8355                        AloBhi, DAG.getConstant(32, MVT::i32));
8356   AhiBlo = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8357                        DAG.getConstant(Intrinsic::x86_sse2_pslli_q, MVT::i32),
8358                        AhiBlo, DAG.getConstant(32, MVT::i32));
8359   SDValue Res = DAG.getNode(ISD::ADD, dl, VT, AloBlo, AloBhi);
8360   Res = DAG.getNode(ISD::ADD, dl, VT, Res, AhiBlo);
8361   return Res;
8362 }
8363
8364 SDValue X86TargetLowering::LowerSHL(SDValue Op, SelectionDAG &DAG) const {
8365   EVT VT = Op.getValueType();
8366   DebugLoc dl = Op.getDebugLoc();
8367   SDValue R = Op.getOperand(0);
8368
8369   LLVMContext *Context = DAG.getContext();
8370
8371   assert(Subtarget->hasSSE41() && "Cannot lower SHL without SSE4.1 or later");
8372
8373   if (VT == MVT::v4i32) {
8374     Op = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8375                      DAG.getConstant(Intrinsic::x86_sse2_pslli_d, MVT::i32),
8376                      Op.getOperand(1), DAG.getConstant(23, MVT::i32));
8377
8378     ConstantInt *CI = ConstantInt::get(*Context, APInt(32, 0x3f800000U));
8379
8380     std::vector<Constant*> CV(4, CI);
8381     Constant *C = ConstantVector::get(CV);
8382     SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
8383     SDValue Addend = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
8384                                  MachinePointerInfo::getConstantPool(),
8385                                  false, false, 16);
8386
8387     Op = DAG.getNode(ISD::ADD, dl, VT, Op, Addend);
8388     Op = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, Op);
8389     Op = DAG.getNode(ISD::FP_TO_SINT, dl, VT, Op);
8390     return DAG.getNode(ISD::MUL, dl, VT, Op, R);
8391   }
8392   if (VT == MVT::v16i8) {
8393     // a = a << 5;
8394     Op = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8395                      DAG.getConstant(Intrinsic::x86_sse2_pslli_w, MVT::i32),
8396                      Op.getOperand(1), DAG.getConstant(5, MVT::i32));
8397
8398     ConstantInt *CM1 = ConstantInt::get(*Context, APInt(8, 15));
8399     ConstantInt *CM2 = ConstantInt::get(*Context, APInt(8, 63));
8400
8401     std::vector<Constant*> CVM1(16, CM1);
8402     std::vector<Constant*> CVM2(16, CM2);
8403     Constant *C = ConstantVector::get(CVM1);
8404     SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
8405     SDValue M = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
8406                             MachinePointerInfo::getConstantPool(),
8407                             false, false, 16);
8408
8409     // r = pblendv(r, psllw(r & (char16)15, 4), a);
8410     M = DAG.getNode(ISD::AND, dl, VT, R, M);
8411     M = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8412                     DAG.getConstant(Intrinsic::x86_sse2_pslli_w, MVT::i32), M,
8413                     DAG.getConstant(4, MVT::i32));
8414     R = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8415                     DAG.getConstant(Intrinsic::x86_sse41_pblendvb, MVT::i32),
8416                     R, M, Op);
8417     // a += a
8418     Op = DAG.getNode(ISD::ADD, dl, VT, Op, Op);
8419
8420     C = ConstantVector::get(CVM2);
8421     CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
8422     M = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
8423                     MachinePointerInfo::getConstantPool(),
8424                     false, false, 16);
8425
8426     // r = pblendv(r, psllw(r & (char16)63, 2), a);
8427     M = DAG.getNode(ISD::AND, dl, VT, R, M);
8428     M = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8429                     DAG.getConstant(Intrinsic::x86_sse2_pslli_w, MVT::i32), M,
8430                     DAG.getConstant(2, MVT::i32));
8431     R = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8432                     DAG.getConstant(Intrinsic::x86_sse41_pblendvb, MVT::i32),
8433                     R, M, Op);
8434     // a += a
8435     Op = DAG.getNode(ISD::ADD, dl, VT, Op, Op);
8436
8437     // return pblendv(r, r+r, a);
8438     R = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8439                     DAG.getConstant(Intrinsic::x86_sse41_pblendvb, MVT::i32),
8440                     R, DAG.getNode(ISD::ADD, dl, VT, R, R), Op);
8441     return R;
8442   }
8443   return SDValue();
8444 }
8445
8446 SDValue X86TargetLowering::LowerXALUO(SDValue Op, SelectionDAG &DAG) const {
8447   // Lower the "add/sub/mul with overflow" instruction into a regular ins plus
8448   // a "setcc" instruction that checks the overflow flag. The "brcond" lowering
8449   // looks for this combo and may remove the "setcc" instruction if the "setcc"
8450   // has only one use.
8451   SDNode *N = Op.getNode();
8452   SDValue LHS = N->getOperand(0);
8453   SDValue RHS = N->getOperand(1);
8454   unsigned BaseOp = 0;
8455   unsigned Cond = 0;
8456   DebugLoc DL = Op.getDebugLoc();
8457   switch (Op.getOpcode()) {
8458   default: llvm_unreachable("Unknown ovf instruction!");
8459   case ISD::SADDO:
8460     // A subtract of one will be selected as a INC. Note that INC doesn't
8461     // set CF, so we can't do this for UADDO.
8462     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op))
8463       if (C->getAPIntValue() == 1) {
8464         BaseOp = X86ISD::INC;
8465         Cond = X86::COND_O;
8466         break;
8467       }
8468     BaseOp = X86ISD::ADD;
8469     Cond = X86::COND_O;
8470     break;
8471   case ISD::UADDO:
8472     BaseOp = X86ISD::ADD;
8473     Cond = X86::COND_B;
8474     break;
8475   case ISD::SSUBO:
8476     // A subtract of one will be selected as a DEC. Note that DEC doesn't
8477     // set CF, so we can't do this for USUBO.
8478     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op))
8479       if (C->getAPIntValue() == 1) {
8480         BaseOp = X86ISD::DEC;
8481         Cond = X86::COND_O;
8482         break;
8483       }
8484     BaseOp = X86ISD::SUB;
8485     Cond = X86::COND_O;
8486     break;
8487   case ISD::USUBO:
8488     BaseOp = X86ISD::SUB;
8489     Cond = X86::COND_B;
8490     break;
8491   case ISD::SMULO:
8492     BaseOp = X86ISD::SMUL;
8493     Cond = X86::COND_O;
8494     break;
8495   case ISD::UMULO: { // i64, i8 = umulo lhs, rhs --> i64, i64, i32 umul lhs,rhs
8496     SDVTList VTs = DAG.getVTList(N->getValueType(0), N->getValueType(0),
8497                                  MVT::i32);
8498     SDValue Sum = DAG.getNode(X86ISD::UMUL, DL, VTs, LHS, RHS);
8499     
8500     SDValue SetCC =
8501       DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
8502                   DAG.getConstant(X86::COND_O, MVT::i32),
8503                   SDValue(Sum.getNode(), 2));
8504     
8505     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), SetCC);
8506     return Sum;
8507   }
8508   }
8509
8510   // Also sets EFLAGS.
8511   SDVTList VTs = DAG.getVTList(N->getValueType(0), MVT::i32);
8512   SDValue Sum = DAG.getNode(BaseOp, DL, VTs, LHS, RHS);
8513
8514   SDValue SetCC =
8515     DAG.getNode(X86ISD::SETCC, DL, N->getValueType(1),
8516                 DAG.getConstant(Cond, MVT::i32),
8517                 SDValue(Sum.getNode(), 1));
8518
8519   DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), SetCC);
8520   return Sum;
8521 }
8522
8523 SDValue X86TargetLowering::LowerMEMBARRIER(SDValue Op, SelectionDAG &DAG) const{
8524   DebugLoc dl = Op.getDebugLoc();
8525
8526   if (!Subtarget->hasSSE2()) {
8527     SDValue Chain = Op.getOperand(0);
8528     SDValue Zero = DAG.getConstant(0,
8529                                    Subtarget->is64Bit() ? MVT::i64 : MVT::i32);
8530     SDValue Ops[] = {
8531       DAG.getRegister(X86::ESP, MVT::i32), // Base
8532       DAG.getTargetConstant(1, MVT::i8),   // Scale
8533       DAG.getRegister(0, MVT::i32),        // Index
8534       DAG.getTargetConstant(0, MVT::i32),  // Disp
8535       DAG.getRegister(0, MVT::i32),        // Segment.
8536       Zero,
8537       Chain
8538     };
8539     SDNode *Res =
8540       DAG.getMachineNode(X86::OR32mrLocked, dl, MVT::Other, Ops,
8541                           array_lengthof(Ops));
8542     return SDValue(Res, 0);
8543   }
8544
8545   unsigned isDev = cast<ConstantSDNode>(Op.getOperand(5))->getZExtValue();
8546   if (!isDev)
8547     return DAG.getNode(X86ISD::MEMBARRIER, dl, MVT::Other, Op.getOperand(0));
8548
8549   unsigned Op1 = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
8550   unsigned Op2 = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue();
8551   unsigned Op3 = cast<ConstantSDNode>(Op.getOperand(3))->getZExtValue();
8552   unsigned Op4 = cast<ConstantSDNode>(Op.getOperand(4))->getZExtValue();
8553
8554   // def : Pat<(membarrier (i8 0), (i8 0), (i8 0), (i8 1), (i8 1)), (SFENCE)>;
8555   if (!Op1 && !Op2 && !Op3 && Op4)
8556     return DAG.getNode(X86ISD::SFENCE, dl, MVT::Other, Op.getOperand(0));
8557
8558   // def : Pat<(membarrier (i8 1), (i8 0), (i8 0), (i8 0), (i8 1)), (LFENCE)>;
8559   if (Op1 && !Op2 && !Op3 && !Op4)
8560     return DAG.getNode(X86ISD::LFENCE, dl, MVT::Other, Op.getOperand(0));
8561
8562   // def : Pat<(membarrier (i8 imm), (i8 imm), (i8 imm), (i8 imm), (i8 1)),
8563   //           (MFENCE)>;
8564   return DAG.getNode(X86ISD::MFENCE, dl, MVT::Other, Op.getOperand(0));
8565 }
8566
8567 SDValue X86TargetLowering::LowerCMP_SWAP(SDValue Op, SelectionDAG &DAG) const {
8568   EVT T = Op.getValueType();
8569   DebugLoc DL = Op.getDebugLoc();
8570   unsigned Reg = 0;
8571   unsigned size = 0;
8572   switch(T.getSimpleVT().SimpleTy) {
8573   default:
8574     assert(false && "Invalid value type!");
8575   case MVT::i8:  Reg = X86::AL;  size = 1; break;
8576   case MVT::i16: Reg = X86::AX;  size = 2; break;
8577   case MVT::i32: Reg = X86::EAX; size = 4; break;
8578   case MVT::i64:
8579     assert(Subtarget->is64Bit() && "Node not type legal!");
8580     Reg = X86::RAX; size = 8;
8581     break;
8582   }
8583   SDValue cpIn = DAG.getCopyToReg(Op.getOperand(0), DL, Reg,
8584                                     Op.getOperand(2), SDValue());
8585   SDValue Ops[] = { cpIn.getValue(0),
8586                     Op.getOperand(1),
8587                     Op.getOperand(3),
8588                     DAG.getTargetConstant(size, MVT::i8),
8589                     cpIn.getValue(1) };
8590   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Flag);
8591   MachineMemOperand *MMO = cast<AtomicSDNode>(Op)->getMemOperand();
8592   SDValue Result = DAG.getMemIntrinsicNode(X86ISD::LCMPXCHG_DAG, DL, Tys,
8593                                            Ops, 5, T, MMO);
8594   SDValue cpOut =
8595     DAG.getCopyFromReg(Result.getValue(0), DL, Reg, T, Result.getValue(1));
8596   return cpOut;
8597 }
8598
8599 SDValue X86TargetLowering::LowerREADCYCLECOUNTER(SDValue Op,
8600                                                  SelectionDAG &DAG) const {
8601   assert(Subtarget->is64Bit() && "Result not type legalized?");
8602   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Flag);
8603   SDValue TheChain = Op.getOperand(0);
8604   DebugLoc dl = Op.getDebugLoc();
8605   SDValue rd = DAG.getNode(X86ISD::RDTSC_DAG, dl, Tys, &TheChain, 1);
8606   SDValue rax = DAG.getCopyFromReg(rd, dl, X86::RAX, MVT::i64, rd.getValue(1));
8607   SDValue rdx = DAG.getCopyFromReg(rax.getValue(1), dl, X86::RDX, MVT::i64,
8608                                    rax.getValue(2));
8609   SDValue Tmp = DAG.getNode(ISD::SHL, dl, MVT::i64, rdx,
8610                             DAG.getConstant(32, MVT::i8));
8611   SDValue Ops[] = {
8612     DAG.getNode(ISD::OR, dl, MVT::i64, rax, Tmp),
8613     rdx.getValue(1)
8614   };
8615   return DAG.getMergeValues(Ops, 2, dl);
8616 }
8617
8618 SDValue X86TargetLowering::LowerBITCAST(SDValue Op,
8619                                             SelectionDAG &DAG) const {
8620   EVT SrcVT = Op.getOperand(0).getValueType();
8621   EVT DstVT = Op.getValueType();
8622   assert((Subtarget->is64Bit() && !Subtarget->hasSSE2() &&
8623           Subtarget->hasMMX() && !DisableMMX) &&
8624          "Unexpected custom BITCAST");
8625   assert((DstVT == MVT::i64 ||
8626           (DstVT.isVector() && DstVT.getSizeInBits()==64)) &&
8627          "Unexpected custom BITCAST");
8628   // i64 <=> MMX conversions are Legal.
8629   if (SrcVT==MVT::i64 && DstVT.isVector())
8630     return Op;
8631   if (DstVT==MVT::i64 && SrcVT.isVector())
8632     return Op;
8633   // MMX <=> MMX conversions are Legal.
8634   if (SrcVT.isVector() && DstVT.isVector())
8635     return Op;
8636   // All other conversions need to be expanded.
8637   return SDValue();
8638 }
8639 SDValue X86TargetLowering::LowerLOAD_SUB(SDValue Op, SelectionDAG &DAG) const {
8640   SDNode *Node = Op.getNode();
8641   DebugLoc dl = Node->getDebugLoc();
8642   EVT T = Node->getValueType(0);
8643   SDValue negOp = DAG.getNode(ISD::SUB, dl, T,
8644                               DAG.getConstant(0, T), Node->getOperand(2));
8645   return DAG.getAtomic(ISD::ATOMIC_LOAD_ADD, dl,
8646                        cast<AtomicSDNode>(Node)->getMemoryVT(),
8647                        Node->getOperand(0),
8648                        Node->getOperand(1), negOp,
8649                        cast<AtomicSDNode>(Node)->getSrcValue(),
8650                        cast<AtomicSDNode>(Node)->getAlignment());
8651 }
8652
8653 /// LowerOperation - Provide custom lowering hooks for some operations.
8654 ///
8655 SDValue X86TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
8656   switch (Op.getOpcode()) {
8657   default: llvm_unreachable("Should not custom lower this!");
8658   case ISD::MEMBARRIER:         return LowerMEMBARRIER(Op,DAG);
8659   case ISD::ATOMIC_CMP_SWAP:    return LowerCMP_SWAP(Op,DAG);
8660   case ISD::ATOMIC_LOAD_SUB:    return LowerLOAD_SUB(Op,DAG);
8661   case ISD::BUILD_VECTOR:       return LowerBUILD_VECTOR(Op, DAG);
8662   case ISD::CONCAT_VECTORS:     return LowerCONCAT_VECTORS(Op, DAG);
8663   case ISD::VECTOR_SHUFFLE:     return LowerVECTOR_SHUFFLE(Op, DAG);
8664   case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
8665   case ISD::INSERT_VECTOR_ELT:  return LowerINSERT_VECTOR_ELT(Op, DAG);
8666   case ISD::SCALAR_TO_VECTOR:   return LowerSCALAR_TO_VECTOR(Op, DAG);
8667   case ISD::ConstantPool:       return LowerConstantPool(Op, DAG);
8668   case ISD::GlobalAddress:      return LowerGlobalAddress(Op, DAG);
8669   case ISD::GlobalTLSAddress:   return LowerGlobalTLSAddress(Op, DAG);
8670   case ISD::ExternalSymbol:     return LowerExternalSymbol(Op, DAG);
8671   case ISD::BlockAddress:       return LowerBlockAddress(Op, DAG);
8672   case ISD::SHL_PARTS:
8673   case ISD::SRA_PARTS:
8674   case ISD::SRL_PARTS:          return LowerShift(Op, DAG);
8675   case ISD::SINT_TO_FP:         return LowerSINT_TO_FP(Op, DAG);
8676   case ISD::UINT_TO_FP:         return LowerUINT_TO_FP(Op, DAG);
8677   case ISD::FP_TO_SINT:         return LowerFP_TO_SINT(Op, DAG);
8678   case ISD::FP_TO_UINT:         return LowerFP_TO_UINT(Op, DAG);
8679   case ISD::FABS:               return LowerFABS(Op, DAG);
8680   case ISD::FNEG:               return LowerFNEG(Op, DAG);
8681   case ISD::FCOPYSIGN:          return LowerFCOPYSIGN(Op, DAG);
8682   case ISD::SETCC:              return LowerSETCC(Op, DAG);
8683   case ISD::VSETCC:             return LowerVSETCC(Op, DAG);
8684   case ISD::SELECT:             return LowerSELECT(Op, DAG);
8685   case ISD::BRCOND:             return LowerBRCOND(Op, DAG);
8686   case ISD::JumpTable:          return LowerJumpTable(Op, DAG);
8687   case ISD::VASTART:            return LowerVASTART(Op, DAG);
8688   case ISD::VAARG:              return LowerVAARG(Op, DAG);
8689   case ISD::VACOPY:             return LowerVACOPY(Op, DAG);
8690   case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
8691   case ISD::RETURNADDR:         return LowerRETURNADDR(Op, DAG);
8692   case ISD::FRAMEADDR:          return LowerFRAMEADDR(Op, DAG);
8693   case ISD::FRAME_TO_ARGS_OFFSET:
8694                                 return LowerFRAME_TO_ARGS_OFFSET(Op, DAG);
8695   case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG);
8696   case ISD::EH_RETURN:          return LowerEH_RETURN(Op, DAG);
8697   case ISD::TRAMPOLINE:         return LowerTRAMPOLINE(Op, DAG);
8698   case ISD::FLT_ROUNDS_:        return LowerFLT_ROUNDS_(Op, DAG);
8699   case ISD::CTLZ:               return LowerCTLZ(Op, DAG);
8700   case ISD::CTTZ:               return LowerCTTZ(Op, DAG);
8701   case ISD::MUL:                return LowerMUL_V2I64(Op, DAG);
8702   case ISD::SHL:                return LowerSHL(Op, DAG);
8703   case ISD::SADDO:
8704   case ISD::UADDO:
8705   case ISD::SSUBO:
8706   case ISD::USUBO:
8707   case ISD::SMULO:
8708   case ISD::UMULO:              return LowerXALUO(Op, DAG);
8709   case ISD::READCYCLECOUNTER:   return LowerREADCYCLECOUNTER(Op, DAG);
8710   case ISD::BITCAST:            return LowerBITCAST(Op, DAG);
8711   }
8712 }
8713
8714 void X86TargetLowering::
8715 ReplaceATOMIC_BINARY_64(SDNode *Node, SmallVectorImpl<SDValue>&Results,
8716                         SelectionDAG &DAG, unsigned NewOp) const {
8717   EVT T = Node->getValueType(0);
8718   DebugLoc dl = Node->getDebugLoc();
8719   assert (T == MVT::i64 && "Only know how to expand i64 atomics");
8720
8721   SDValue Chain = Node->getOperand(0);
8722   SDValue In1 = Node->getOperand(1);
8723   SDValue In2L = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
8724                              Node->getOperand(2), DAG.getIntPtrConstant(0));
8725   SDValue In2H = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
8726                              Node->getOperand(2), DAG.getIntPtrConstant(1));
8727   SDValue Ops[] = { Chain, In1, In2L, In2H };
8728   SDVTList Tys = DAG.getVTList(MVT::i32, MVT::i32, MVT::Other);
8729   SDValue Result =
8730     DAG.getMemIntrinsicNode(NewOp, dl, Tys, Ops, 4, MVT::i64,
8731                             cast<MemSDNode>(Node)->getMemOperand());
8732   SDValue OpsF[] = { Result.getValue(0), Result.getValue(1)};
8733   Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, OpsF, 2));
8734   Results.push_back(Result.getValue(2));
8735 }
8736
8737 /// ReplaceNodeResults - Replace a node with an illegal result type
8738 /// with a new node built out of custom code.
8739 void X86TargetLowering::ReplaceNodeResults(SDNode *N,
8740                                            SmallVectorImpl<SDValue>&Results,
8741                                            SelectionDAG &DAG) const {
8742   DebugLoc dl = N->getDebugLoc();
8743   switch (N->getOpcode()) {
8744   default:
8745     assert(false && "Do not know how to custom type legalize this operation!");
8746     return;
8747   case ISD::FP_TO_SINT: {
8748     std::pair<SDValue,SDValue> Vals =
8749         FP_TO_INTHelper(SDValue(N, 0), DAG, true);
8750     SDValue FIST = Vals.first, StackSlot = Vals.second;
8751     if (FIST.getNode() != 0) {
8752       EVT VT = N->getValueType(0);
8753       // Return a load from the stack slot.
8754       Results.push_back(DAG.getLoad(VT, dl, FIST, StackSlot,
8755                                     MachinePointerInfo(), false, false, 0));
8756     }
8757     return;
8758   }
8759   case ISD::READCYCLECOUNTER: {
8760     SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Flag);
8761     SDValue TheChain = N->getOperand(0);
8762     SDValue rd = DAG.getNode(X86ISD::RDTSC_DAG, dl, Tys, &TheChain, 1);
8763     SDValue eax = DAG.getCopyFromReg(rd, dl, X86::EAX, MVT::i32,
8764                                      rd.getValue(1));
8765     SDValue edx = DAG.getCopyFromReg(eax.getValue(1), dl, X86::EDX, MVT::i32,
8766                                      eax.getValue(2));
8767     // Use a buildpair to merge the two 32-bit values into a 64-bit one.
8768     SDValue Ops[] = { eax, edx };
8769     Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Ops, 2));
8770     Results.push_back(edx.getValue(1));
8771     return;
8772   }
8773   case ISD::ATOMIC_CMP_SWAP: {
8774     EVT T = N->getValueType(0);
8775     assert (T == MVT::i64 && "Only know how to expand i64 Cmp and Swap");
8776     SDValue cpInL, cpInH;
8777     cpInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(2),
8778                         DAG.getConstant(0, MVT::i32));
8779     cpInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(2),
8780                         DAG.getConstant(1, MVT::i32));
8781     cpInL = DAG.getCopyToReg(N->getOperand(0), dl, X86::EAX, cpInL, SDValue());
8782     cpInH = DAG.getCopyToReg(cpInL.getValue(0), dl, X86::EDX, cpInH,
8783                              cpInL.getValue(1));
8784     SDValue swapInL, swapInH;
8785     swapInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(3),
8786                           DAG.getConstant(0, MVT::i32));
8787     swapInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(3),
8788                           DAG.getConstant(1, MVT::i32));
8789     swapInL = DAG.getCopyToReg(cpInH.getValue(0), dl, X86::EBX, swapInL,
8790                                cpInH.getValue(1));
8791     swapInH = DAG.getCopyToReg(swapInL.getValue(0), dl, X86::ECX, swapInH,
8792                                swapInL.getValue(1));
8793     SDValue Ops[] = { swapInH.getValue(0),
8794                       N->getOperand(1),
8795                       swapInH.getValue(1) };
8796     SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Flag);
8797     MachineMemOperand *MMO = cast<AtomicSDNode>(N)->getMemOperand();
8798     SDValue Result = DAG.getMemIntrinsicNode(X86ISD::LCMPXCHG8_DAG, dl, Tys,
8799                                              Ops, 3, T, MMO);
8800     SDValue cpOutL = DAG.getCopyFromReg(Result.getValue(0), dl, X86::EAX,
8801                                         MVT::i32, Result.getValue(1));
8802     SDValue cpOutH = DAG.getCopyFromReg(cpOutL.getValue(1), dl, X86::EDX,
8803                                         MVT::i32, cpOutL.getValue(2));
8804     SDValue OpsF[] = { cpOutL.getValue(0), cpOutH.getValue(0)};
8805     Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, OpsF, 2));
8806     Results.push_back(cpOutH.getValue(1));
8807     return;
8808   }
8809   case ISD::ATOMIC_LOAD_ADD:
8810     ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMADD64_DAG);
8811     return;
8812   case ISD::ATOMIC_LOAD_AND:
8813     ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMAND64_DAG);
8814     return;
8815   case ISD::ATOMIC_LOAD_NAND:
8816     ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMNAND64_DAG);
8817     return;
8818   case ISD::ATOMIC_LOAD_OR:
8819     ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMOR64_DAG);
8820     return;
8821   case ISD::ATOMIC_LOAD_SUB:
8822     ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMSUB64_DAG);
8823     return;
8824   case ISD::ATOMIC_LOAD_XOR:
8825     ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMXOR64_DAG);
8826     return;
8827   case ISD::ATOMIC_SWAP:
8828     ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMSWAP64_DAG);
8829     return;
8830   }
8831 }
8832
8833 const char *X86TargetLowering::getTargetNodeName(unsigned Opcode) const {
8834   switch (Opcode) {
8835   default: return NULL;
8836   case X86ISD::BSF:                return "X86ISD::BSF";
8837   case X86ISD::BSR:                return "X86ISD::BSR";
8838   case X86ISD::SHLD:               return "X86ISD::SHLD";
8839   case X86ISD::SHRD:               return "X86ISD::SHRD";
8840   case X86ISD::FAND:               return "X86ISD::FAND";
8841   case X86ISD::FOR:                return "X86ISD::FOR";
8842   case X86ISD::FXOR:               return "X86ISD::FXOR";
8843   case X86ISD::FSRL:               return "X86ISD::FSRL";
8844   case X86ISD::FILD:               return "X86ISD::FILD";
8845   case X86ISD::FILD_FLAG:          return "X86ISD::FILD_FLAG";
8846   case X86ISD::FP_TO_INT16_IN_MEM: return "X86ISD::FP_TO_INT16_IN_MEM";
8847   case X86ISD::FP_TO_INT32_IN_MEM: return "X86ISD::FP_TO_INT32_IN_MEM";
8848   case X86ISD::FP_TO_INT64_IN_MEM: return "X86ISD::FP_TO_INT64_IN_MEM";
8849   case X86ISD::FLD:                return "X86ISD::FLD";
8850   case X86ISD::FST:                return "X86ISD::FST";
8851   case X86ISD::CALL:               return "X86ISD::CALL";
8852   case X86ISD::RDTSC_DAG:          return "X86ISD::RDTSC_DAG";
8853   case X86ISD::BT:                 return "X86ISD::BT";
8854   case X86ISD::CMP:                return "X86ISD::CMP";
8855   case X86ISD::COMI:               return "X86ISD::COMI";
8856   case X86ISD::UCOMI:              return "X86ISD::UCOMI";
8857   case X86ISD::SETCC:              return "X86ISD::SETCC";
8858   case X86ISD::SETCC_CARRY:        return "X86ISD::SETCC_CARRY";
8859   case X86ISD::CMOV:               return "X86ISD::CMOV";
8860   case X86ISD::BRCOND:             return "X86ISD::BRCOND";
8861   case X86ISD::RET_FLAG:           return "X86ISD::RET_FLAG";
8862   case X86ISD::REP_STOS:           return "X86ISD::REP_STOS";
8863   case X86ISD::REP_MOVS:           return "X86ISD::REP_MOVS";
8864   case X86ISD::GlobalBaseReg:      return "X86ISD::GlobalBaseReg";
8865   case X86ISD::Wrapper:            return "X86ISD::Wrapper";
8866   case X86ISD::WrapperRIP:         return "X86ISD::WrapperRIP";
8867   case X86ISD::PEXTRB:             return "X86ISD::PEXTRB";
8868   case X86ISD::PEXTRW:             return "X86ISD::PEXTRW";
8869   case X86ISD::INSERTPS:           return "X86ISD::INSERTPS";
8870   case X86ISD::PINSRB:             return "X86ISD::PINSRB";
8871   case X86ISD::PINSRW:             return "X86ISD::PINSRW";
8872   case X86ISD::PSHUFB:             return "X86ISD::PSHUFB";
8873   case X86ISD::PANDN:              return "X86ISD::PANDN";
8874   case X86ISD::PSIGNB:             return "X86ISD::PSIGNB";
8875   case X86ISD::PSIGNW:             return "X86ISD::PSIGNW";
8876   case X86ISD::PSIGND:             return "X86ISD::PSIGND";
8877   case X86ISD::FMAX:               return "X86ISD::FMAX";
8878   case X86ISD::FMIN:               return "X86ISD::FMIN";
8879   case X86ISD::FRSQRT:             return "X86ISD::FRSQRT";
8880   case X86ISD::FRCP:               return "X86ISD::FRCP";
8881   case X86ISD::TLSADDR:            return "X86ISD::TLSADDR";
8882   case X86ISD::TLSCALL:            return "X86ISD::TLSCALL";
8883   case X86ISD::EH_RETURN:          return "X86ISD::EH_RETURN";
8884   case X86ISD::TC_RETURN:          return "X86ISD::TC_RETURN";
8885   case X86ISD::FNSTCW16m:          return "X86ISD::FNSTCW16m";
8886   case X86ISD::LCMPXCHG_DAG:       return "X86ISD::LCMPXCHG_DAG";
8887   case X86ISD::LCMPXCHG8_DAG:      return "X86ISD::LCMPXCHG8_DAG";
8888   case X86ISD::ATOMADD64_DAG:      return "X86ISD::ATOMADD64_DAG";
8889   case X86ISD::ATOMSUB64_DAG:      return "X86ISD::ATOMSUB64_DAG";
8890   case X86ISD::ATOMOR64_DAG:       return "X86ISD::ATOMOR64_DAG";
8891   case X86ISD::ATOMXOR64_DAG:      return "X86ISD::ATOMXOR64_DAG";
8892   case X86ISD::ATOMAND64_DAG:      return "X86ISD::ATOMAND64_DAG";
8893   case X86ISD::ATOMNAND64_DAG:     return "X86ISD::ATOMNAND64_DAG";
8894   case X86ISD::VZEXT_MOVL:         return "X86ISD::VZEXT_MOVL";
8895   case X86ISD::VZEXT_LOAD:         return "X86ISD::VZEXT_LOAD";
8896   case X86ISD::VSHL:               return "X86ISD::VSHL";
8897   case X86ISD::VSRL:               return "X86ISD::VSRL";
8898   case X86ISD::CMPPD:              return "X86ISD::CMPPD";
8899   case X86ISD::CMPPS:              return "X86ISD::CMPPS";
8900   case X86ISD::PCMPEQB:            return "X86ISD::PCMPEQB";
8901   case X86ISD::PCMPEQW:            return "X86ISD::PCMPEQW";
8902   case X86ISD::PCMPEQD:            return "X86ISD::PCMPEQD";
8903   case X86ISD::PCMPEQQ:            return "X86ISD::PCMPEQQ";
8904   case X86ISD::PCMPGTB:            return "X86ISD::PCMPGTB";
8905   case X86ISD::PCMPGTW:            return "X86ISD::PCMPGTW";
8906   case X86ISD::PCMPGTD:            return "X86ISD::PCMPGTD";
8907   case X86ISD::PCMPGTQ:            return "X86ISD::PCMPGTQ";
8908   case X86ISD::ADD:                return "X86ISD::ADD";
8909   case X86ISD::SUB:                return "X86ISD::SUB";
8910   case X86ISD::SMUL:               return "X86ISD::SMUL";
8911   case X86ISD::UMUL:               return "X86ISD::UMUL";
8912   case X86ISD::INC:                return "X86ISD::INC";
8913   case X86ISD::DEC:                return "X86ISD::DEC";
8914   case X86ISD::OR:                 return "X86ISD::OR";
8915   case X86ISD::XOR:                return "X86ISD::XOR";
8916   case X86ISD::AND:                return "X86ISD::AND";
8917   case X86ISD::MUL_IMM:            return "X86ISD::MUL_IMM";
8918   case X86ISD::PTEST:              return "X86ISD::PTEST";
8919   case X86ISD::TESTP:              return "X86ISD::TESTP";
8920   case X86ISD::PALIGN:             return "X86ISD::PALIGN";
8921   case X86ISD::PSHUFD:             return "X86ISD::PSHUFD";
8922   case X86ISD::PSHUFHW:            return "X86ISD::PSHUFHW";
8923   case X86ISD::PSHUFHW_LD:         return "X86ISD::PSHUFHW_LD";
8924   case X86ISD::PSHUFLW:            return "X86ISD::PSHUFLW";
8925   case X86ISD::PSHUFLW_LD:         return "X86ISD::PSHUFLW_LD";
8926   case X86ISD::SHUFPS:             return "X86ISD::SHUFPS";
8927   case X86ISD::SHUFPD:             return "X86ISD::SHUFPD";
8928   case X86ISD::MOVLHPS:            return "X86ISD::MOVLHPS";
8929   case X86ISD::MOVLHPD:            return "X86ISD::MOVLHPD";
8930   case X86ISD::MOVHLPS:            return "X86ISD::MOVHLPS";
8931   case X86ISD::MOVHLPD:            return "X86ISD::MOVHLPD";
8932   case X86ISD::MOVLPS:             return "X86ISD::MOVLPS";
8933   case X86ISD::MOVLPD:             return "X86ISD::MOVLPD";
8934   case X86ISD::MOVDDUP:            return "X86ISD::MOVDDUP";
8935   case X86ISD::MOVSHDUP:           return "X86ISD::MOVSHDUP";
8936   case X86ISD::MOVSLDUP:           return "X86ISD::MOVSLDUP";
8937   case X86ISD::MOVSHDUP_LD:        return "X86ISD::MOVSHDUP_LD";
8938   case X86ISD::MOVSLDUP_LD:        return "X86ISD::MOVSLDUP_LD";
8939   case X86ISD::MOVSD:              return "X86ISD::MOVSD";
8940   case X86ISD::MOVSS:              return "X86ISD::MOVSS";
8941   case X86ISD::UNPCKLPS:           return "X86ISD::UNPCKLPS";
8942   case X86ISD::UNPCKLPD:           return "X86ISD::UNPCKLPD";
8943   case X86ISD::UNPCKHPS:           return "X86ISD::UNPCKHPS";
8944   case X86ISD::UNPCKHPD:           return "X86ISD::UNPCKHPD";
8945   case X86ISD::PUNPCKLBW:          return "X86ISD::PUNPCKLBW";
8946   case X86ISD::PUNPCKLWD:          return "X86ISD::PUNPCKLWD";
8947   case X86ISD::PUNPCKLDQ:          return "X86ISD::PUNPCKLDQ";
8948   case X86ISD::PUNPCKLQDQ:         return "X86ISD::PUNPCKLQDQ";
8949   case X86ISD::PUNPCKHBW:          return "X86ISD::PUNPCKHBW";
8950   case X86ISD::PUNPCKHWD:          return "X86ISD::PUNPCKHWD";
8951   case X86ISD::PUNPCKHDQ:          return "X86ISD::PUNPCKHDQ";
8952   case X86ISD::PUNPCKHQDQ:         return "X86ISD::PUNPCKHQDQ";
8953   case X86ISD::VASTART_SAVE_XMM_REGS: return "X86ISD::VASTART_SAVE_XMM_REGS";
8954   case X86ISD::VAARG_64:           return "X86ISD::VAARG_64";
8955   case X86ISD::WIN_ALLOCA:         return "X86ISD::WIN_ALLOCA";
8956   }
8957 }
8958
8959 // isLegalAddressingMode - Return true if the addressing mode represented
8960 // by AM is legal for this target, for a load/store of the specified type.
8961 bool X86TargetLowering::isLegalAddressingMode(const AddrMode &AM,
8962                                               const Type *Ty) const {
8963   // X86 supports extremely general addressing modes.
8964   CodeModel::Model M = getTargetMachine().getCodeModel();
8965   Reloc::Model R = getTargetMachine().getRelocationModel();
8966
8967   // X86 allows a sign-extended 32-bit immediate field as a displacement.
8968   if (!X86::isOffsetSuitableForCodeModel(AM.BaseOffs, M, AM.BaseGV != NULL))
8969     return false;
8970
8971   if (AM.BaseGV) {
8972     unsigned GVFlags =
8973       Subtarget->ClassifyGlobalReference(AM.BaseGV, getTargetMachine());
8974
8975     // If a reference to this global requires an extra load, we can't fold it.
8976     if (isGlobalStubReference(GVFlags))
8977       return false;
8978
8979     // If BaseGV requires a register for the PIC base, we cannot also have a
8980     // BaseReg specified.
8981     if (AM.HasBaseReg && isGlobalRelativeToPICBase(GVFlags))
8982       return false;
8983
8984     // If lower 4G is not available, then we must use rip-relative addressing.
8985     if ((M != CodeModel::Small || R != Reloc::Static) &&
8986         Subtarget->is64Bit() && (AM.BaseOffs || AM.Scale > 1))
8987       return false;
8988   }
8989
8990   switch (AM.Scale) {
8991   case 0:
8992   case 1:
8993   case 2:
8994   case 4:
8995   case 8:
8996     // These scales always work.
8997     break;
8998   case 3:
8999   case 5:
9000   case 9:
9001     // These scales are formed with basereg+scalereg.  Only accept if there is
9002     // no basereg yet.
9003     if (AM.HasBaseReg)
9004       return false;
9005     break;
9006   default:  // Other stuff never works.
9007     return false;
9008   }
9009
9010   return true;
9011 }
9012
9013
9014 bool X86TargetLowering::isTruncateFree(const Type *Ty1, const Type *Ty2) const {
9015   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
9016     return false;
9017   unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
9018   unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
9019   if (NumBits1 <= NumBits2)
9020     return false;
9021   return true;
9022 }
9023
9024 bool X86TargetLowering::isTruncateFree(EVT VT1, EVT VT2) const {
9025   if (!VT1.isInteger() || !VT2.isInteger())
9026     return false;
9027   unsigned NumBits1 = VT1.getSizeInBits();
9028   unsigned NumBits2 = VT2.getSizeInBits();
9029   if (NumBits1 <= NumBits2)
9030     return false;
9031   return true;
9032 }
9033
9034 bool X86TargetLowering::isZExtFree(const Type *Ty1, const Type *Ty2) const {
9035   // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
9036   return Ty1->isIntegerTy(32) && Ty2->isIntegerTy(64) && Subtarget->is64Bit();
9037 }
9038
9039 bool X86TargetLowering::isZExtFree(EVT VT1, EVT VT2) const {
9040   // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
9041   return VT1 == MVT::i32 && VT2 == MVT::i64 && Subtarget->is64Bit();
9042 }
9043
9044 bool X86TargetLowering::isNarrowingProfitable(EVT VT1, EVT VT2) const {
9045   // i16 instructions are longer (0x66 prefix) and potentially slower.
9046   return !(VT1 == MVT::i32 && VT2 == MVT::i16);
9047 }
9048
9049 /// isShuffleMaskLegal - Targets can use this to indicate that they only
9050 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
9051 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
9052 /// are assumed to be legal.
9053 bool
9054 X86TargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M,
9055                                       EVT VT) const {
9056   // Very little shuffling can be done for 64-bit vectors right now.
9057   if (VT.getSizeInBits() == 64)
9058     return isPALIGNRMask(M, VT, Subtarget->hasSSSE3());
9059
9060   // FIXME: pshufb, blends, shifts.
9061   return (VT.getVectorNumElements() == 2 ||
9062           ShuffleVectorSDNode::isSplatMask(&M[0], VT) ||
9063           isMOVLMask(M, VT) ||
9064           isSHUFPMask(M, VT) ||
9065           isPSHUFDMask(M, VT) ||
9066           isPSHUFHWMask(M, VT) ||
9067           isPSHUFLWMask(M, VT) ||
9068           isPALIGNRMask(M, VT, Subtarget->hasSSSE3()) ||
9069           isUNPCKLMask(M, VT) ||
9070           isUNPCKHMask(M, VT) ||
9071           isUNPCKL_v_undef_Mask(M, VT) ||
9072           isUNPCKH_v_undef_Mask(M, VT));
9073 }
9074
9075 bool
9076 X86TargetLowering::isVectorClearMaskLegal(const SmallVectorImpl<int> &Mask,
9077                                           EVT VT) const {
9078   unsigned NumElts = VT.getVectorNumElements();
9079   // FIXME: This collection of masks seems suspect.
9080   if (NumElts == 2)
9081     return true;
9082   if (NumElts == 4 && VT.getSizeInBits() == 128) {
9083     return (isMOVLMask(Mask, VT)  ||
9084             isCommutedMOVLMask(Mask, VT, true) ||
9085             isSHUFPMask(Mask, VT) ||
9086             isCommutedSHUFPMask(Mask, VT));
9087   }
9088   return false;
9089 }
9090
9091 //===----------------------------------------------------------------------===//
9092 //                           X86 Scheduler Hooks
9093 //===----------------------------------------------------------------------===//
9094
9095 // private utility function
9096 MachineBasicBlock *
9097 X86TargetLowering::EmitAtomicBitwiseWithCustomInserter(MachineInstr *bInstr,
9098                                                        MachineBasicBlock *MBB,
9099                                                        unsigned regOpc,
9100                                                        unsigned immOpc,
9101                                                        unsigned LoadOpc,
9102                                                        unsigned CXchgOpc,
9103                                                        unsigned notOpc,
9104                                                        unsigned EAXreg,
9105                                                        TargetRegisterClass *RC,
9106                                                        bool invSrc) const {
9107   // For the atomic bitwise operator, we generate
9108   //   thisMBB:
9109   //   newMBB:
9110   //     ld  t1 = [bitinstr.addr]
9111   //     op  t2 = t1, [bitinstr.val]
9112   //     mov EAX = t1
9113   //     lcs dest = [bitinstr.addr], t2  [EAX is implicit]
9114   //     bz  newMBB
9115   //     fallthrough -->nextMBB
9116   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
9117   const BasicBlock *LLVM_BB = MBB->getBasicBlock();
9118   MachineFunction::iterator MBBIter = MBB;
9119   ++MBBIter;
9120
9121   /// First build the CFG
9122   MachineFunction *F = MBB->getParent();
9123   MachineBasicBlock *thisMBB = MBB;
9124   MachineBasicBlock *newMBB = F->CreateMachineBasicBlock(LLVM_BB);
9125   MachineBasicBlock *nextMBB = F->CreateMachineBasicBlock(LLVM_BB);
9126   F->insert(MBBIter, newMBB);
9127   F->insert(MBBIter, nextMBB);
9128
9129   // Transfer the remainder of thisMBB and its successor edges to nextMBB.
9130   nextMBB->splice(nextMBB->begin(), thisMBB,
9131                   llvm::next(MachineBasicBlock::iterator(bInstr)),
9132                   thisMBB->end());
9133   nextMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
9134
9135   // Update thisMBB to fall through to newMBB
9136   thisMBB->addSuccessor(newMBB);
9137
9138   // newMBB jumps to itself and fall through to nextMBB
9139   newMBB->addSuccessor(nextMBB);
9140   newMBB->addSuccessor(newMBB);
9141
9142   // Insert instructions into newMBB based on incoming instruction
9143   assert(bInstr->getNumOperands() < X86::AddrNumOperands + 4 &&
9144          "unexpected number of operands");
9145   DebugLoc dl = bInstr->getDebugLoc();
9146   MachineOperand& destOper = bInstr->getOperand(0);
9147   MachineOperand* argOpers[2 + X86::AddrNumOperands];
9148   int numArgs = bInstr->getNumOperands() - 1;
9149   for (int i=0; i < numArgs; ++i)
9150     argOpers[i] = &bInstr->getOperand(i+1);
9151
9152   // x86 address has 4 operands: base, index, scale, and displacement
9153   int lastAddrIndx = X86::AddrNumOperands - 1; // [0,3]
9154   int valArgIndx = lastAddrIndx + 1;
9155
9156   unsigned t1 = F->getRegInfo().createVirtualRegister(RC);
9157   MachineInstrBuilder MIB = BuildMI(newMBB, dl, TII->get(LoadOpc), t1);
9158   for (int i=0; i <= lastAddrIndx; ++i)
9159     (*MIB).addOperand(*argOpers[i]);
9160
9161   unsigned tt = F->getRegInfo().createVirtualRegister(RC);
9162   if (invSrc) {
9163     MIB = BuildMI(newMBB, dl, TII->get(notOpc), tt).addReg(t1);
9164   }
9165   else
9166     tt = t1;
9167
9168   unsigned t2 = F->getRegInfo().createVirtualRegister(RC);
9169   assert((argOpers[valArgIndx]->isReg() ||
9170           argOpers[valArgIndx]->isImm()) &&
9171          "invalid operand");
9172   if (argOpers[valArgIndx]->isReg())
9173     MIB = BuildMI(newMBB, dl, TII->get(regOpc), t2);
9174   else
9175     MIB = BuildMI(newMBB, dl, TII->get(immOpc), t2);
9176   MIB.addReg(tt);
9177   (*MIB).addOperand(*argOpers[valArgIndx]);
9178
9179   MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), EAXreg);
9180   MIB.addReg(t1);
9181
9182   MIB = BuildMI(newMBB, dl, TII->get(CXchgOpc));
9183   for (int i=0; i <= lastAddrIndx; ++i)
9184     (*MIB).addOperand(*argOpers[i]);
9185   MIB.addReg(t2);
9186   assert(bInstr->hasOneMemOperand() && "Unexpected number of memoperand");
9187   (*MIB).setMemRefs(bInstr->memoperands_begin(),
9188                     bInstr->memoperands_end());
9189
9190   MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), destOper.getReg());
9191   MIB.addReg(EAXreg);
9192
9193   // insert branch
9194   BuildMI(newMBB, dl, TII->get(X86::JNE_4)).addMBB(newMBB);
9195
9196   bInstr->eraseFromParent();   // The pseudo instruction is gone now.
9197   return nextMBB;
9198 }
9199
9200 // private utility function:  64 bit atomics on 32 bit host.
9201 MachineBasicBlock *
9202 X86TargetLowering::EmitAtomicBit6432WithCustomInserter(MachineInstr *bInstr,
9203                                                        MachineBasicBlock *MBB,
9204                                                        unsigned regOpcL,
9205                                                        unsigned regOpcH,
9206                                                        unsigned immOpcL,
9207                                                        unsigned immOpcH,
9208                                                        bool invSrc) const {
9209   // For the atomic bitwise operator, we generate
9210   //   thisMBB (instructions are in pairs, except cmpxchg8b)
9211   //     ld t1,t2 = [bitinstr.addr]
9212   //   newMBB:
9213   //     out1, out2 = phi (thisMBB, t1/t2) (newMBB, t3/t4)
9214   //     op  t5, t6 <- out1, out2, [bitinstr.val]
9215   //      (for SWAP, substitute:  mov t5, t6 <- [bitinstr.val])
9216   //     mov ECX, EBX <- t5, t6
9217   //     mov EAX, EDX <- t1, t2
9218   //     cmpxchg8b [bitinstr.addr]  [EAX, EDX, EBX, ECX implicit]
9219   //     mov t3, t4 <- EAX, EDX
9220   //     bz  newMBB
9221   //     result in out1, out2
9222   //     fallthrough -->nextMBB
9223
9224   const TargetRegisterClass *RC = X86::GR32RegisterClass;
9225   const unsigned LoadOpc = X86::MOV32rm;
9226   const unsigned NotOpc = X86::NOT32r;
9227   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
9228   const BasicBlock *LLVM_BB = MBB->getBasicBlock();
9229   MachineFunction::iterator MBBIter = MBB;
9230   ++MBBIter;
9231
9232   /// First build the CFG
9233   MachineFunction *F = MBB->getParent();
9234   MachineBasicBlock *thisMBB = MBB;
9235   MachineBasicBlock *newMBB = F->CreateMachineBasicBlock(LLVM_BB);
9236   MachineBasicBlock *nextMBB = F->CreateMachineBasicBlock(LLVM_BB);
9237   F->insert(MBBIter, newMBB);
9238   F->insert(MBBIter, nextMBB);
9239
9240   // Transfer the remainder of thisMBB and its successor edges to nextMBB.
9241   nextMBB->splice(nextMBB->begin(), thisMBB,
9242                   llvm::next(MachineBasicBlock::iterator(bInstr)),
9243                   thisMBB->end());
9244   nextMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
9245
9246   // Update thisMBB to fall through to newMBB
9247   thisMBB->addSuccessor(newMBB);
9248
9249   // newMBB jumps to itself and fall through to nextMBB
9250   newMBB->addSuccessor(nextMBB);
9251   newMBB->addSuccessor(newMBB);
9252
9253   DebugLoc dl = bInstr->getDebugLoc();
9254   // Insert instructions into newMBB based on incoming instruction
9255   // There are 8 "real" operands plus 9 implicit def/uses, ignored here.
9256   assert(bInstr->getNumOperands() < X86::AddrNumOperands + 14 &&
9257          "unexpected number of operands");
9258   MachineOperand& dest1Oper = bInstr->getOperand(0);
9259   MachineOperand& dest2Oper = bInstr->getOperand(1);
9260   MachineOperand* argOpers[2 + X86::AddrNumOperands];
9261   for (int i=0; i < 2 + X86::AddrNumOperands; ++i) {
9262     argOpers[i] = &bInstr->getOperand(i+2);
9263
9264     // We use some of the operands multiple times, so conservatively just
9265     // clear any kill flags that might be present.
9266     if (argOpers[i]->isReg() && argOpers[i]->isUse())
9267       argOpers[i]->setIsKill(false);
9268   }
9269
9270   // x86 address has 5 operands: base, index, scale, displacement, and segment.
9271   int lastAddrIndx = X86::AddrNumOperands - 1; // [0,3]
9272
9273   unsigned t1 = F->getRegInfo().createVirtualRegister(RC);
9274   MachineInstrBuilder MIB = BuildMI(thisMBB, dl, TII->get(LoadOpc), t1);
9275   for (int i=0; i <= lastAddrIndx; ++i)
9276     (*MIB).addOperand(*argOpers[i]);
9277   unsigned t2 = F->getRegInfo().createVirtualRegister(RC);
9278   MIB = BuildMI(thisMBB, dl, TII->get(LoadOpc), t2);
9279   // add 4 to displacement.
9280   for (int i=0; i <= lastAddrIndx-2; ++i)
9281     (*MIB).addOperand(*argOpers[i]);
9282   MachineOperand newOp3 = *(argOpers[3]);
9283   if (newOp3.isImm())
9284     newOp3.setImm(newOp3.getImm()+4);
9285   else
9286     newOp3.setOffset(newOp3.getOffset()+4);
9287   (*MIB).addOperand(newOp3);
9288   (*MIB).addOperand(*argOpers[lastAddrIndx]);
9289
9290   // t3/4 are defined later, at the bottom of the loop
9291   unsigned t3 = F->getRegInfo().createVirtualRegister(RC);
9292   unsigned t4 = F->getRegInfo().createVirtualRegister(RC);
9293   BuildMI(newMBB, dl, TII->get(X86::PHI), dest1Oper.getReg())
9294     .addReg(t1).addMBB(thisMBB).addReg(t3).addMBB(newMBB);
9295   BuildMI(newMBB, dl, TII->get(X86::PHI), dest2Oper.getReg())
9296     .addReg(t2).addMBB(thisMBB).addReg(t4).addMBB(newMBB);
9297
9298   // The subsequent operations should be using the destination registers of
9299   //the PHI instructions.
9300   if (invSrc) {
9301     t1 = F->getRegInfo().createVirtualRegister(RC);
9302     t2 = F->getRegInfo().createVirtualRegister(RC);
9303     MIB = BuildMI(newMBB, dl, TII->get(NotOpc), t1).addReg(dest1Oper.getReg());
9304     MIB = BuildMI(newMBB, dl, TII->get(NotOpc), t2).addReg(dest2Oper.getReg());
9305   } else {
9306     t1 = dest1Oper.getReg();
9307     t2 = dest2Oper.getReg();
9308   }
9309
9310   int valArgIndx = lastAddrIndx + 1;
9311   assert((argOpers[valArgIndx]->isReg() ||
9312           argOpers[valArgIndx]->isImm()) &&
9313          "invalid operand");
9314   unsigned t5 = F->getRegInfo().createVirtualRegister(RC);
9315   unsigned t6 = F->getRegInfo().createVirtualRegister(RC);
9316   if (argOpers[valArgIndx]->isReg())
9317     MIB = BuildMI(newMBB, dl, TII->get(regOpcL), t5);
9318   else
9319     MIB = BuildMI(newMBB, dl, TII->get(immOpcL), t5);
9320   if (regOpcL != X86::MOV32rr)
9321     MIB.addReg(t1);
9322   (*MIB).addOperand(*argOpers[valArgIndx]);
9323   assert(argOpers[valArgIndx + 1]->isReg() ==
9324          argOpers[valArgIndx]->isReg());
9325   assert(argOpers[valArgIndx + 1]->isImm() ==
9326          argOpers[valArgIndx]->isImm());
9327   if (argOpers[valArgIndx + 1]->isReg())
9328     MIB = BuildMI(newMBB, dl, TII->get(regOpcH), t6);
9329   else
9330     MIB = BuildMI(newMBB, dl, TII->get(immOpcH), t6);
9331   if (regOpcH != X86::MOV32rr)
9332     MIB.addReg(t2);
9333   (*MIB).addOperand(*argOpers[valArgIndx + 1]);
9334
9335   MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), X86::EAX);
9336   MIB.addReg(t1);
9337   MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), X86::EDX);
9338   MIB.addReg(t2);
9339
9340   MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), X86::EBX);
9341   MIB.addReg(t5);
9342   MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), X86::ECX);
9343   MIB.addReg(t6);
9344
9345   MIB = BuildMI(newMBB, dl, TII->get(X86::LCMPXCHG8B));
9346   for (int i=0; i <= lastAddrIndx; ++i)
9347     (*MIB).addOperand(*argOpers[i]);
9348
9349   assert(bInstr->hasOneMemOperand() && "Unexpected number of memoperand");
9350   (*MIB).setMemRefs(bInstr->memoperands_begin(),
9351                     bInstr->memoperands_end());
9352
9353   MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), t3);
9354   MIB.addReg(X86::EAX);
9355   MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), t4);
9356   MIB.addReg(X86::EDX);
9357
9358   // insert branch
9359   BuildMI(newMBB, dl, TII->get(X86::JNE_4)).addMBB(newMBB);
9360
9361   bInstr->eraseFromParent();   // The pseudo instruction is gone now.
9362   return nextMBB;
9363 }
9364
9365 // private utility function
9366 MachineBasicBlock *
9367 X86TargetLowering::EmitAtomicMinMaxWithCustomInserter(MachineInstr *mInstr,
9368                                                       MachineBasicBlock *MBB,
9369                                                       unsigned cmovOpc) const {
9370   // For the atomic min/max operator, we generate
9371   //   thisMBB:
9372   //   newMBB:
9373   //     ld t1 = [min/max.addr]
9374   //     mov t2 = [min/max.val]
9375   //     cmp  t1, t2
9376   //     cmov[cond] t2 = t1
9377   //     mov EAX = t1
9378   //     lcs dest = [bitinstr.addr], t2  [EAX is implicit]
9379   //     bz   newMBB
9380   //     fallthrough -->nextMBB
9381   //
9382   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
9383   const BasicBlock *LLVM_BB = MBB->getBasicBlock();
9384   MachineFunction::iterator MBBIter = MBB;
9385   ++MBBIter;
9386
9387   /// First build the CFG
9388   MachineFunction *F = MBB->getParent();
9389   MachineBasicBlock *thisMBB = MBB;
9390   MachineBasicBlock *newMBB = F->CreateMachineBasicBlock(LLVM_BB);
9391   MachineBasicBlock *nextMBB = F->CreateMachineBasicBlock(LLVM_BB);
9392   F->insert(MBBIter, newMBB);
9393   F->insert(MBBIter, nextMBB);
9394
9395   // Transfer the remainder of thisMBB and its successor edges to nextMBB.
9396   nextMBB->splice(nextMBB->begin(), thisMBB,
9397                   llvm::next(MachineBasicBlock::iterator(mInstr)),
9398                   thisMBB->end());
9399   nextMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
9400
9401   // Update thisMBB to fall through to newMBB
9402   thisMBB->addSuccessor(newMBB);
9403
9404   // newMBB jumps to newMBB and fall through to nextMBB
9405   newMBB->addSuccessor(nextMBB);
9406   newMBB->addSuccessor(newMBB);
9407
9408   DebugLoc dl = mInstr->getDebugLoc();
9409   // Insert instructions into newMBB based on incoming instruction
9410   assert(mInstr->getNumOperands() < X86::AddrNumOperands + 4 &&
9411          "unexpected number of operands");
9412   MachineOperand& destOper = mInstr->getOperand(0);
9413   MachineOperand* argOpers[2 + X86::AddrNumOperands];
9414   int numArgs = mInstr->getNumOperands() - 1;
9415   for (int i=0; i < numArgs; ++i)
9416     argOpers[i] = &mInstr->getOperand(i+1);
9417
9418   // x86 address has 4 operands: base, index, scale, and displacement
9419   int lastAddrIndx = X86::AddrNumOperands - 1; // [0,3]
9420   int valArgIndx = lastAddrIndx + 1;
9421
9422   unsigned t1 = F->getRegInfo().createVirtualRegister(X86::GR32RegisterClass);
9423   MachineInstrBuilder MIB = BuildMI(newMBB, dl, TII->get(X86::MOV32rm), t1);
9424   for (int i=0; i <= lastAddrIndx; ++i)
9425     (*MIB).addOperand(*argOpers[i]);
9426
9427   // We only support register and immediate values
9428   assert((argOpers[valArgIndx]->isReg() ||
9429           argOpers[valArgIndx]->isImm()) &&
9430          "invalid operand");
9431
9432   unsigned t2 = F->getRegInfo().createVirtualRegister(X86::GR32RegisterClass);
9433   if (argOpers[valArgIndx]->isReg())
9434     MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), t2);
9435   else
9436     MIB = BuildMI(newMBB, dl, TII->get(X86::MOV32rr), t2);
9437   (*MIB).addOperand(*argOpers[valArgIndx]);
9438
9439   MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), X86::EAX);
9440   MIB.addReg(t1);
9441
9442   MIB = BuildMI(newMBB, dl, TII->get(X86::CMP32rr));
9443   MIB.addReg(t1);
9444   MIB.addReg(t2);
9445
9446   // Generate movc
9447   unsigned t3 = F->getRegInfo().createVirtualRegister(X86::GR32RegisterClass);
9448   MIB = BuildMI(newMBB, dl, TII->get(cmovOpc),t3);
9449   MIB.addReg(t2);
9450   MIB.addReg(t1);
9451
9452   // Cmp and exchange if none has modified the memory location
9453   MIB = BuildMI(newMBB, dl, TII->get(X86::LCMPXCHG32));
9454   for (int i=0; i <= lastAddrIndx; ++i)
9455     (*MIB).addOperand(*argOpers[i]);
9456   MIB.addReg(t3);
9457   assert(mInstr->hasOneMemOperand() && "Unexpected number of memoperand");
9458   (*MIB).setMemRefs(mInstr->memoperands_begin(),
9459                     mInstr->memoperands_end());
9460
9461   MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), destOper.getReg());
9462   MIB.addReg(X86::EAX);
9463
9464   // insert branch
9465   BuildMI(newMBB, dl, TII->get(X86::JNE_4)).addMBB(newMBB);
9466
9467   mInstr->eraseFromParent();   // The pseudo instruction is gone now.
9468   return nextMBB;
9469 }
9470
9471 // FIXME: When we get size specific XMM0 registers, i.e. XMM0_V16I8
9472 // or XMM0_V32I8 in AVX all of this code can be replaced with that
9473 // in the .td file.
9474 MachineBasicBlock *
9475 X86TargetLowering::EmitPCMP(MachineInstr *MI, MachineBasicBlock *BB,
9476                             unsigned numArgs, bool memArg) const {
9477   assert((Subtarget->hasSSE42() || Subtarget->hasAVX()) &&
9478          "Target must have SSE4.2 or AVX features enabled");
9479
9480   DebugLoc dl = MI->getDebugLoc();
9481   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
9482   unsigned Opc;
9483   if (!Subtarget->hasAVX()) {
9484     if (memArg)
9485       Opc = numArgs == 3 ? X86::PCMPISTRM128rm : X86::PCMPESTRM128rm;
9486     else
9487       Opc = numArgs == 3 ? X86::PCMPISTRM128rr : X86::PCMPESTRM128rr;
9488   } else {
9489     if (memArg)
9490       Opc = numArgs == 3 ? X86::VPCMPISTRM128rm : X86::VPCMPESTRM128rm;
9491     else
9492       Opc = numArgs == 3 ? X86::VPCMPISTRM128rr : X86::VPCMPESTRM128rr;
9493   }
9494
9495   MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(Opc));
9496   for (unsigned i = 0; i < numArgs; ++i) {
9497     MachineOperand &Op = MI->getOperand(i+1);
9498     if (!(Op.isReg() && Op.isImplicit()))
9499       MIB.addOperand(Op);
9500   }
9501   BuildMI(*BB, MI, dl, TII->get(X86::MOVAPSrr), MI->getOperand(0).getReg())
9502     .addReg(X86::XMM0);
9503
9504   MI->eraseFromParent();
9505   return BB;
9506 }
9507
9508 MachineBasicBlock *
9509 X86TargetLowering::EmitMonitor(MachineInstr *MI, MachineBasicBlock *BB) const {
9510   DebugLoc dl = MI->getDebugLoc();
9511   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
9512   
9513   // Address into RAX/EAX, other two args into ECX, EDX.
9514   unsigned MemOpc = Subtarget->is64Bit() ? X86::LEA64r : X86::LEA32r;
9515   unsigned MemReg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
9516   MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(MemOpc), MemReg);
9517   for (int i = 0; i < X86::AddrNumOperands; ++i)
9518     MIB.addOperand(MI->getOperand(i));
9519   
9520   unsigned ValOps = X86::AddrNumOperands;
9521   BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::ECX)
9522     .addReg(MI->getOperand(ValOps).getReg());
9523   BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::EDX)
9524     .addReg(MI->getOperand(ValOps+1).getReg());
9525
9526   // The instruction doesn't actually take any operands though.
9527   BuildMI(*BB, MI, dl, TII->get(X86::MONITORrrr));
9528   
9529   MI->eraseFromParent(); // The pseudo is gone now.
9530   return BB;
9531 }
9532
9533 MachineBasicBlock *
9534 X86TargetLowering::EmitMwait(MachineInstr *MI, MachineBasicBlock *BB) const {
9535   DebugLoc dl = MI->getDebugLoc();
9536   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
9537   
9538   // First arg in ECX, the second in EAX.
9539   BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::ECX)
9540     .addReg(MI->getOperand(0).getReg());
9541   BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::EAX)
9542     .addReg(MI->getOperand(1).getReg());
9543     
9544   // The instruction doesn't actually take any operands though.
9545   BuildMI(*BB, MI, dl, TII->get(X86::MWAITrr));
9546   
9547   MI->eraseFromParent(); // The pseudo is gone now.
9548   return BB;
9549 }
9550
9551 MachineBasicBlock *
9552 X86TargetLowering::EmitVAARG64WithCustomInserter(
9553                    MachineInstr *MI,
9554                    MachineBasicBlock *MBB) const {
9555   // Emit va_arg instruction on X86-64.
9556
9557   // Operands to this pseudo-instruction:
9558   // 0  ) Output        : destination address (reg)
9559   // 1-5) Input         : va_list address (addr, i64mem)
9560   // 6  ) ArgSize       : Size (in bytes) of vararg type
9561   // 7  ) ArgMode       : 0=overflow only, 1=use gp_offset, 2=use fp_offset
9562   // 8  ) Align         : Alignment of type
9563   // 9  ) EFLAGS (implicit-def)
9564
9565   assert(MI->getNumOperands() == 10 && "VAARG_64 should have 10 operands!");
9566   assert(X86::AddrNumOperands == 5 && "VAARG_64 assumes 5 address operands");
9567
9568   unsigned DestReg = MI->getOperand(0).getReg();
9569   MachineOperand &Base = MI->getOperand(1);
9570   MachineOperand &Scale = MI->getOperand(2);
9571   MachineOperand &Index = MI->getOperand(3);
9572   MachineOperand &Disp = MI->getOperand(4);
9573   MachineOperand &Segment = MI->getOperand(5);
9574   unsigned ArgSize = MI->getOperand(6).getImm();
9575   unsigned ArgMode = MI->getOperand(7).getImm();
9576   unsigned Align = MI->getOperand(8).getImm();
9577
9578   // Memory Reference
9579   assert(MI->hasOneMemOperand() && "Expected VAARG_64 to have one memoperand");
9580   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
9581   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
9582
9583   // Machine Information
9584   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
9585   MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo();
9586   const TargetRegisterClass *AddrRegClass = getRegClassFor(MVT::i64);
9587   const TargetRegisterClass *OffsetRegClass = getRegClassFor(MVT::i32);
9588   DebugLoc DL = MI->getDebugLoc();
9589
9590   // struct va_list {
9591   //   i32   gp_offset
9592   //   i32   fp_offset
9593   //   i64   overflow_area (address)
9594   //   i64   reg_save_area (address)
9595   // }
9596   // sizeof(va_list) = 24
9597   // alignment(va_list) = 8
9598
9599   unsigned TotalNumIntRegs = 6;
9600   unsigned TotalNumXMMRegs = 8;
9601   bool UseGPOffset = (ArgMode == 1);
9602   bool UseFPOffset = (ArgMode == 2);
9603   unsigned MaxOffset = TotalNumIntRegs * 8 +
9604                        (UseFPOffset ? TotalNumXMMRegs * 16 : 0);
9605
9606   /* Align ArgSize to a multiple of 8 */
9607   unsigned ArgSizeA8 = (ArgSize + 7) & ~7;
9608   bool NeedsAlign = (Align > 8);
9609
9610   MachineBasicBlock *thisMBB = MBB;
9611   MachineBasicBlock *overflowMBB;
9612   MachineBasicBlock *offsetMBB;
9613   MachineBasicBlock *endMBB;
9614
9615   unsigned OffsetDestReg = 0;    // Argument address computed by offsetMBB
9616   unsigned OverflowDestReg = 0;  // Argument address computed by overflowMBB
9617   unsigned OffsetReg = 0;
9618
9619   if (!UseGPOffset && !UseFPOffset) {
9620     // If we only pull from the overflow region, we don't create a branch.
9621     // We don't need to alter control flow.
9622     OffsetDestReg = 0; // unused
9623     OverflowDestReg = DestReg;
9624
9625     offsetMBB = NULL;
9626     overflowMBB = thisMBB;
9627     endMBB = thisMBB;
9628   } else {
9629     // First emit code to check if gp_offset (or fp_offset) is below the bound.
9630     // If so, pull the argument from reg_save_area. (branch to offsetMBB)
9631     // If not, pull from overflow_area. (branch to overflowMBB)
9632     //
9633     //       thisMBB
9634     //         |     .
9635     //         |        .
9636     //     offsetMBB   overflowMBB
9637     //         |        .
9638     //         |     .
9639     //        endMBB
9640
9641     // Registers for the PHI in endMBB
9642     OffsetDestReg = MRI.createVirtualRegister(AddrRegClass);
9643     OverflowDestReg = MRI.createVirtualRegister(AddrRegClass);
9644
9645     const BasicBlock *LLVM_BB = MBB->getBasicBlock();
9646     MachineFunction *MF = MBB->getParent();
9647     overflowMBB = MF->CreateMachineBasicBlock(LLVM_BB);
9648     offsetMBB = MF->CreateMachineBasicBlock(LLVM_BB);
9649     endMBB = MF->CreateMachineBasicBlock(LLVM_BB);
9650
9651     MachineFunction::iterator MBBIter = MBB;
9652     ++MBBIter;
9653
9654     // Insert the new basic blocks
9655     MF->insert(MBBIter, offsetMBB);
9656     MF->insert(MBBIter, overflowMBB);
9657     MF->insert(MBBIter, endMBB);
9658
9659     // Transfer the remainder of MBB and its successor edges to endMBB.
9660     endMBB->splice(endMBB->begin(), thisMBB,
9661                     llvm::next(MachineBasicBlock::iterator(MI)),
9662                     thisMBB->end());
9663     endMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
9664
9665     // Make offsetMBB and overflowMBB successors of thisMBB
9666     thisMBB->addSuccessor(offsetMBB);
9667     thisMBB->addSuccessor(overflowMBB);
9668
9669     // endMBB is a successor of both offsetMBB and overflowMBB
9670     offsetMBB->addSuccessor(endMBB);
9671     overflowMBB->addSuccessor(endMBB);
9672
9673     // Load the offset value into a register
9674     OffsetReg = MRI.createVirtualRegister(OffsetRegClass);
9675     BuildMI(thisMBB, DL, TII->get(X86::MOV32rm), OffsetReg)
9676       .addOperand(Base)
9677       .addOperand(Scale)
9678       .addOperand(Index)
9679       .addDisp(Disp, UseFPOffset ? 4 : 0)
9680       .addOperand(Segment)
9681       .setMemRefs(MMOBegin, MMOEnd);
9682
9683     // Check if there is enough room left to pull this argument.
9684     BuildMI(thisMBB, DL, TII->get(X86::CMP32ri))
9685       .addReg(OffsetReg)
9686       .addImm(MaxOffset + 8 - ArgSizeA8);
9687
9688     // Branch to "overflowMBB" if offset >= max
9689     // Fall through to "offsetMBB" otherwise
9690     BuildMI(thisMBB, DL, TII->get(X86::GetCondBranchFromCond(X86::COND_AE)))
9691       .addMBB(overflowMBB);
9692   }
9693
9694   // In offsetMBB, emit code to use the reg_save_area.
9695   if (offsetMBB) {
9696     assert(OffsetReg != 0);
9697
9698     // Read the reg_save_area address.
9699     unsigned RegSaveReg = MRI.createVirtualRegister(AddrRegClass);
9700     BuildMI(offsetMBB, DL, TII->get(X86::MOV64rm), RegSaveReg)
9701       .addOperand(Base)
9702       .addOperand(Scale)
9703       .addOperand(Index)
9704       .addDisp(Disp, 16)
9705       .addOperand(Segment)
9706       .setMemRefs(MMOBegin, MMOEnd);
9707
9708     // Zero-extend the offset
9709     unsigned OffsetReg64 = MRI.createVirtualRegister(AddrRegClass);
9710       BuildMI(offsetMBB, DL, TII->get(X86::SUBREG_TO_REG), OffsetReg64)
9711         .addImm(0)
9712         .addReg(OffsetReg)
9713         .addImm(X86::sub_32bit);
9714
9715     // Add the offset to the reg_save_area to get the final address.
9716     BuildMI(offsetMBB, DL, TII->get(X86::ADD64rr), OffsetDestReg)
9717       .addReg(OffsetReg64)
9718       .addReg(RegSaveReg);
9719
9720     // Compute the offset for the next argument
9721     unsigned NextOffsetReg = MRI.createVirtualRegister(OffsetRegClass);
9722     BuildMI(offsetMBB, DL, TII->get(X86::ADD32ri), NextOffsetReg)
9723       .addReg(OffsetReg)
9724       .addImm(UseFPOffset ? 16 : 8);
9725
9726     // Store it back into the va_list.
9727     BuildMI(offsetMBB, DL, TII->get(X86::MOV32mr))
9728       .addOperand(Base)
9729       .addOperand(Scale)
9730       .addOperand(Index)
9731       .addDisp(Disp, UseFPOffset ? 4 : 0)
9732       .addOperand(Segment)
9733       .addReg(NextOffsetReg)
9734       .setMemRefs(MMOBegin, MMOEnd);
9735
9736     // Jump to endMBB
9737     BuildMI(offsetMBB, DL, TII->get(X86::JMP_4))
9738       .addMBB(endMBB);
9739   }
9740
9741   //
9742   // Emit code to use overflow area
9743   //
9744
9745   // Load the overflow_area address into a register.
9746   unsigned OverflowAddrReg = MRI.createVirtualRegister(AddrRegClass);
9747   BuildMI(overflowMBB, DL, TII->get(X86::MOV64rm), OverflowAddrReg)
9748     .addOperand(Base)
9749     .addOperand(Scale)
9750     .addOperand(Index)
9751     .addDisp(Disp, 8)
9752     .addOperand(Segment)
9753     .setMemRefs(MMOBegin, MMOEnd);
9754
9755   // If we need to align it, do so. Otherwise, just copy the address
9756   // to OverflowDestReg.
9757   if (NeedsAlign) {
9758     // Align the overflow address
9759     assert((Align & (Align-1)) == 0 && "Alignment must be a power of 2");
9760     unsigned TmpReg = MRI.createVirtualRegister(AddrRegClass);
9761
9762     // aligned_addr = (addr + (align-1)) & ~(align-1)
9763     BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), TmpReg)
9764       .addReg(OverflowAddrReg)
9765       .addImm(Align-1);
9766
9767     BuildMI(overflowMBB, DL, TII->get(X86::AND64ri32), OverflowDestReg)
9768       .addReg(TmpReg)
9769       .addImm(~(uint64_t)(Align-1));
9770   } else {
9771     BuildMI(overflowMBB, DL, TII->get(TargetOpcode::COPY), OverflowDestReg)
9772       .addReg(OverflowAddrReg);
9773   }
9774
9775   // Compute the next overflow address after this argument.
9776   // (the overflow address should be kept 8-byte aligned)
9777   unsigned NextAddrReg = MRI.createVirtualRegister(AddrRegClass);
9778   BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), NextAddrReg)
9779     .addReg(OverflowDestReg)
9780     .addImm(ArgSizeA8);
9781
9782   // Store the new overflow address.
9783   BuildMI(overflowMBB, DL, TII->get(X86::MOV64mr))
9784     .addOperand(Base)
9785     .addOperand(Scale)
9786     .addOperand(Index)
9787     .addDisp(Disp, 8)
9788     .addOperand(Segment)
9789     .addReg(NextAddrReg)
9790     .setMemRefs(MMOBegin, MMOEnd);
9791
9792   // If we branched, emit the PHI to the front of endMBB.
9793   if (offsetMBB) {
9794     BuildMI(*endMBB, endMBB->begin(), DL,
9795             TII->get(X86::PHI), DestReg)
9796       .addReg(OffsetDestReg).addMBB(offsetMBB)
9797       .addReg(OverflowDestReg).addMBB(overflowMBB);
9798   }
9799
9800   // Erase the pseudo instruction
9801   MI->eraseFromParent();
9802
9803   return endMBB;
9804 }
9805
9806 MachineBasicBlock *
9807 X86TargetLowering::EmitVAStartSaveXMMRegsWithCustomInserter(
9808                                                  MachineInstr *MI,
9809                                                  MachineBasicBlock *MBB) const {
9810   // Emit code to save XMM registers to the stack. The ABI says that the
9811   // number of registers to save is given in %al, so it's theoretically
9812   // possible to do an indirect jump trick to avoid saving all of them,
9813   // however this code takes a simpler approach and just executes all
9814   // of the stores if %al is non-zero. It's less code, and it's probably
9815   // easier on the hardware branch predictor, and stores aren't all that
9816   // expensive anyway.
9817
9818   // Create the new basic blocks. One block contains all the XMM stores,
9819   // and one block is the final destination regardless of whether any
9820   // stores were performed.
9821   const BasicBlock *LLVM_BB = MBB->getBasicBlock();
9822   MachineFunction *F = MBB->getParent();
9823   MachineFunction::iterator MBBIter = MBB;
9824   ++MBBIter;
9825   MachineBasicBlock *XMMSaveMBB = F->CreateMachineBasicBlock(LLVM_BB);
9826   MachineBasicBlock *EndMBB = F->CreateMachineBasicBlock(LLVM_BB);
9827   F->insert(MBBIter, XMMSaveMBB);
9828   F->insert(MBBIter, EndMBB);
9829
9830   // Transfer the remainder of MBB and its successor edges to EndMBB.
9831   EndMBB->splice(EndMBB->begin(), MBB,
9832                  llvm::next(MachineBasicBlock::iterator(MI)),
9833                  MBB->end());
9834   EndMBB->transferSuccessorsAndUpdatePHIs(MBB);
9835
9836   // The original block will now fall through to the XMM save block.
9837   MBB->addSuccessor(XMMSaveMBB);
9838   // The XMMSaveMBB will fall through to the end block.
9839   XMMSaveMBB->addSuccessor(EndMBB);
9840
9841   // Now add the instructions.
9842   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
9843   DebugLoc DL = MI->getDebugLoc();
9844
9845   unsigned CountReg = MI->getOperand(0).getReg();
9846   int64_t RegSaveFrameIndex = MI->getOperand(1).getImm();
9847   int64_t VarArgsFPOffset = MI->getOperand(2).getImm();
9848
9849   if (!Subtarget->isTargetWin64()) {
9850     // If %al is 0, branch around the XMM save block.
9851     BuildMI(MBB, DL, TII->get(X86::TEST8rr)).addReg(CountReg).addReg(CountReg);
9852     BuildMI(MBB, DL, TII->get(X86::JE_4)).addMBB(EndMBB);
9853     MBB->addSuccessor(EndMBB);
9854   }
9855
9856   // In the XMM save block, save all the XMM argument registers.
9857   for (int i = 3, e = MI->getNumOperands(); i != e; ++i) {
9858     int64_t Offset = (i - 3) * 16 + VarArgsFPOffset;
9859     MachineMemOperand *MMO =
9860       F->getMachineMemOperand(
9861           MachinePointerInfo::getFixedStack(RegSaveFrameIndex, Offset),
9862         MachineMemOperand::MOStore,
9863         /*Size=*/16, /*Align=*/16);
9864     BuildMI(XMMSaveMBB, DL, TII->get(X86::MOVAPSmr))
9865       .addFrameIndex(RegSaveFrameIndex)
9866       .addImm(/*Scale=*/1)
9867       .addReg(/*IndexReg=*/0)
9868       .addImm(/*Disp=*/Offset)
9869       .addReg(/*Segment=*/0)
9870       .addReg(MI->getOperand(i).getReg())
9871       .addMemOperand(MMO);
9872   }
9873
9874   MI->eraseFromParent();   // The pseudo instruction is gone now.
9875
9876   return EndMBB;
9877 }
9878
9879 MachineBasicBlock *
9880 X86TargetLowering::EmitLoweredSelect(MachineInstr *MI,
9881                                      MachineBasicBlock *BB) const {
9882   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
9883   DebugLoc DL = MI->getDebugLoc();
9884
9885   // To "insert" a SELECT_CC instruction, we actually have to insert the
9886   // diamond control-flow pattern.  The incoming instruction knows the
9887   // destination vreg to set, the condition code register to branch on, the
9888   // true/false values to select between, and a branch opcode to use.
9889   const BasicBlock *LLVM_BB = BB->getBasicBlock();
9890   MachineFunction::iterator It = BB;
9891   ++It;
9892
9893   //  thisMBB:
9894   //  ...
9895   //   TrueVal = ...
9896   //   cmpTY ccX, r1, r2
9897   //   bCC copy1MBB
9898   //   fallthrough --> copy0MBB
9899   MachineBasicBlock *thisMBB = BB;
9900   MachineFunction *F = BB->getParent();
9901   MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
9902   MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
9903   F->insert(It, copy0MBB);
9904   F->insert(It, sinkMBB);
9905
9906   // If the EFLAGS register isn't dead in the terminator, then claim that it's
9907   // live into the sink and copy blocks.
9908   const MachineFunction *MF = BB->getParent();
9909   const TargetRegisterInfo *TRI = MF->getTarget().getRegisterInfo();
9910   BitVector ReservedRegs = TRI->getReservedRegs(*MF);
9911
9912   for (unsigned I = 0, E = MI->getNumOperands(); I != E; ++I) {
9913     const MachineOperand &MO = MI->getOperand(I);
9914     if (!MO.isReg() || !MO.isUse() || MO.isKill()) continue;
9915     unsigned Reg = MO.getReg();
9916     if (Reg != X86::EFLAGS) continue;
9917     copy0MBB->addLiveIn(Reg);
9918     sinkMBB->addLiveIn(Reg);
9919   }
9920
9921   // Transfer the remainder of BB and its successor edges to sinkMBB.
9922   sinkMBB->splice(sinkMBB->begin(), BB,
9923                   llvm::next(MachineBasicBlock::iterator(MI)),
9924                   BB->end());
9925   sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
9926
9927   // Add the true and fallthrough blocks as its successors.
9928   BB->addSuccessor(copy0MBB);
9929   BB->addSuccessor(sinkMBB);
9930
9931   // Create the conditional branch instruction.
9932   unsigned Opc =
9933     X86::GetCondBranchFromCond((X86::CondCode)MI->getOperand(3).getImm());
9934   BuildMI(BB, DL, TII->get(Opc)).addMBB(sinkMBB);
9935
9936   //  copy0MBB:
9937   //   %FalseValue = ...
9938   //   # fallthrough to sinkMBB
9939   copy0MBB->addSuccessor(sinkMBB);
9940
9941   //  sinkMBB:
9942   //   %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
9943   //  ...
9944   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
9945           TII->get(X86::PHI), MI->getOperand(0).getReg())
9946     .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB)
9947     .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
9948
9949   MI->eraseFromParent();   // The pseudo instruction is gone now.
9950   return sinkMBB;
9951 }
9952
9953 MachineBasicBlock *
9954 X86TargetLowering::EmitLoweredWinAlloca(MachineInstr *MI,
9955                                           MachineBasicBlock *BB) const {
9956   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
9957   DebugLoc DL = MI->getDebugLoc();
9958
9959   // The lowering is pretty easy: we're just emitting the call to _alloca.  The
9960   // non-trivial part is impdef of ESP.
9961   // FIXME: The code should be tweaked as soon as we'll try to do codegen for
9962   // mingw-w64.
9963
9964   const char *StackProbeSymbol =
9965       Subtarget->isTargetWindows() ? "_chkstk" : "_alloca";
9966
9967   BuildMI(*BB, MI, DL, TII->get(X86::CALLpcrel32))
9968     .addExternalSymbol(StackProbeSymbol)
9969     .addReg(X86::EAX, RegState::Implicit)
9970     .addReg(X86::ESP, RegState::Implicit)
9971     .addReg(X86::EAX, RegState::Define | RegState::Implicit)
9972     .addReg(X86::ESP, RegState::Define | RegState::Implicit)
9973     .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
9974
9975   MI->eraseFromParent();   // The pseudo instruction is gone now.
9976   return BB;
9977 }
9978
9979 MachineBasicBlock *
9980 X86TargetLowering::EmitLoweredTLSCall(MachineInstr *MI,
9981                                       MachineBasicBlock *BB) const {
9982   // This is pretty easy.  We're taking the value that we received from
9983   // our load from the relocation, sticking it in either RDI (x86-64)
9984   // or EAX and doing an indirect call.  The return value will then
9985   // be in the normal return register.
9986   const X86InstrInfo *TII
9987     = static_cast<const X86InstrInfo*>(getTargetMachine().getInstrInfo());
9988   DebugLoc DL = MI->getDebugLoc();
9989   MachineFunction *F = BB->getParent();
9990
9991   assert(Subtarget->isTargetDarwin() && "Darwin only instr emitted?");
9992   assert(MI->getOperand(3).isGlobal() && "This should be a global");
9993
9994   if (Subtarget->is64Bit()) {
9995     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
9996                                       TII->get(X86::MOV64rm), X86::RDI)
9997     .addReg(X86::RIP)
9998     .addImm(0).addReg(0)
9999     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
10000                       MI->getOperand(3).getTargetFlags())
10001     .addReg(0);
10002     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL64m));
10003     addDirectMem(MIB, X86::RDI);
10004   } else if (getTargetMachine().getRelocationModel() != Reloc::PIC_) {
10005     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
10006                                       TII->get(X86::MOV32rm), X86::EAX)
10007     .addReg(0)
10008     .addImm(0).addReg(0)
10009     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
10010                       MI->getOperand(3).getTargetFlags())
10011     .addReg(0);
10012     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
10013     addDirectMem(MIB, X86::EAX);
10014   } else {
10015     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
10016                                       TII->get(X86::MOV32rm), X86::EAX)
10017     .addReg(TII->getGlobalBaseReg(F))
10018     .addImm(0).addReg(0)
10019     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
10020                       MI->getOperand(3).getTargetFlags())
10021     .addReg(0);
10022     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
10023     addDirectMem(MIB, X86::EAX);
10024   }
10025
10026   MI->eraseFromParent(); // The pseudo instruction is gone now.
10027   return BB;
10028 }
10029
10030 MachineBasicBlock *
10031 X86TargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
10032                                                MachineBasicBlock *BB) const {
10033   switch (MI->getOpcode()) {
10034   default: assert(false && "Unexpected instr type to insert");
10035   case X86::WIN_ALLOCA:
10036     return EmitLoweredWinAlloca(MI, BB);
10037   case X86::TLSCall_32:
10038   case X86::TLSCall_64:
10039     return EmitLoweredTLSCall(MI, BB);
10040   case X86::CMOV_GR8:
10041   case X86::CMOV_FR32:
10042   case X86::CMOV_FR64:
10043   case X86::CMOV_V4F32:
10044   case X86::CMOV_V2F64:
10045   case X86::CMOV_V2I64:
10046   case X86::CMOV_GR16:
10047   case X86::CMOV_GR32:
10048   case X86::CMOV_RFP32:
10049   case X86::CMOV_RFP64:
10050   case X86::CMOV_RFP80:
10051     return EmitLoweredSelect(MI, BB);
10052
10053   case X86::FP32_TO_INT16_IN_MEM:
10054   case X86::FP32_TO_INT32_IN_MEM:
10055   case X86::FP32_TO_INT64_IN_MEM:
10056   case X86::FP64_TO_INT16_IN_MEM:
10057   case X86::FP64_TO_INT32_IN_MEM:
10058   case X86::FP64_TO_INT64_IN_MEM:
10059   case X86::FP80_TO_INT16_IN_MEM:
10060   case X86::FP80_TO_INT32_IN_MEM:
10061   case X86::FP80_TO_INT64_IN_MEM: {
10062     const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
10063     DebugLoc DL = MI->getDebugLoc();
10064
10065     // Change the floating point control register to use "round towards zero"
10066     // mode when truncating to an integer value.
10067     MachineFunction *F = BB->getParent();
10068     int CWFrameIdx = F->getFrameInfo()->CreateStackObject(2, 2, false);
10069     addFrameReference(BuildMI(*BB, MI, DL,
10070                               TII->get(X86::FNSTCW16m)), CWFrameIdx);
10071
10072     // Load the old value of the high byte of the control word...
10073     unsigned OldCW =
10074       F->getRegInfo().createVirtualRegister(X86::GR16RegisterClass);
10075     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16rm), OldCW),
10076                       CWFrameIdx);
10077
10078     // Set the high part to be round to zero...
10079     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mi)), CWFrameIdx)
10080       .addImm(0xC7F);
10081
10082     // Reload the modified control word now...
10083     addFrameReference(BuildMI(*BB, MI, DL,
10084                               TII->get(X86::FLDCW16m)), CWFrameIdx);
10085
10086     // Restore the memory image of control word to original value
10087     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mr)), CWFrameIdx)
10088       .addReg(OldCW);
10089
10090     // Get the X86 opcode to use.
10091     unsigned Opc;
10092     switch (MI->getOpcode()) {
10093     default: llvm_unreachable("illegal opcode!");
10094     case X86::FP32_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m32; break;
10095     case X86::FP32_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m32; break;
10096     case X86::FP32_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m32; break;
10097     case X86::FP64_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m64; break;
10098     case X86::FP64_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m64; break;
10099     case X86::FP64_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m64; break;
10100     case X86::FP80_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m80; break;
10101     case X86::FP80_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m80; break;
10102     case X86::FP80_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m80; break;
10103     }
10104
10105     X86AddressMode AM;
10106     MachineOperand &Op = MI->getOperand(0);
10107     if (Op.isReg()) {
10108       AM.BaseType = X86AddressMode::RegBase;
10109       AM.Base.Reg = Op.getReg();
10110     } else {
10111       AM.BaseType = X86AddressMode::FrameIndexBase;
10112       AM.Base.FrameIndex = Op.getIndex();
10113     }
10114     Op = MI->getOperand(1);
10115     if (Op.isImm())
10116       AM.Scale = Op.getImm();
10117     Op = MI->getOperand(2);
10118     if (Op.isImm())
10119       AM.IndexReg = Op.getImm();
10120     Op = MI->getOperand(3);
10121     if (Op.isGlobal()) {
10122       AM.GV = Op.getGlobal();
10123     } else {
10124       AM.Disp = Op.getImm();
10125     }
10126     addFullAddress(BuildMI(*BB, MI, DL, TII->get(Opc)), AM)
10127                       .addReg(MI->getOperand(X86::AddrNumOperands).getReg());
10128
10129     // Reload the original control word now.
10130     addFrameReference(BuildMI(*BB, MI, DL,
10131                               TII->get(X86::FLDCW16m)), CWFrameIdx);
10132
10133     MI->eraseFromParent();   // The pseudo instruction is gone now.
10134     return BB;
10135   }
10136     // String/text processing lowering.
10137   case X86::PCMPISTRM128REG:
10138   case X86::VPCMPISTRM128REG:
10139     return EmitPCMP(MI, BB, 3, false /* in-mem */);
10140   case X86::PCMPISTRM128MEM:
10141   case X86::VPCMPISTRM128MEM:
10142     return EmitPCMP(MI, BB, 3, true /* in-mem */);
10143   case X86::PCMPESTRM128REG:
10144   case X86::VPCMPESTRM128REG:
10145     return EmitPCMP(MI, BB, 5, false /* in mem */);
10146   case X86::PCMPESTRM128MEM:
10147   case X86::VPCMPESTRM128MEM:
10148     return EmitPCMP(MI, BB, 5, true /* in mem */);
10149
10150     // Thread synchronization.
10151   case X86::MONITOR:
10152     return EmitMonitor(MI, BB);  
10153   case X86::MWAIT:
10154     return EmitMwait(MI, BB);
10155
10156     // Atomic Lowering.
10157   case X86::ATOMAND32:
10158     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND32rr,
10159                                                X86::AND32ri, X86::MOV32rm,
10160                                                X86::LCMPXCHG32,
10161                                                X86::NOT32r, X86::EAX,
10162                                                X86::GR32RegisterClass);
10163   case X86::ATOMOR32:
10164     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR32rr,
10165                                                X86::OR32ri, X86::MOV32rm,
10166                                                X86::LCMPXCHG32,
10167                                                X86::NOT32r, X86::EAX,
10168                                                X86::GR32RegisterClass);
10169   case X86::ATOMXOR32:
10170     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR32rr,
10171                                                X86::XOR32ri, X86::MOV32rm,
10172                                                X86::LCMPXCHG32,
10173                                                X86::NOT32r, X86::EAX,
10174                                                X86::GR32RegisterClass);
10175   case X86::ATOMNAND32:
10176     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND32rr,
10177                                                X86::AND32ri, X86::MOV32rm,
10178                                                X86::LCMPXCHG32,
10179                                                X86::NOT32r, X86::EAX,
10180                                                X86::GR32RegisterClass, true);
10181   case X86::ATOMMIN32:
10182     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVL32rr);
10183   case X86::ATOMMAX32:
10184     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVG32rr);
10185   case X86::ATOMUMIN32:
10186     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVB32rr);
10187   case X86::ATOMUMAX32:
10188     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVA32rr);
10189
10190   case X86::ATOMAND16:
10191     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND16rr,
10192                                                X86::AND16ri, X86::MOV16rm,
10193                                                X86::LCMPXCHG16,
10194                                                X86::NOT16r, X86::AX,
10195                                                X86::GR16RegisterClass);
10196   case X86::ATOMOR16:
10197     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR16rr,
10198                                                X86::OR16ri, X86::MOV16rm,
10199                                                X86::LCMPXCHG16,
10200                                                X86::NOT16r, X86::AX,
10201                                                X86::GR16RegisterClass);
10202   case X86::ATOMXOR16:
10203     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR16rr,
10204                                                X86::XOR16ri, X86::MOV16rm,
10205                                                X86::LCMPXCHG16,
10206                                                X86::NOT16r, X86::AX,
10207                                                X86::GR16RegisterClass);
10208   case X86::ATOMNAND16:
10209     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND16rr,
10210                                                X86::AND16ri, X86::MOV16rm,
10211                                                X86::LCMPXCHG16,
10212                                                X86::NOT16r, X86::AX,
10213                                                X86::GR16RegisterClass, true);
10214   case X86::ATOMMIN16:
10215     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVL16rr);
10216   case X86::ATOMMAX16:
10217     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVG16rr);
10218   case X86::ATOMUMIN16:
10219     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVB16rr);
10220   case X86::ATOMUMAX16:
10221     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVA16rr);
10222
10223   case X86::ATOMAND8:
10224     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND8rr,
10225                                                X86::AND8ri, X86::MOV8rm,
10226                                                X86::LCMPXCHG8,
10227                                                X86::NOT8r, X86::AL,
10228                                                X86::GR8RegisterClass);
10229   case X86::ATOMOR8:
10230     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR8rr,
10231                                                X86::OR8ri, X86::MOV8rm,
10232                                                X86::LCMPXCHG8,
10233                                                X86::NOT8r, X86::AL,
10234                                                X86::GR8RegisterClass);
10235   case X86::ATOMXOR8:
10236     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR8rr,
10237                                                X86::XOR8ri, X86::MOV8rm,
10238                                                X86::LCMPXCHG8,
10239                                                X86::NOT8r, X86::AL,
10240                                                X86::GR8RegisterClass);
10241   case X86::ATOMNAND8:
10242     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND8rr,
10243                                                X86::AND8ri, X86::MOV8rm,
10244                                                X86::LCMPXCHG8,
10245                                                X86::NOT8r, X86::AL,
10246                                                X86::GR8RegisterClass, true);
10247   // FIXME: There are no CMOV8 instructions; MIN/MAX need some other way.
10248   // This group is for 64-bit host.
10249   case X86::ATOMAND64:
10250     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND64rr,
10251                                                X86::AND64ri32, X86::MOV64rm,
10252                                                X86::LCMPXCHG64,
10253                                                X86::NOT64r, X86::RAX,
10254                                                X86::GR64RegisterClass);
10255   case X86::ATOMOR64:
10256     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR64rr,
10257                                                X86::OR64ri32, X86::MOV64rm,
10258                                                X86::LCMPXCHG64,
10259                                                X86::NOT64r, X86::RAX,
10260                                                X86::GR64RegisterClass);
10261   case X86::ATOMXOR64:
10262     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR64rr,
10263                                                X86::XOR64ri32, X86::MOV64rm,
10264                                                X86::LCMPXCHG64,
10265                                                X86::NOT64r, X86::RAX,
10266                                                X86::GR64RegisterClass);
10267   case X86::ATOMNAND64:
10268     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND64rr,
10269                                                X86::AND64ri32, X86::MOV64rm,
10270                                                X86::LCMPXCHG64,
10271                                                X86::NOT64r, X86::RAX,
10272                                                X86::GR64RegisterClass, true);
10273   case X86::ATOMMIN64:
10274     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVL64rr);
10275   case X86::ATOMMAX64:
10276     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVG64rr);
10277   case X86::ATOMUMIN64:
10278     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVB64rr);
10279   case X86::ATOMUMAX64:
10280     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVA64rr);
10281
10282   // This group does 64-bit operations on a 32-bit host.
10283   case X86::ATOMAND6432:
10284     return EmitAtomicBit6432WithCustomInserter(MI, BB,
10285                                                X86::AND32rr, X86::AND32rr,
10286                                                X86::AND32ri, X86::AND32ri,
10287                                                false);
10288   case X86::ATOMOR6432:
10289     return EmitAtomicBit6432WithCustomInserter(MI, BB,
10290                                                X86::OR32rr, X86::OR32rr,
10291                                                X86::OR32ri, X86::OR32ri,
10292                                                false);
10293   case X86::ATOMXOR6432:
10294     return EmitAtomicBit6432WithCustomInserter(MI, BB,
10295                                                X86::XOR32rr, X86::XOR32rr,
10296                                                X86::XOR32ri, X86::XOR32ri,
10297                                                false);
10298   case X86::ATOMNAND6432:
10299     return EmitAtomicBit6432WithCustomInserter(MI, BB,
10300                                                X86::AND32rr, X86::AND32rr,
10301                                                X86::AND32ri, X86::AND32ri,
10302                                                true);
10303   case X86::ATOMADD6432:
10304     return EmitAtomicBit6432WithCustomInserter(MI, BB,
10305                                                X86::ADD32rr, X86::ADC32rr,
10306                                                X86::ADD32ri, X86::ADC32ri,
10307                                                false);
10308   case X86::ATOMSUB6432:
10309     return EmitAtomicBit6432WithCustomInserter(MI, BB,
10310                                                X86::SUB32rr, X86::SBB32rr,
10311                                                X86::SUB32ri, X86::SBB32ri,
10312                                                false);
10313   case X86::ATOMSWAP6432:
10314     return EmitAtomicBit6432WithCustomInserter(MI, BB,
10315                                                X86::MOV32rr, X86::MOV32rr,
10316                                                X86::MOV32ri, X86::MOV32ri,
10317                                                false);
10318   case X86::VASTART_SAVE_XMM_REGS:
10319     return EmitVAStartSaveXMMRegsWithCustomInserter(MI, BB);
10320
10321   case X86::VAARG_64:
10322     return EmitVAARG64WithCustomInserter(MI, BB);
10323   }
10324 }
10325
10326 //===----------------------------------------------------------------------===//
10327 //                           X86 Optimization Hooks
10328 //===----------------------------------------------------------------------===//
10329
10330 void X86TargetLowering::computeMaskedBitsForTargetNode(const SDValue Op,
10331                                                        const APInt &Mask,
10332                                                        APInt &KnownZero,
10333                                                        APInt &KnownOne,
10334                                                        const SelectionDAG &DAG,
10335                                                        unsigned Depth) const {
10336   unsigned Opc = Op.getOpcode();
10337   assert((Opc >= ISD::BUILTIN_OP_END ||
10338           Opc == ISD::INTRINSIC_WO_CHAIN ||
10339           Opc == ISD::INTRINSIC_W_CHAIN ||
10340           Opc == ISD::INTRINSIC_VOID) &&
10341          "Should use MaskedValueIsZero if you don't know whether Op"
10342          " is a target node!");
10343
10344   KnownZero = KnownOne = APInt(Mask.getBitWidth(), 0);   // Don't know anything.
10345   switch (Opc) {
10346   default: break;
10347   case X86ISD::ADD:
10348   case X86ISD::SUB:
10349   case X86ISD::SMUL:
10350   case X86ISD::UMUL:
10351   case X86ISD::INC:
10352   case X86ISD::DEC:
10353   case X86ISD::OR:
10354   case X86ISD::XOR:
10355   case X86ISD::AND:
10356     // These nodes' second result is a boolean.
10357     if (Op.getResNo() == 0)
10358       break;
10359     // Fallthrough
10360   case X86ISD::SETCC:
10361     KnownZero |= APInt::getHighBitsSet(Mask.getBitWidth(),
10362                                        Mask.getBitWidth() - 1);
10363     break;
10364   }
10365 }
10366
10367 unsigned X86TargetLowering::ComputeNumSignBitsForTargetNode(SDValue Op,
10368                                                          unsigned Depth) const {
10369   // SETCC_CARRY sets the dest to ~0 for true or 0 for false.
10370   if (Op.getOpcode() == X86ISD::SETCC_CARRY)
10371     return Op.getValueType().getScalarType().getSizeInBits();
10372
10373   // Fallback case.
10374   return 1;
10375 }
10376
10377 /// isGAPlusOffset - Returns true (and the GlobalValue and the offset) if the
10378 /// node is a GlobalAddress + offset.
10379 bool X86TargetLowering::isGAPlusOffset(SDNode *N,
10380                                        const GlobalValue* &GA,
10381                                        int64_t &Offset) const {
10382   if (N->getOpcode() == X86ISD::Wrapper) {
10383     if (isa<GlobalAddressSDNode>(N->getOperand(0))) {
10384       GA = cast<GlobalAddressSDNode>(N->getOperand(0))->getGlobal();
10385       Offset = cast<GlobalAddressSDNode>(N->getOperand(0))->getOffset();
10386       return true;
10387     }
10388   }
10389   return TargetLowering::isGAPlusOffset(N, GA, Offset);
10390 }
10391
10392 /// PerformShuffleCombine - Combine a vector_shuffle that is equal to
10393 /// build_vector load1, load2, load3, load4, <0, 1, 2, 3> into a 128-bit load
10394 /// if the load addresses are consecutive, non-overlapping, and in the right
10395 /// order.
10396 static SDValue PerformShuffleCombine(SDNode *N, SelectionDAG &DAG,
10397                                      const TargetLowering &TLI) {
10398   DebugLoc dl = N->getDebugLoc();
10399   EVT VT = N->getValueType(0);
10400
10401   if (VT.getSizeInBits() != 128)
10402     return SDValue();
10403
10404   SmallVector<SDValue, 16> Elts;
10405   for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i)
10406     Elts.push_back(getShuffleScalarElt(N, i, DAG, 0));
10407
10408   return EltsFromConsecutiveLoads(VT, Elts, dl, DAG);
10409 }
10410
10411 /// PerformEXTRACT_VECTOR_ELTCombine - Detect vector gather/scatter index
10412 /// generation and convert it from being a bunch of shuffles and extracts
10413 /// to a simple store and scalar loads to extract the elements.
10414 static SDValue PerformEXTRACT_VECTOR_ELTCombine(SDNode *N, SelectionDAG &DAG,
10415                                                 const TargetLowering &TLI) {
10416   SDValue InputVector = N->getOperand(0);
10417
10418   // Only operate on vectors of 4 elements, where the alternative shuffling
10419   // gets to be more expensive.
10420   if (InputVector.getValueType() != MVT::v4i32)
10421     return SDValue();
10422
10423   // Check whether every use of InputVector is an EXTRACT_VECTOR_ELT with a
10424   // single use which is a sign-extend or zero-extend, and all elements are
10425   // used.
10426   SmallVector<SDNode *, 4> Uses;
10427   unsigned ExtractedElements = 0;
10428   for (SDNode::use_iterator UI = InputVector.getNode()->use_begin(),
10429        UE = InputVector.getNode()->use_end(); UI != UE; ++UI) {
10430     if (UI.getUse().getResNo() != InputVector.getResNo())
10431       return SDValue();
10432
10433     SDNode *Extract = *UI;
10434     if (Extract->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
10435       return SDValue();
10436
10437     if (Extract->getValueType(0) != MVT::i32)
10438       return SDValue();
10439     if (!Extract->hasOneUse())
10440       return SDValue();
10441     if (Extract->use_begin()->getOpcode() != ISD::SIGN_EXTEND &&
10442         Extract->use_begin()->getOpcode() != ISD::ZERO_EXTEND)
10443       return SDValue();
10444     if (!isa<ConstantSDNode>(Extract->getOperand(1)))
10445       return SDValue();
10446
10447     // Record which element was extracted.
10448     ExtractedElements |=
10449       1 << cast<ConstantSDNode>(Extract->getOperand(1))->getZExtValue();
10450
10451     Uses.push_back(Extract);
10452   }
10453
10454   // If not all the elements were used, this may not be worthwhile.
10455   if (ExtractedElements != 15)
10456     return SDValue();
10457
10458   // Ok, we've now decided to do the transformation.
10459   DebugLoc dl = InputVector.getDebugLoc();
10460
10461   // Store the value to a temporary stack slot.
10462   SDValue StackPtr = DAG.CreateStackTemporary(InputVector.getValueType());
10463   SDValue Ch = DAG.getStore(DAG.getEntryNode(), dl, InputVector, StackPtr,
10464                             MachinePointerInfo(), false, false, 0);
10465
10466   // Replace each use (extract) with a load of the appropriate element.
10467   for (SmallVectorImpl<SDNode *>::iterator UI = Uses.begin(),
10468        UE = Uses.end(); UI != UE; ++UI) {
10469     SDNode *Extract = *UI;
10470
10471     // Compute the element's address.
10472     SDValue Idx = Extract->getOperand(1);
10473     unsigned EltSize =
10474         InputVector.getValueType().getVectorElementType().getSizeInBits()/8;
10475     uint64_t Offset = EltSize * cast<ConstantSDNode>(Idx)->getZExtValue();
10476     SDValue OffsetVal = DAG.getConstant(Offset, TLI.getPointerTy());
10477
10478     SDValue ScalarAddr = DAG.getNode(ISD::ADD, dl, Idx.getValueType(),
10479                                      StackPtr, OffsetVal);
10480
10481     // Load the scalar.
10482     SDValue LoadScalar = DAG.getLoad(Extract->getValueType(0), dl, Ch,
10483                                      ScalarAddr, MachinePointerInfo(),
10484                                      false, false, 0);
10485
10486     // Replace the exact with the load.
10487     DAG.ReplaceAllUsesOfValueWith(SDValue(Extract, 0), LoadScalar);
10488   }
10489
10490   // The replacement was made in place; don't return anything.
10491   return SDValue();
10492 }
10493
10494 /// PerformSELECTCombine - Do target-specific dag combines on SELECT nodes.
10495 static SDValue PerformSELECTCombine(SDNode *N, SelectionDAG &DAG,
10496                                     const X86Subtarget *Subtarget) {
10497   DebugLoc DL = N->getDebugLoc();
10498   SDValue Cond = N->getOperand(0);
10499   // Get the LHS/RHS of the select.
10500   SDValue LHS = N->getOperand(1);
10501   SDValue RHS = N->getOperand(2);
10502
10503   // If we have SSE[12] support, try to form min/max nodes. SSE min/max
10504   // instructions match the semantics of the common C idiom x<y?x:y but not
10505   // x<=y?x:y, because of how they handle negative zero (which can be
10506   // ignored in unsafe-math mode).
10507   if (Subtarget->hasSSE2() &&
10508       (LHS.getValueType() == MVT::f32 || LHS.getValueType() == MVT::f64) &&
10509       Cond.getOpcode() == ISD::SETCC) {
10510     ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
10511
10512     unsigned Opcode = 0;
10513     // Check for x CC y ? x : y.
10514     if (DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
10515         DAG.isEqualTo(RHS, Cond.getOperand(1))) {
10516       switch (CC) {
10517       default: break;
10518       case ISD::SETULT:
10519         // Converting this to a min would handle NaNs incorrectly, and swapping
10520         // the operands would cause it to handle comparisons between positive
10521         // and negative zero incorrectly.
10522         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
10523           if (!UnsafeFPMath &&
10524               !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
10525             break;
10526           std::swap(LHS, RHS);
10527         }
10528         Opcode = X86ISD::FMIN;
10529         break;
10530       case ISD::SETOLE:
10531         // Converting this to a min would handle comparisons between positive
10532         // and negative zero incorrectly.
10533         if (!UnsafeFPMath &&
10534             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
10535           break;
10536         Opcode = X86ISD::FMIN;
10537         break;
10538       case ISD::SETULE:
10539         // Converting this to a min would handle both negative zeros and NaNs
10540         // incorrectly, but we can swap the operands to fix both.
10541         std::swap(LHS, RHS);
10542       case ISD::SETOLT:
10543       case ISD::SETLT:
10544       case ISD::SETLE:
10545         Opcode = X86ISD::FMIN;
10546         break;
10547
10548       case ISD::SETOGE:
10549         // Converting this to a max would handle comparisons between positive
10550         // and negative zero incorrectly.
10551         if (!UnsafeFPMath &&
10552             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(LHS))
10553           break;
10554         Opcode = X86ISD::FMAX;
10555         break;
10556       case ISD::SETUGT:
10557         // Converting this to a max would handle NaNs incorrectly, and swapping
10558         // the operands would cause it to handle comparisons between positive
10559         // and negative zero incorrectly.
10560         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
10561           if (!UnsafeFPMath &&
10562               !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
10563             break;
10564           std::swap(LHS, RHS);
10565         }
10566         Opcode = X86ISD::FMAX;
10567         break;
10568       case ISD::SETUGE:
10569         // Converting this to a max would handle both negative zeros and NaNs
10570         // incorrectly, but we can swap the operands to fix both.
10571         std::swap(LHS, RHS);
10572       case ISD::SETOGT:
10573       case ISD::SETGT:
10574       case ISD::SETGE:
10575         Opcode = X86ISD::FMAX;
10576         break;
10577       }
10578     // Check for x CC y ? y : x -- a min/max with reversed arms.
10579     } else if (DAG.isEqualTo(LHS, Cond.getOperand(1)) &&
10580                DAG.isEqualTo(RHS, Cond.getOperand(0))) {
10581       switch (CC) {
10582       default: break;
10583       case ISD::SETOGE:
10584         // Converting this to a min would handle comparisons between positive
10585         // and negative zero incorrectly, and swapping the operands would
10586         // cause it to handle NaNs incorrectly.
10587         if (!UnsafeFPMath &&
10588             !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS))) {
10589           if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
10590             break;
10591           std::swap(LHS, RHS);
10592         }
10593         Opcode = X86ISD::FMIN;
10594         break;
10595       case ISD::SETUGT:
10596         // Converting this to a min would handle NaNs incorrectly.
10597         if (!UnsafeFPMath &&
10598             (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)))
10599           break;
10600         Opcode = X86ISD::FMIN;
10601         break;
10602       case ISD::SETUGE:
10603         // Converting this to a min would handle both negative zeros and NaNs
10604         // incorrectly, but we can swap the operands to fix both.
10605         std::swap(LHS, RHS);
10606       case ISD::SETOGT:
10607       case ISD::SETGT:
10608       case ISD::SETGE:
10609         Opcode = X86ISD::FMIN;
10610         break;
10611
10612       case ISD::SETULT:
10613         // Converting this to a max would handle NaNs incorrectly.
10614         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
10615           break;
10616         Opcode = X86ISD::FMAX;
10617         break;
10618       case ISD::SETOLE:
10619         // Converting this to a max would handle comparisons between positive
10620         // and negative zero incorrectly, and swapping the operands would
10621         // cause it to handle NaNs incorrectly.
10622         if (!UnsafeFPMath &&
10623             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS)) {
10624           if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
10625             break;
10626           std::swap(LHS, RHS);
10627         }
10628         Opcode = X86ISD::FMAX;
10629         break;
10630       case ISD::SETULE:
10631         // Converting this to a max would handle both negative zeros and NaNs
10632         // incorrectly, but we can swap the operands to fix both.
10633         std::swap(LHS, RHS);
10634       case ISD::SETOLT:
10635       case ISD::SETLT:
10636       case ISD::SETLE:
10637         Opcode = X86ISD::FMAX;
10638         break;
10639       }
10640     }
10641
10642     if (Opcode)
10643       return DAG.getNode(Opcode, DL, N->getValueType(0), LHS, RHS);
10644   }
10645
10646   // If this is a select between two integer constants, try to do some
10647   // optimizations.
10648   if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(LHS)) {
10649     if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(RHS))
10650       // Don't do this for crazy integer types.
10651       if (DAG.getTargetLoweringInfo().isTypeLegal(LHS.getValueType())) {
10652         // If this is efficiently invertible, canonicalize the LHSC/RHSC values
10653         // so that TrueC (the true value) is larger than FalseC.
10654         bool NeedsCondInvert = false;
10655
10656         if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue()) &&
10657             // Efficiently invertible.
10658             (Cond.getOpcode() == ISD::SETCC ||  // setcc -> invertible.
10659              (Cond.getOpcode() == ISD::XOR &&   // xor(X, C) -> invertible.
10660               isa<ConstantSDNode>(Cond.getOperand(1))))) {
10661           NeedsCondInvert = true;
10662           std::swap(TrueC, FalseC);
10663         }
10664
10665         // Optimize C ? 8 : 0 -> zext(C) << 3.  Likewise for any pow2/0.
10666         if (FalseC->getAPIntValue() == 0 &&
10667             TrueC->getAPIntValue().isPowerOf2()) {
10668           if (NeedsCondInvert) // Invert the condition if needed.
10669             Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
10670                                DAG.getConstant(1, Cond.getValueType()));
10671
10672           // Zero extend the condition if needed.
10673           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, LHS.getValueType(), Cond);
10674
10675           unsigned ShAmt = TrueC->getAPIntValue().logBase2();
10676           return DAG.getNode(ISD::SHL, DL, LHS.getValueType(), Cond,
10677                              DAG.getConstant(ShAmt, MVT::i8));
10678         }
10679
10680         // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.
10681         if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
10682           if (NeedsCondInvert) // Invert the condition if needed.
10683             Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
10684                                DAG.getConstant(1, Cond.getValueType()));
10685
10686           // Zero extend the condition if needed.
10687           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
10688                              FalseC->getValueType(0), Cond);
10689           return DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
10690                              SDValue(FalseC, 0));
10691         }
10692
10693         // Optimize cases that will turn into an LEA instruction.  This requires
10694         // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
10695         if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
10696           uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
10697           if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
10698
10699           bool isFastMultiplier = false;
10700           if (Diff < 10) {
10701             switch ((unsigned char)Diff) {
10702               default: break;
10703               case 1:  // result = add base, cond
10704               case 2:  // result = lea base(    , cond*2)
10705               case 3:  // result = lea base(cond, cond*2)
10706               case 4:  // result = lea base(    , cond*4)
10707               case 5:  // result = lea base(cond, cond*4)
10708               case 8:  // result = lea base(    , cond*8)
10709               case 9:  // result = lea base(cond, cond*8)
10710                 isFastMultiplier = true;
10711                 break;
10712             }
10713           }
10714
10715           if (isFastMultiplier) {
10716             APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
10717             if (NeedsCondInvert) // Invert the condition if needed.
10718               Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
10719                                  DAG.getConstant(1, Cond.getValueType()));
10720
10721             // Zero extend the condition if needed.
10722             Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
10723                                Cond);
10724             // Scale the condition by the difference.
10725             if (Diff != 1)
10726               Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
10727                                  DAG.getConstant(Diff, Cond.getValueType()));
10728
10729             // Add the base if non-zero.
10730             if (FalseC->getAPIntValue() != 0)
10731               Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
10732                                  SDValue(FalseC, 0));
10733             return Cond;
10734           }
10735         }
10736       }
10737   }
10738
10739   return SDValue();
10740 }
10741
10742 /// Optimize X86ISD::CMOV [LHS, RHS, CONDCODE (e.g. X86::COND_NE), CONDVAL]
10743 static SDValue PerformCMOVCombine(SDNode *N, SelectionDAG &DAG,
10744                                   TargetLowering::DAGCombinerInfo &DCI) {
10745   DebugLoc DL = N->getDebugLoc();
10746
10747   // If the flag operand isn't dead, don't touch this CMOV.
10748   if (N->getNumValues() == 2 && !SDValue(N, 1).use_empty())
10749     return SDValue();
10750
10751   // If this is a select between two integer constants, try to do some
10752   // optimizations.  Note that the operands are ordered the opposite of SELECT
10753   // operands.
10754   if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(N->getOperand(1))) {
10755     if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(N->getOperand(0))) {
10756       // Canonicalize the TrueC/FalseC values so that TrueC (the true value) is
10757       // larger than FalseC (the false value).
10758       X86::CondCode CC = (X86::CondCode)N->getConstantOperandVal(2);
10759
10760       if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue())) {
10761         CC = X86::GetOppositeBranchCondition(CC);
10762         std::swap(TrueC, FalseC);
10763       }
10764
10765       // Optimize C ? 8 : 0 -> zext(setcc(C)) << 3.  Likewise for any pow2/0.
10766       // This is efficient for any integer data type (including i8/i16) and
10767       // shift amount.
10768       if (FalseC->getAPIntValue() == 0 && TrueC->getAPIntValue().isPowerOf2()) {
10769         SDValue Cond = N->getOperand(3);
10770         Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
10771                            DAG.getConstant(CC, MVT::i8), Cond);
10772
10773         // Zero extend the condition if needed.
10774         Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, TrueC->getValueType(0), Cond);
10775
10776         unsigned ShAmt = TrueC->getAPIntValue().logBase2();
10777         Cond = DAG.getNode(ISD::SHL, DL, Cond.getValueType(), Cond,
10778                            DAG.getConstant(ShAmt, MVT::i8));
10779         if (N->getNumValues() == 2)  // Dead flag value?
10780           return DCI.CombineTo(N, Cond, SDValue());
10781         return Cond;
10782       }
10783
10784       // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.  This is efficient
10785       // for any integer data type, including i8/i16.
10786       if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
10787         SDValue Cond = N->getOperand(3);
10788         Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
10789                            DAG.getConstant(CC, MVT::i8), Cond);
10790
10791         // Zero extend the condition if needed.
10792         Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
10793                            FalseC->getValueType(0), Cond);
10794         Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
10795                            SDValue(FalseC, 0));
10796
10797         if (N->getNumValues() == 2)  // Dead flag value?
10798           return DCI.CombineTo(N, Cond, SDValue());
10799         return Cond;
10800       }
10801
10802       // Optimize cases that will turn into an LEA instruction.  This requires
10803       // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
10804       if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
10805         uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
10806         if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
10807
10808         bool isFastMultiplier = false;
10809         if (Diff < 10) {
10810           switch ((unsigned char)Diff) {
10811           default: break;
10812           case 1:  // result = add base, cond
10813           case 2:  // result = lea base(    , cond*2)
10814           case 3:  // result = lea base(cond, cond*2)
10815           case 4:  // result = lea base(    , cond*4)
10816           case 5:  // result = lea base(cond, cond*4)
10817           case 8:  // result = lea base(    , cond*8)
10818           case 9:  // result = lea base(cond, cond*8)
10819             isFastMultiplier = true;
10820             break;
10821           }
10822         }
10823
10824         if (isFastMultiplier) {
10825           APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
10826           SDValue Cond = N->getOperand(3);
10827           Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
10828                              DAG.getConstant(CC, MVT::i8), Cond);
10829           // Zero extend the condition if needed.
10830           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
10831                              Cond);
10832           // Scale the condition by the difference.
10833           if (Diff != 1)
10834             Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
10835                                DAG.getConstant(Diff, Cond.getValueType()));
10836
10837           // Add the base if non-zero.
10838           if (FalseC->getAPIntValue() != 0)
10839             Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
10840                                SDValue(FalseC, 0));
10841           if (N->getNumValues() == 2)  // Dead flag value?
10842             return DCI.CombineTo(N, Cond, SDValue());
10843           return Cond;
10844         }
10845       }
10846     }
10847   }
10848   return SDValue();
10849 }
10850
10851
10852 /// PerformMulCombine - Optimize a single multiply with constant into two
10853 /// in order to implement it with two cheaper instructions, e.g.
10854 /// LEA + SHL, LEA + LEA.
10855 static SDValue PerformMulCombine(SDNode *N, SelectionDAG &DAG,
10856                                  TargetLowering::DAGCombinerInfo &DCI) {
10857   if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
10858     return SDValue();
10859
10860   EVT VT = N->getValueType(0);
10861   if (VT != MVT::i64)
10862     return SDValue();
10863
10864   ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
10865   if (!C)
10866     return SDValue();
10867   uint64_t MulAmt = C->getZExtValue();
10868   if (isPowerOf2_64(MulAmt) || MulAmt == 3 || MulAmt == 5 || MulAmt == 9)
10869     return SDValue();
10870
10871   uint64_t MulAmt1 = 0;
10872   uint64_t MulAmt2 = 0;
10873   if ((MulAmt % 9) == 0) {
10874     MulAmt1 = 9;
10875     MulAmt2 = MulAmt / 9;
10876   } else if ((MulAmt % 5) == 0) {
10877     MulAmt1 = 5;
10878     MulAmt2 = MulAmt / 5;
10879   } else if ((MulAmt % 3) == 0) {
10880     MulAmt1 = 3;
10881     MulAmt2 = MulAmt / 3;
10882   }
10883   if (MulAmt2 &&
10884       (isPowerOf2_64(MulAmt2) || MulAmt2 == 3 || MulAmt2 == 5 || MulAmt2 == 9)){
10885     DebugLoc DL = N->getDebugLoc();
10886
10887     if (isPowerOf2_64(MulAmt2) &&
10888         !(N->hasOneUse() && N->use_begin()->getOpcode() == ISD::ADD))
10889       // If second multiplifer is pow2, issue it first. We want the multiply by
10890       // 3, 5, or 9 to be folded into the addressing mode unless the lone use
10891       // is an add.
10892       std::swap(MulAmt1, MulAmt2);
10893
10894     SDValue NewMul;
10895     if (isPowerOf2_64(MulAmt1))
10896       NewMul = DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
10897                            DAG.getConstant(Log2_64(MulAmt1), MVT::i8));
10898     else
10899       NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, N->getOperand(0),
10900                            DAG.getConstant(MulAmt1, VT));
10901
10902     if (isPowerOf2_64(MulAmt2))
10903       NewMul = DAG.getNode(ISD::SHL, DL, VT, NewMul,
10904                            DAG.getConstant(Log2_64(MulAmt2), MVT::i8));
10905     else
10906       NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, NewMul,
10907                            DAG.getConstant(MulAmt2, VT));
10908
10909     // Do not add new nodes to DAG combiner worklist.
10910     DCI.CombineTo(N, NewMul, false);
10911   }
10912   return SDValue();
10913 }
10914
10915 static SDValue PerformSHLCombine(SDNode *N, SelectionDAG &DAG) {
10916   SDValue N0 = N->getOperand(0);
10917   SDValue N1 = N->getOperand(1);
10918   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
10919   EVT VT = N0.getValueType();
10920
10921   // fold (shl (and (setcc_c), c1), c2) -> (and setcc_c, (c1 << c2))
10922   // since the result of setcc_c is all zero's or all ones.
10923   if (N1C && N0.getOpcode() == ISD::AND &&
10924       N0.getOperand(1).getOpcode() == ISD::Constant) {
10925     SDValue N00 = N0.getOperand(0);
10926     if (N00.getOpcode() == X86ISD::SETCC_CARRY ||
10927         ((N00.getOpcode() == ISD::ANY_EXTEND ||
10928           N00.getOpcode() == ISD::ZERO_EXTEND) &&
10929          N00.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY)) {
10930       APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
10931       APInt ShAmt = N1C->getAPIntValue();
10932       Mask = Mask.shl(ShAmt);
10933       if (Mask != 0)
10934         return DAG.getNode(ISD::AND, N->getDebugLoc(), VT,
10935                            N00, DAG.getConstant(Mask, VT));
10936     }
10937   }
10938
10939   return SDValue();
10940 }
10941
10942 /// PerformShiftCombine - Transforms vector shift nodes to use vector shifts
10943 ///                       when possible.
10944 static SDValue PerformShiftCombine(SDNode* N, SelectionDAG &DAG,
10945                                    const X86Subtarget *Subtarget) {
10946   EVT VT = N->getValueType(0);
10947   if (!VT.isVector() && VT.isInteger() &&
10948       N->getOpcode() == ISD::SHL)
10949     return PerformSHLCombine(N, DAG);
10950
10951   // On X86 with SSE2 support, we can transform this to a vector shift if
10952   // all elements are shifted by the same amount.  We can't do this in legalize
10953   // because the a constant vector is typically transformed to a constant pool
10954   // so we have no knowledge of the shift amount.
10955   if (!Subtarget->hasSSE2())
10956     return SDValue();
10957
10958   if (VT != MVT::v2i64 && VT != MVT::v4i32 && VT != MVT::v8i16)
10959     return SDValue();
10960
10961   SDValue ShAmtOp = N->getOperand(1);
10962   EVT EltVT = VT.getVectorElementType();
10963   DebugLoc DL = N->getDebugLoc();
10964   SDValue BaseShAmt = SDValue();
10965   if (ShAmtOp.getOpcode() == ISD::BUILD_VECTOR) {
10966     unsigned NumElts = VT.getVectorNumElements();
10967     unsigned i = 0;
10968     for (; i != NumElts; ++i) {
10969       SDValue Arg = ShAmtOp.getOperand(i);
10970       if (Arg.getOpcode() == ISD::UNDEF) continue;
10971       BaseShAmt = Arg;
10972       break;
10973     }
10974     for (; i != NumElts; ++i) {
10975       SDValue Arg = ShAmtOp.getOperand(i);
10976       if (Arg.getOpcode() == ISD::UNDEF) continue;
10977       if (Arg != BaseShAmt) {
10978         return SDValue();
10979       }
10980     }
10981   } else if (ShAmtOp.getOpcode() == ISD::VECTOR_SHUFFLE &&
10982              cast<ShuffleVectorSDNode>(ShAmtOp)->isSplat()) {
10983     SDValue InVec = ShAmtOp.getOperand(0);
10984     if (InVec.getOpcode() == ISD::BUILD_VECTOR) {
10985       unsigned NumElts = InVec.getValueType().getVectorNumElements();
10986       unsigned i = 0;
10987       for (; i != NumElts; ++i) {
10988         SDValue Arg = InVec.getOperand(i);
10989         if (Arg.getOpcode() == ISD::UNDEF) continue;
10990         BaseShAmt = Arg;
10991         break;
10992       }
10993     } else if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT) {
10994        if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(InVec.getOperand(2))) {
10995          unsigned SplatIdx= cast<ShuffleVectorSDNode>(ShAmtOp)->getSplatIndex();
10996          if (C->getZExtValue() == SplatIdx)
10997            BaseShAmt = InVec.getOperand(1);
10998        }
10999     }
11000     if (BaseShAmt.getNode() == 0)
11001       BaseShAmt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, EltVT, ShAmtOp,
11002                               DAG.getIntPtrConstant(0));
11003   } else
11004     return SDValue();
11005
11006   // The shift amount is an i32.
11007   if (EltVT.bitsGT(MVT::i32))
11008     BaseShAmt = DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, BaseShAmt);
11009   else if (EltVT.bitsLT(MVT::i32))
11010     BaseShAmt = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, BaseShAmt);
11011
11012   // The shift amount is identical so we can do a vector shift.
11013   SDValue  ValOp = N->getOperand(0);
11014   switch (N->getOpcode()) {
11015   default:
11016     llvm_unreachable("Unknown shift opcode!");
11017     break;
11018   case ISD::SHL:
11019     if (VT == MVT::v2i64)
11020       return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
11021                          DAG.getConstant(Intrinsic::x86_sse2_pslli_q, MVT::i32),
11022                          ValOp, BaseShAmt);
11023     if (VT == MVT::v4i32)
11024       return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
11025                          DAG.getConstant(Intrinsic::x86_sse2_pslli_d, MVT::i32),
11026                          ValOp, BaseShAmt);
11027     if (VT == MVT::v8i16)
11028       return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
11029                          DAG.getConstant(Intrinsic::x86_sse2_pslli_w, MVT::i32),
11030                          ValOp, BaseShAmt);
11031     break;
11032   case ISD::SRA:
11033     if (VT == MVT::v4i32)
11034       return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
11035                          DAG.getConstant(Intrinsic::x86_sse2_psrai_d, MVT::i32),
11036                          ValOp, BaseShAmt);
11037     if (VT == MVT::v8i16)
11038       return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
11039                          DAG.getConstant(Intrinsic::x86_sse2_psrai_w, MVT::i32),
11040                          ValOp, BaseShAmt);
11041     break;
11042   case ISD::SRL:
11043     if (VT == MVT::v2i64)
11044       return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
11045                          DAG.getConstant(Intrinsic::x86_sse2_psrli_q, MVT::i32),
11046                          ValOp, BaseShAmt);
11047     if (VT == MVT::v4i32)
11048       return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
11049                          DAG.getConstant(Intrinsic::x86_sse2_psrli_d, MVT::i32),
11050                          ValOp, BaseShAmt);
11051     if (VT ==  MVT::v8i16)
11052       return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
11053                          DAG.getConstant(Intrinsic::x86_sse2_psrli_w, MVT::i32),
11054                          ValOp, BaseShAmt);
11055     break;
11056   }
11057   return SDValue();
11058 }
11059
11060
11061 static SDValue PerformAndCombine(SDNode *N, SelectionDAG &DAG,
11062                                  TargetLowering::DAGCombinerInfo &DCI,
11063                                  const X86Subtarget *Subtarget) {
11064   if (DCI.isBeforeLegalizeOps())
11065     return SDValue();
11066   
11067   // Want to form PANDN nodes, in the hopes of then easily combining them with
11068   // OR and AND nodes to form PBLEND/PSIGN.
11069   EVT VT = N->getValueType(0);
11070   if (VT != MVT::v2i64)
11071     return SDValue();
11072   
11073   SDValue N0 = N->getOperand(0);
11074   SDValue N1 = N->getOperand(1);
11075   DebugLoc DL = N->getDebugLoc();
11076   
11077   // Check LHS for vnot
11078   if (N0.getOpcode() == ISD::XOR && 
11079       ISD::isBuildVectorAllOnes(N0.getOperand(1).getNode()))
11080     return DAG.getNode(X86ISD::PANDN, DL, VT, N0.getOperand(0), N1);
11081
11082   // Check RHS for vnot
11083   if (N1.getOpcode() == ISD::XOR &&
11084       ISD::isBuildVectorAllOnes(N1.getOperand(1).getNode()))
11085     return DAG.getNode(X86ISD::PANDN, DL, VT, N1.getOperand(0), N0);
11086   
11087   return SDValue();
11088 }
11089
11090 static SDValue PerformOrCombine(SDNode *N, SelectionDAG &DAG,
11091                                 TargetLowering::DAGCombinerInfo &DCI,
11092                                 const X86Subtarget *Subtarget) {
11093   if (DCI.isBeforeLegalizeOps())
11094     return SDValue();
11095
11096   EVT VT = N->getValueType(0);
11097   if (VT != MVT::i16 && VT != MVT::i32 && VT != MVT::i64 && VT != MVT::v2i64)
11098     return SDValue();
11099
11100   SDValue N0 = N->getOperand(0);
11101   SDValue N1 = N->getOperand(1);
11102   
11103   // look for psign/blend
11104   if (Subtarget->hasSSSE3()) {
11105     if (VT == MVT::v2i64) {
11106       // Canonicalize pandn to RHS
11107       if (N0.getOpcode() == X86ISD::PANDN)
11108         std::swap(N0, N1);
11109       // or (and (m, x), (pandn m, y))
11110       if (N0.getOpcode() == ISD::AND && N1.getOpcode() == X86ISD::PANDN) {
11111         SDValue Mask = N1.getOperand(0);
11112         SDValue X    = N1.getOperand(1);
11113         SDValue Y;
11114         if (N0.getOperand(0) == Mask)
11115           Y = N0.getOperand(1);
11116         if (N0.getOperand(1) == Mask)
11117           Y = N0.getOperand(0);
11118         
11119         // Check to see if the mask appeared in both the AND and PANDN and
11120         if (!Y.getNode())
11121           return SDValue();
11122         
11123         // Validate that X, Y, and Mask are BIT_CONVERTS, and see through them.
11124         if (Mask.getOpcode() != ISD::BITCAST ||
11125             X.getOpcode() != ISD::BITCAST ||
11126             Y.getOpcode() != ISD::BITCAST)
11127           return SDValue();
11128         
11129         // Look through mask bitcast.
11130         Mask = Mask.getOperand(0);
11131         EVT MaskVT = Mask.getValueType();
11132
11133         // Validate that the Mask operand is a vector sra node.  The sra node
11134         // will be an intrinsic.
11135         if (Mask.getOpcode() != ISD::INTRINSIC_WO_CHAIN)
11136           return SDValue();
11137         
11138         // FIXME: what to do for bytes, since there is a psignb/pblendvb, but
11139         // there is no psrai.b
11140         switch (cast<ConstantSDNode>(Mask.getOperand(0))->getZExtValue()) {
11141         case Intrinsic::x86_sse2_psrai_w:
11142         case Intrinsic::x86_sse2_psrai_d:
11143           break;
11144         default: return SDValue();
11145         }
11146         
11147         // Check that the SRA is all signbits.
11148         SDValue SraC = Mask.getOperand(2);
11149         unsigned SraAmt  = cast<ConstantSDNode>(SraC)->getZExtValue();
11150         unsigned EltBits = MaskVT.getVectorElementType().getSizeInBits();
11151         if ((SraAmt + 1) != EltBits)
11152           return SDValue();
11153         
11154         DebugLoc DL = N->getDebugLoc();
11155
11156         // Now we know we at least have a plendvb with the mask val.  See if
11157         // we can form a psignb/w/d.
11158         // psign = x.type == y.type == mask.type && y = sub(0, x);
11159         X = X.getOperand(0);
11160         Y = Y.getOperand(0);
11161         if (Y.getOpcode() == ISD::SUB && Y.getOperand(1) == X &&
11162             ISD::isBuildVectorAllZeros(Y.getOperand(0).getNode()) &&
11163             X.getValueType() == MaskVT && X.getValueType() == Y.getValueType()){
11164           unsigned Opc = 0;
11165           switch (EltBits) {
11166           case 8: Opc = X86ISD::PSIGNB; break;
11167           case 16: Opc = X86ISD::PSIGNW; break;
11168           case 32: Opc = X86ISD::PSIGND; break;
11169           default: break;
11170           }
11171           if (Opc) {
11172             SDValue Sign = DAG.getNode(Opc, DL, MaskVT, X, Mask.getOperand(1));
11173             return DAG.getNode(ISD::BITCAST, DL, MVT::v2i64, Sign);
11174           }
11175         }
11176         // PBLENDVB only available on SSE 4.1
11177         if (!Subtarget->hasSSE41())
11178           return SDValue();
11179         
11180         unsigned IID = Intrinsic::x86_sse41_pblendvb;
11181         X = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, X);
11182         Y = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, Y);
11183         Mask = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, Mask);
11184         Mask = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, MVT::v16i8,
11185                            DAG.getConstant(IID, MVT::i32), X, Y, Mask);
11186         return DAG.getNode(ISD::BITCAST, DL, MVT::v2i64, Mask);
11187       }
11188     }
11189   }
11190   
11191   // fold (or (x << c) | (y >> (64 - c))) ==> (shld64 x, y, c)
11192   if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL)
11193     std::swap(N0, N1);
11194   if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL)
11195     return SDValue();
11196   if (!N0.hasOneUse() || !N1.hasOneUse())
11197     return SDValue();
11198
11199   SDValue ShAmt0 = N0.getOperand(1);
11200   if (ShAmt0.getValueType() != MVT::i8)
11201     return SDValue();
11202   SDValue ShAmt1 = N1.getOperand(1);
11203   if (ShAmt1.getValueType() != MVT::i8)
11204     return SDValue();
11205   if (ShAmt0.getOpcode() == ISD::TRUNCATE)
11206     ShAmt0 = ShAmt0.getOperand(0);
11207   if (ShAmt1.getOpcode() == ISD::TRUNCATE)
11208     ShAmt1 = ShAmt1.getOperand(0);
11209
11210   DebugLoc DL = N->getDebugLoc();
11211   unsigned Opc = X86ISD::SHLD;
11212   SDValue Op0 = N0.getOperand(0);
11213   SDValue Op1 = N1.getOperand(0);
11214   if (ShAmt0.getOpcode() == ISD::SUB) {
11215     Opc = X86ISD::SHRD;
11216     std::swap(Op0, Op1);
11217     std::swap(ShAmt0, ShAmt1);
11218   }
11219
11220   unsigned Bits = VT.getSizeInBits();
11221   if (ShAmt1.getOpcode() == ISD::SUB) {
11222     SDValue Sum = ShAmt1.getOperand(0);
11223     if (ConstantSDNode *SumC = dyn_cast<ConstantSDNode>(Sum)) {
11224       SDValue ShAmt1Op1 = ShAmt1.getOperand(1);
11225       if (ShAmt1Op1.getNode()->getOpcode() == ISD::TRUNCATE)
11226         ShAmt1Op1 = ShAmt1Op1.getOperand(0);
11227       if (SumC->getSExtValue() == Bits && ShAmt1Op1 == ShAmt0)
11228         return DAG.getNode(Opc, DL, VT,
11229                            Op0, Op1,
11230                            DAG.getNode(ISD::TRUNCATE, DL,
11231                                        MVT::i8, ShAmt0));
11232     }
11233   } else if (ConstantSDNode *ShAmt1C = dyn_cast<ConstantSDNode>(ShAmt1)) {
11234     ConstantSDNode *ShAmt0C = dyn_cast<ConstantSDNode>(ShAmt0);
11235     if (ShAmt0C &&
11236         ShAmt0C->getSExtValue() + ShAmt1C->getSExtValue() == Bits)
11237       return DAG.getNode(Opc, DL, VT,
11238                          N0.getOperand(0), N1.getOperand(0),
11239                          DAG.getNode(ISD::TRUNCATE, DL,
11240                                        MVT::i8, ShAmt0));
11241   }
11242   
11243   return SDValue();
11244 }
11245
11246 /// PerformSTORECombine - Do target-specific dag combines on STORE nodes.
11247 static SDValue PerformSTORECombine(SDNode *N, SelectionDAG &DAG,
11248                                    const X86Subtarget *Subtarget) {
11249   // Turn load->store of MMX types into GPR load/stores.  This avoids clobbering
11250   // the FP state in cases where an emms may be missing.
11251   // A preferable solution to the general problem is to figure out the right
11252   // places to insert EMMS.  This qualifies as a quick hack.
11253
11254   // Similarly, turn load->store of i64 into double load/stores in 32-bit mode.
11255   StoreSDNode *St = cast<StoreSDNode>(N);
11256   EVT VT = St->getValue().getValueType();
11257   if (VT.getSizeInBits() != 64)
11258     return SDValue();
11259
11260   const Function *F = DAG.getMachineFunction().getFunction();
11261   bool NoImplicitFloatOps = F->hasFnAttr(Attribute::NoImplicitFloat);
11262   bool F64IsLegal = !UseSoftFloat && !NoImplicitFloatOps
11263     && Subtarget->hasSSE2();
11264   if ((VT.isVector() ||
11265        (VT == MVT::i64 && F64IsLegal && !Subtarget->is64Bit())) &&
11266       isa<LoadSDNode>(St->getValue()) &&
11267       !cast<LoadSDNode>(St->getValue())->isVolatile() &&
11268       St->getChain().hasOneUse() && !St->isVolatile()) {
11269     SDNode* LdVal = St->getValue().getNode();
11270     LoadSDNode *Ld = 0;
11271     int TokenFactorIndex = -1;
11272     SmallVector<SDValue, 8> Ops;
11273     SDNode* ChainVal = St->getChain().getNode();
11274     // Must be a store of a load.  We currently handle two cases:  the load
11275     // is a direct child, and it's under an intervening TokenFactor.  It is
11276     // possible to dig deeper under nested TokenFactors.
11277     if (ChainVal == LdVal)
11278       Ld = cast<LoadSDNode>(St->getChain());
11279     else if (St->getValue().hasOneUse() &&
11280              ChainVal->getOpcode() == ISD::TokenFactor) {
11281       for (unsigned i=0, e = ChainVal->getNumOperands(); i != e; ++i) {
11282         if (ChainVal->getOperand(i).getNode() == LdVal) {
11283           TokenFactorIndex = i;
11284           Ld = cast<LoadSDNode>(St->getValue());
11285         } else
11286           Ops.push_back(ChainVal->getOperand(i));
11287       }
11288     }
11289
11290     if (!Ld || !ISD::isNormalLoad(Ld))
11291       return SDValue();
11292
11293     // If this is not the MMX case, i.e. we are just turning i64 load/store
11294     // into f64 load/store, avoid the transformation if there are multiple
11295     // uses of the loaded value.
11296     if (!VT.isVector() && !Ld->hasNUsesOfValue(1, 0))
11297       return SDValue();
11298
11299     DebugLoc LdDL = Ld->getDebugLoc();
11300     DebugLoc StDL = N->getDebugLoc();
11301     // If we are a 64-bit capable x86, lower to a single movq load/store pair.
11302     // Otherwise, if it's legal to use f64 SSE instructions, use f64 load/store
11303     // pair instead.
11304     if (Subtarget->is64Bit() || F64IsLegal) {
11305       EVT LdVT = Subtarget->is64Bit() ? MVT::i64 : MVT::f64;
11306       SDValue NewLd = DAG.getLoad(LdVT, LdDL, Ld->getChain(), Ld->getBasePtr(),
11307                                   Ld->getPointerInfo(), Ld->isVolatile(),
11308                                   Ld->isNonTemporal(), Ld->getAlignment());
11309       SDValue NewChain = NewLd.getValue(1);
11310       if (TokenFactorIndex != -1) {
11311         Ops.push_back(NewChain);
11312         NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, &Ops[0],
11313                                Ops.size());
11314       }
11315       return DAG.getStore(NewChain, StDL, NewLd, St->getBasePtr(),
11316                           St->getPointerInfo(),
11317                           St->isVolatile(), St->isNonTemporal(),
11318                           St->getAlignment());
11319     }
11320
11321     // Otherwise, lower to two pairs of 32-bit loads / stores.
11322     SDValue LoAddr = Ld->getBasePtr();
11323     SDValue HiAddr = DAG.getNode(ISD::ADD, LdDL, MVT::i32, LoAddr,
11324                                  DAG.getConstant(4, MVT::i32));
11325
11326     SDValue LoLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), LoAddr,
11327                                Ld->getPointerInfo(),
11328                                Ld->isVolatile(), Ld->isNonTemporal(),
11329                                Ld->getAlignment());
11330     SDValue HiLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), HiAddr,
11331                                Ld->getPointerInfo().getWithOffset(4),
11332                                Ld->isVolatile(), Ld->isNonTemporal(),
11333                                MinAlign(Ld->getAlignment(), 4));
11334
11335     SDValue NewChain = LoLd.getValue(1);
11336     if (TokenFactorIndex != -1) {
11337       Ops.push_back(LoLd);
11338       Ops.push_back(HiLd);
11339       NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, &Ops[0],
11340                              Ops.size());
11341     }
11342
11343     LoAddr = St->getBasePtr();
11344     HiAddr = DAG.getNode(ISD::ADD, StDL, MVT::i32, LoAddr,
11345                          DAG.getConstant(4, MVT::i32));
11346
11347     SDValue LoSt = DAG.getStore(NewChain, StDL, LoLd, LoAddr,
11348                                 St->getPointerInfo(),
11349                                 St->isVolatile(), St->isNonTemporal(),
11350                                 St->getAlignment());
11351     SDValue HiSt = DAG.getStore(NewChain, StDL, HiLd, HiAddr,
11352                                 St->getPointerInfo().getWithOffset(4),
11353                                 St->isVolatile(),
11354                                 St->isNonTemporal(),
11355                                 MinAlign(St->getAlignment(), 4));
11356     return DAG.getNode(ISD::TokenFactor, StDL, MVT::Other, LoSt, HiSt);
11357   }
11358   return SDValue();
11359 }
11360
11361 /// PerformFORCombine - Do target-specific dag combines on X86ISD::FOR and
11362 /// X86ISD::FXOR nodes.
11363 static SDValue PerformFORCombine(SDNode *N, SelectionDAG &DAG) {
11364   assert(N->getOpcode() == X86ISD::FOR || N->getOpcode() == X86ISD::FXOR);
11365   // F[X]OR(0.0, x) -> x
11366   // F[X]OR(x, 0.0) -> x
11367   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
11368     if (C->getValueAPF().isPosZero())
11369       return N->getOperand(1);
11370   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
11371     if (C->getValueAPF().isPosZero())
11372       return N->getOperand(0);
11373   return SDValue();
11374 }
11375
11376 /// PerformFANDCombine - Do target-specific dag combines on X86ISD::FAND nodes.
11377 static SDValue PerformFANDCombine(SDNode *N, SelectionDAG &DAG) {
11378   // FAND(0.0, x) -> 0.0
11379   // FAND(x, 0.0) -> 0.0
11380   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
11381     if (C->getValueAPF().isPosZero())
11382       return N->getOperand(0);
11383   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
11384     if (C->getValueAPF().isPosZero())
11385       return N->getOperand(1);
11386   return SDValue();
11387 }
11388
11389 static SDValue PerformBTCombine(SDNode *N,
11390                                 SelectionDAG &DAG,
11391                                 TargetLowering::DAGCombinerInfo &DCI) {
11392   // BT ignores high bits in the bit index operand.
11393   SDValue Op1 = N->getOperand(1);
11394   if (Op1.hasOneUse()) {
11395     unsigned BitWidth = Op1.getValueSizeInBits();
11396     APInt DemandedMask = APInt::getLowBitsSet(BitWidth, Log2_32(BitWidth));
11397     APInt KnownZero, KnownOne;
11398     TargetLowering::TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(),
11399                                           !DCI.isBeforeLegalizeOps());
11400     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
11401     if (TLO.ShrinkDemandedConstant(Op1, DemandedMask) ||
11402         TLI.SimplifyDemandedBits(Op1, DemandedMask, KnownZero, KnownOne, TLO))
11403       DCI.CommitTargetLoweringOpt(TLO);
11404   }
11405   return SDValue();
11406 }
11407
11408 static SDValue PerformVZEXT_MOVLCombine(SDNode *N, SelectionDAG &DAG) {
11409   SDValue Op = N->getOperand(0);
11410   if (Op.getOpcode() == ISD::BITCAST)
11411     Op = Op.getOperand(0);
11412   EVT VT = N->getValueType(0), OpVT = Op.getValueType();
11413   if (Op.getOpcode() == X86ISD::VZEXT_LOAD &&
11414       VT.getVectorElementType().getSizeInBits() ==
11415       OpVT.getVectorElementType().getSizeInBits()) {
11416     return DAG.getNode(ISD::BITCAST, N->getDebugLoc(), VT, Op);
11417   }
11418   return SDValue();
11419 }
11420
11421 static SDValue PerformZExtCombine(SDNode *N, SelectionDAG &DAG) {
11422   // (i32 zext (and (i8  x86isd::setcc_carry), 1)) ->
11423   //           (and (i32 x86isd::setcc_carry), 1)
11424   // This eliminates the zext. This transformation is necessary because
11425   // ISD::SETCC is always legalized to i8.
11426   DebugLoc dl = N->getDebugLoc();
11427   SDValue N0 = N->getOperand(0);
11428   EVT VT = N->getValueType(0);
11429   if (N0.getOpcode() == ISD::AND &&
11430       N0.hasOneUse() &&
11431       N0.getOperand(0).hasOneUse()) {
11432     SDValue N00 = N0.getOperand(0);
11433     if (N00.getOpcode() != X86ISD::SETCC_CARRY)
11434       return SDValue();
11435     ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
11436     if (!C || C->getZExtValue() != 1)
11437       return SDValue();
11438     return DAG.getNode(ISD::AND, dl, VT,
11439                        DAG.getNode(X86ISD::SETCC_CARRY, dl, VT,
11440                                    N00.getOperand(0), N00.getOperand(1)),
11441                        DAG.getConstant(1, VT));
11442   }
11443
11444   return SDValue();
11445 }
11446
11447 SDValue X86TargetLowering::PerformDAGCombine(SDNode *N,
11448                                              DAGCombinerInfo &DCI) const {
11449   SelectionDAG &DAG = DCI.DAG;
11450   switch (N->getOpcode()) {
11451   default: break;
11452   case ISD::EXTRACT_VECTOR_ELT:
11453                         return PerformEXTRACT_VECTOR_ELTCombine(N, DAG, *this);
11454   case ISD::SELECT:         return PerformSELECTCombine(N, DAG, Subtarget);
11455   case X86ISD::CMOV:        return PerformCMOVCombine(N, DAG, DCI);
11456   case ISD::MUL:            return PerformMulCombine(N, DAG, DCI);
11457   case ISD::SHL:
11458   case ISD::SRA:
11459   case ISD::SRL:            return PerformShiftCombine(N, DAG, Subtarget);
11460   case ISD::AND:            return PerformAndCombine(N, DAG, DCI, Subtarget);
11461   case ISD::OR:             return PerformOrCombine(N, DAG, DCI, Subtarget);
11462   case ISD::STORE:          return PerformSTORECombine(N, DAG, Subtarget);
11463   case X86ISD::FXOR:
11464   case X86ISD::FOR:         return PerformFORCombine(N, DAG);
11465   case X86ISD::FAND:        return PerformFANDCombine(N, DAG);
11466   case X86ISD::BT:          return PerformBTCombine(N, DAG, DCI);
11467   case X86ISD::VZEXT_MOVL:  return PerformVZEXT_MOVLCombine(N, DAG);
11468   case ISD::ZERO_EXTEND:    return PerformZExtCombine(N, DAG);
11469   case X86ISD::SHUFPS:      // Handle all target specific shuffles
11470   case X86ISD::SHUFPD:
11471   case X86ISD::PALIGN:
11472   case X86ISD::PUNPCKHBW:
11473   case X86ISD::PUNPCKHWD:
11474   case X86ISD::PUNPCKHDQ:
11475   case X86ISD::PUNPCKHQDQ:
11476   case X86ISD::UNPCKHPS:
11477   case X86ISD::UNPCKHPD:
11478   case X86ISD::PUNPCKLBW:
11479   case X86ISD::PUNPCKLWD:
11480   case X86ISD::PUNPCKLDQ:
11481   case X86ISD::PUNPCKLQDQ:
11482   case X86ISD::UNPCKLPS:
11483   case X86ISD::UNPCKLPD:
11484   case X86ISD::MOVHLPS:
11485   case X86ISD::MOVLHPS:
11486   case X86ISD::PSHUFD:
11487   case X86ISD::PSHUFHW:
11488   case X86ISD::PSHUFLW:
11489   case X86ISD::MOVSS:
11490   case X86ISD::MOVSD:
11491   case ISD::VECTOR_SHUFFLE: return PerformShuffleCombine(N, DAG, *this);
11492   }
11493
11494   return SDValue();
11495 }
11496
11497 /// isTypeDesirableForOp - Return true if the target has native support for
11498 /// the specified value type and it is 'desirable' to use the type for the
11499 /// given node type. e.g. On x86 i16 is legal, but undesirable since i16
11500 /// instruction encodings are longer and some i16 instructions are slow.
11501 bool X86TargetLowering::isTypeDesirableForOp(unsigned Opc, EVT VT) const {
11502   if (!isTypeLegal(VT))
11503     return false;
11504   if (VT != MVT::i16)
11505     return true;
11506
11507   switch (Opc) {
11508   default:
11509     return true;
11510   case ISD::LOAD:
11511   case ISD::SIGN_EXTEND:
11512   case ISD::ZERO_EXTEND:
11513   case ISD::ANY_EXTEND:
11514   case ISD::SHL:
11515   case ISD::SRL:
11516   case ISD::SUB:
11517   case ISD::ADD:
11518   case ISD::MUL:
11519   case ISD::AND:
11520   case ISD::OR:
11521   case ISD::XOR:
11522     return false;
11523   }
11524 }
11525
11526 /// IsDesirableToPromoteOp - This method query the target whether it is
11527 /// beneficial for dag combiner to promote the specified node. If true, it
11528 /// should return the desired promotion type by reference.
11529 bool X86TargetLowering::IsDesirableToPromoteOp(SDValue Op, EVT &PVT) const {
11530   EVT VT = Op.getValueType();
11531   if (VT != MVT::i16)
11532     return false;
11533
11534   bool Promote = false;
11535   bool Commute = false;
11536   switch (Op.getOpcode()) {
11537   default: break;
11538   case ISD::LOAD: {
11539     LoadSDNode *LD = cast<LoadSDNode>(Op);
11540     // If the non-extending load has a single use and it's not live out, then it
11541     // might be folded.
11542     if (LD->getExtensionType() == ISD::NON_EXTLOAD /*&&
11543                                                      Op.hasOneUse()*/) {
11544       for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
11545              UE = Op.getNode()->use_end(); UI != UE; ++UI) {
11546         // The only case where we'd want to promote LOAD (rather then it being
11547         // promoted as an operand is when it's only use is liveout.
11548         if (UI->getOpcode() != ISD::CopyToReg)
11549           return false;
11550       }
11551     }
11552     Promote = true;
11553     break;
11554   }
11555   case ISD::SIGN_EXTEND:
11556   case ISD::ZERO_EXTEND:
11557   case ISD::ANY_EXTEND:
11558     Promote = true;
11559     break;
11560   case ISD::SHL:
11561   case ISD::SRL: {
11562     SDValue N0 = Op.getOperand(0);
11563     // Look out for (store (shl (load), x)).
11564     if (MayFoldLoad(N0) && MayFoldIntoStore(Op))
11565       return false;
11566     Promote = true;
11567     break;
11568   }
11569   case ISD::ADD:
11570   case ISD::MUL:
11571   case ISD::AND:
11572   case ISD::OR:
11573   case ISD::XOR:
11574     Commute = true;
11575     // fallthrough
11576   case ISD::SUB: {
11577     SDValue N0 = Op.getOperand(0);
11578     SDValue N1 = Op.getOperand(1);
11579     if (!Commute && MayFoldLoad(N1))
11580       return false;
11581     // Avoid disabling potential load folding opportunities.
11582     if (MayFoldLoad(N0) && (!isa<ConstantSDNode>(N1) || MayFoldIntoStore(Op)))
11583       return false;
11584     if (MayFoldLoad(N1) && (!isa<ConstantSDNode>(N0) || MayFoldIntoStore(Op)))
11585       return false;
11586     Promote = true;
11587   }
11588   }
11589
11590   PVT = MVT::i32;
11591   return Promote;
11592 }
11593
11594 //===----------------------------------------------------------------------===//
11595 //                           X86 Inline Assembly Support
11596 //===----------------------------------------------------------------------===//
11597
11598 static bool LowerToBSwap(CallInst *CI) {
11599   // FIXME: this should verify that we are targetting a 486 or better.  If not,
11600   // we will turn this bswap into something that will be lowered to logical ops
11601   // instead of emitting the bswap asm.  For now, we don't support 486 or lower
11602   // so don't worry about this.
11603
11604   // Verify this is a simple bswap.
11605   if (CI->getNumArgOperands() != 1 ||
11606       CI->getType() != CI->getArgOperand(0)->getType() ||
11607       !CI->getType()->isIntegerTy())
11608     return false;
11609
11610   const IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
11611   if (!Ty || Ty->getBitWidth() % 16 != 0)
11612     return false;
11613
11614   // Okay, we can do this xform, do so now.
11615   const Type *Tys[] = { Ty };
11616   Module *M = CI->getParent()->getParent()->getParent();
11617   Constant *Int = Intrinsic::getDeclaration(M, Intrinsic::bswap, Tys, 1);
11618
11619   Value *Op = CI->getArgOperand(0);
11620   Op = CallInst::Create(Int, Op, CI->getName(), CI);
11621
11622   CI->replaceAllUsesWith(Op);
11623   CI->eraseFromParent();
11624   return true;
11625 }
11626
11627 bool X86TargetLowering::ExpandInlineAsm(CallInst *CI) const {
11628   InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue());
11629   InlineAsm::ConstraintInfoVector Constraints = IA->ParseConstraints();
11630
11631   std::string AsmStr = IA->getAsmString();
11632
11633   // TODO: should remove alternatives from the asmstring: "foo {a|b}" -> "foo a"
11634   SmallVector<StringRef, 4> AsmPieces;
11635   SplitString(AsmStr, AsmPieces, ";\n");
11636
11637   switch (AsmPieces.size()) {
11638   default: return false;
11639   case 1:
11640     AsmStr = AsmPieces[0];
11641     AsmPieces.clear();
11642     SplitString(AsmStr, AsmPieces, " \t");  // Split with whitespace.
11643
11644     // bswap $0
11645     if (AsmPieces.size() == 2 &&
11646         (AsmPieces[0] == "bswap" ||
11647          AsmPieces[0] == "bswapq" ||
11648          AsmPieces[0] == "bswapl") &&
11649         (AsmPieces[1] == "$0" ||
11650          AsmPieces[1] == "${0:q}")) {
11651       // No need to check constraints, nothing other than the equivalent of
11652       // "=r,0" would be valid here.
11653       return LowerToBSwap(CI);
11654     }
11655     // rorw $$8, ${0:w}  -->  llvm.bswap.i16
11656     if (CI->getType()->isIntegerTy(16) &&
11657         AsmPieces.size() == 3 &&
11658         (AsmPieces[0] == "rorw" || AsmPieces[0] == "rolw") &&
11659         AsmPieces[1] == "$$8," &&
11660         AsmPieces[2] == "${0:w}" &&
11661         IA->getConstraintString().compare(0, 5, "=r,0,") == 0) {
11662       AsmPieces.clear();
11663       const std::string &Constraints = IA->getConstraintString();
11664       SplitString(StringRef(Constraints).substr(5), AsmPieces, ",");
11665       std::sort(AsmPieces.begin(), AsmPieces.end());
11666       if (AsmPieces.size() == 4 &&
11667           AsmPieces[0] == "~{cc}" &&
11668           AsmPieces[1] == "~{dirflag}" &&
11669           AsmPieces[2] == "~{flags}" &&
11670           AsmPieces[3] == "~{fpsr}") {
11671         return LowerToBSwap(CI);
11672       }
11673     }
11674     break;
11675   case 3:
11676     if (CI->getType()->isIntegerTy(32) &&
11677         IA->getConstraintString().compare(0, 5, "=r,0,") == 0) {
11678       SmallVector<StringRef, 4> Words;
11679       SplitString(AsmPieces[0], Words, " \t,");
11680       if (Words.size() == 3 && Words[0] == "rorw" && Words[1] == "$$8" &&
11681           Words[2] == "${0:w}") {
11682         Words.clear();
11683         SplitString(AsmPieces[1], Words, " \t,");
11684         if (Words.size() == 3 && Words[0] == "rorl" && Words[1] == "$$16" &&
11685             Words[2] == "$0") {
11686           Words.clear();
11687           SplitString(AsmPieces[2], Words, " \t,");
11688           if (Words.size() == 3 && Words[0] == "rorw" && Words[1] == "$$8" &&
11689               Words[2] == "${0:w}") {
11690             AsmPieces.clear();
11691             const std::string &Constraints = IA->getConstraintString();
11692             SplitString(StringRef(Constraints).substr(5), AsmPieces, ",");
11693             std::sort(AsmPieces.begin(), AsmPieces.end());
11694             if (AsmPieces.size() == 4 &&
11695                 AsmPieces[0] == "~{cc}" &&
11696                 AsmPieces[1] == "~{dirflag}" &&
11697                 AsmPieces[2] == "~{flags}" &&
11698                 AsmPieces[3] == "~{fpsr}") {
11699               return LowerToBSwap(CI);
11700             }
11701           }
11702         }
11703       }
11704     }
11705     if (CI->getType()->isIntegerTy(64) &&
11706         Constraints.size() >= 2 &&
11707         Constraints[0].Codes.size() == 1 && Constraints[0].Codes[0] == "A" &&
11708         Constraints[1].Codes.size() == 1 && Constraints[1].Codes[0] == "0") {
11709       // bswap %eax / bswap %edx / xchgl %eax, %edx  -> llvm.bswap.i64
11710       SmallVector<StringRef, 4> Words;
11711       SplitString(AsmPieces[0], Words, " \t");
11712       if (Words.size() == 2 && Words[0] == "bswap" && Words[1] == "%eax") {
11713         Words.clear();
11714         SplitString(AsmPieces[1], Words, " \t");
11715         if (Words.size() == 2 && Words[0] == "bswap" && Words[1] == "%edx") {
11716           Words.clear();
11717           SplitString(AsmPieces[2], Words, " \t,");
11718           if (Words.size() == 3 && Words[0] == "xchgl" && Words[1] == "%eax" &&
11719               Words[2] == "%edx") {
11720             return LowerToBSwap(CI);
11721           }
11722         }
11723       }
11724     }
11725     break;
11726   }
11727   return false;
11728 }
11729
11730
11731
11732 /// getConstraintType - Given a constraint letter, return the type of
11733 /// constraint it is for this target.
11734 X86TargetLowering::ConstraintType
11735 X86TargetLowering::getConstraintType(const std::string &Constraint) const {
11736   if (Constraint.size() == 1) {
11737     switch (Constraint[0]) {
11738     case 'R':
11739     case 'q':
11740     case 'Q':
11741     case 'f':
11742     case 't':
11743     case 'u':
11744     case 'y':
11745     case 'x':
11746     case 'Y':
11747       return C_RegisterClass;
11748     case 'a':
11749     case 'b':
11750     case 'c':
11751     case 'd':
11752     case 'S':
11753     case 'D':
11754     case 'A':
11755       return C_Register;
11756     case 'I':
11757     case 'J':
11758     case 'K':
11759     case 'L':
11760     case 'M':
11761     case 'N':
11762     case 'G':
11763     case 'C':
11764     case 'e':
11765     case 'Z':
11766       return C_Other;
11767     default:
11768       break;
11769     }
11770   }
11771   return TargetLowering::getConstraintType(Constraint);
11772 }
11773
11774 /// Examine constraint type and operand type and determine a weight value.
11775 /// This object must already have been set up with the operand type
11776 /// and the current alternative constraint selected.
11777 TargetLowering::ConstraintWeight
11778   X86TargetLowering::getSingleConstraintMatchWeight(
11779     AsmOperandInfo &info, const char *constraint) const {
11780   ConstraintWeight weight = CW_Invalid;
11781   Value *CallOperandVal = info.CallOperandVal;
11782     // If we don't have a value, we can't do a match,
11783     // but allow it at the lowest weight.
11784   if (CallOperandVal == NULL)
11785     return CW_Default;
11786   const Type *type = CallOperandVal->getType();
11787   // Look at the constraint type.
11788   switch (*constraint) {
11789   default:
11790     weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
11791   case 'R':
11792   case 'q':
11793   case 'Q':
11794   case 'a':
11795   case 'b':
11796   case 'c':
11797   case 'd':
11798   case 'S':
11799   case 'D':
11800   case 'A':
11801     if (CallOperandVal->getType()->isIntegerTy())
11802       weight = CW_SpecificReg;
11803     break;
11804   case 'f':
11805   case 't':
11806   case 'u':
11807       if (type->isFloatingPointTy())
11808         weight = CW_SpecificReg;
11809       break;
11810   case 'y':
11811       if (type->isX86_MMXTy() && !DisableMMX && Subtarget->hasMMX())
11812         weight = CW_SpecificReg;
11813       break;
11814   case 'x':
11815   case 'Y':
11816     if ((type->getPrimitiveSizeInBits() == 128) && Subtarget->hasXMM())
11817       weight = CW_Register;
11818     break;
11819   case 'I':
11820     if (ConstantInt *C = dyn_cast<ConstantInt>(info.CallOperandVal)) {
11821       if (C->getZExtValue() <= 31)
11822         weight = CW_Constant;
11823     }
11824     break;
11825   case 'J':
11826     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
11827       if (C->getZExtValue() <= 63)
11828         weight = CW_Constant;
11829     }
11830     break;
11831   case 'K':
11832     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
11833       if ((C->getSExtValue() >= -0x80) && (C->getSExtValue() <= 0x7f))
11834         weight = CW_Constant;
11835     }
11836     break;
11837   case 'L':
11838     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
11839       if ((C->getZExtValue() == 0xff) || (C->getZExtValue() == 0xffff))
11840         weight = CW_Constant;
11841     }
11842     break;
11843   case 'M':
11844     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
11845       if (C->getZExtValue() <= 3)
11846         weight = CW_Constant;
11847     }
11848     break;
11849   case 'N':
11850     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
11851       if (C->getZExtValue() <= 0xff)
11852         weight = CW_Constant;
11853     }
11854     break;
11855   case 'G':
11856   case 'C':
11857     if (dyn_cast<ConstantFP>(CallOperandVal)) {
11858       weight = CW_Constant;
11859     }
11860     break;
11861   case 'e':
11862     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
11863       if ((C->getSExtValue() >= -0x80000000LL) &&
11864           (C->getSExtValue() <= 0x7fffffffLL))
11865         weight = CW_Constant;
11866     }
11867     break;
11868   case 'Z':
11869     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
11870       if (C->getZExtValue() <= 0xffffffff)
11871         weight = CW_Constant;
11872     }
11873     break;
11874   }
11875   return weight;
11876 }
11877
11878 /// LowerXConstraint - try to replace an X constraint, which matches anything,
11879 /// with another that has more specific requirements based on the type of the
11880 /// corresponding operand.
11881 const char *X86TargetLowering::
11882 LowerXConstraint(EVT ConstraintVT) const {
11883   // FP X constraints get lowered to SSE1/2 registers if available, otherwise
11884   // 'f' like normal targets.
11885   if (ConstraintVT.isFloatingPoint()) {
11886     if (Subtarget->hasXMMInt())
11887       return "Y";
11888     if (Subtarget->hasXMM())
11889       return "x";
11890   }
11891
11892   return TargetLowering::LowerXConstraint(ConstraintVT);
11893 }
11894
11895 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
11896 /// vector.  If it is invalid, don't add anything to Ops.
11897 void X86TargetLowering::LowerAsmOperandForConstraint(SDValue Op,
11898                                                      char Constraint,
11899                                                      std::vector<SDValue>&Ops,
11900                                                      SelectionDAG &DAG) const {
11901   SDValue Result(0, 0);
11902
11903   switch (Constraint) {
11904   default: break;
11905   case 'I':
11906     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
11907       if (C->getZExtValue() <= 31) {
11908         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
11909         break;
11910       }
11911     }
11912     return;
11913   case 'J':
11914     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
11915       if (C->getZExtValue() <= 63) {
11916         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
11917         break;
11918       }
11919     }
11920     return;
11921   case 'K':
11922     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
11923       if ((int8_t)C->getSExtValue() == C->getSExtValue()) {
11924         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
11925         break;
11926       }
11927     }
11928     return;
11929   case 'N':
11930     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
11931       if (C->getZExtValue() <= 255) {
11932         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
11933         break;
11934       }
11935     }
11936     return;
11937   case 'e': {
11938     // 32-bit signed value
11939     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
11940       if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
11941                                            C->getSExtValue())) {
11942         // Widen to 64 bits here to get it sign extended.
11943         Result = DAG.getTargetConstant(C->getSExtValue(), MVT::i64);
11944         break;
11945       }
11946     // FIXME gcc accepts some relocatable values here too, but only in certain
11947     // memory models; it's complicated.
11948     }
11949     return;
11950   }
11951   case 'Z': {
11952     // 32-bit unsigned value
11953     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
11954       if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
11955                                            C->getZExtValue())) {
11956         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
11957         break;
11958       }
11959     }
11960     // FIXME gcc accepts some relocatable values here too, but only in certain
11961     // memory models; it's complicated.
11962     return;
11963   }
11964   case 'i': {
11965     // Literal immediates are always ok.
11966     if (ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op)) {
11967       // Widen to 64 bits here to get it sign extended.
11968       Result = DAG.getTargetConstant(CST->getSExtValue(), MVT::i64);
11969       break;
11970     }
11971
11972     // In any sort of PIC mode addresses need to be computed at runtime by
11973     // adding in a register or some sort of table lookup.  These can't
11974     // be used as immediates.
11975     if (Subtarget->isPICStyleGOT() || Subtarget->isPICStyleStubPIC())
11976       return;
11977
11978     // If we are in non-pic codegen mode, we allow the address of a global (with
11979     // an optional displacement) to be used with 'i'.
11980     GlobalAddressSDNode *GA = 0;
11981     int64_t Offset = 0;
11982
11983     // Match either (GA), (GA+C), (GA+C1+C2), etc.
11984     while (1) {
11985       if ((GA = dyn_cast<GlobalAddressSDNode>(Op))) {
11986         Offset += GA->getOffset();
11987         break;
11988       } else if (Op.getOpcode() == ISD::ADD) {
11989         if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
11990           Offset += C->getZExtValue();
11991           Op = Op.getOperand(0);
11992           continue;
11993         }
11994       } else if (Op.getOpcode() == ISD::SUB) {
11995         if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
11996           Offset += -C->getZExtValue();
11997           Op = Op.getOperand(0);
11998           continue;
11999         }
12000       }
12001
12002       // Otherwise, this isn't something we can handle, reject it.
12003       return;
12004     }
12005
12006     const GlobalValue *GV = GA->getGlobal();
12007     // If we require an extra load to get this address, as in PIC mode, we
12008     // can't accept it.
12009     if (isGlobalStubReference(Subtarget->ClassifyGlobalReference(GV,
12010                                                         getTargetMachine())))
12011       return;
12012
12013     Result = DAG.getTargetGlobalAddress(GV, Op.getDebugLoc(),
12014                                         GA->getValueType(0), Offset);
12015     break;
12016   }
12017   }
12018
12019   if (Result.getNode()) {
12020     Ops.push_back(Result);
12021     return;
12022   }
12023   return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
12024 }
12025
12026 std::vector<unsigned> X86TargetLowering::
12027 getRegClassForInlineAsmConstraint(const std::string &Constraint,
12028                                   EVT VT) const {
12029   if (Constraint.size() == 1) {
12030     // FIXME: not handling fp-stack yet!
12031     switch (Constraint[0]) {      // GCC X86 Constraint Letters
12032     default: break;  // Unknown constraint letter
12033     case 'q':   // GENERAL_REGS in 64-bit mode, Q_REGS in 32-bit mode.
12034       if (Subtarget->is64Bit()) {
12035         if (VT == MVT::i32)
12036           return make_vector<unsigned>(X86::EAX, X86::EDX, X86::ECX, X86::EBX,
12037                                        X86::ESI, X86::EDI, X86::R8D, X86::R9D,
12038                                        X86::R10D,X86::R11D,X86::R12D,
12039                                        X86::R13D,X86::R14D,X86::R15D,
12040                                        X86::EBP, X86::ESP, 0);
12041         else if (VT == MVT::i16)
12042           return make_vector<unsigned>(X86::AX,  X86::DX,  X86::CX, X86::BX,
12043                                        X86::SI,  X86::DI,  X86::R8W,X86::R9W,
12044                                        X86::R10W,X86::R11W,X86::R12W,
12045                                        X86::R13W,X86::R14W,X86::R15W,
12046                                        X86::BP,  X86::SP, 0);
12047         else if (VT == MVT::i8)
12048           return make_vector<unsigned>(X86::AL,  X86::DL,  X86::CL, X86::BL,
12049                                        X86::SIL, X86::DIL, X86::R8B,X86::R9B,
12050                                        X86::R10B,X86::R11B,X86::R12B,
12051                                        X86::R13B,X86::R14B,X86::R15B,
12052                                        X86::BPL, X86::SPL, 0);
12053
12054         else if (VT == MVT::i64)
12055           return make_vector<unsigned>(X86::RAX, X86::RDX, X86::RCX, X86::RBX,
12056                                        X86::RSI, X86::RDI, X86::R8,  X86::R9,
12057                                        X86::R10, X86::R11, X86::R12,
12058                                        X86::R13, X86::R14, X86::R15,
12059                                        X86::RBP, X86::RSP, 0);
12060
12061         break;
12062       }
12063       // 32-bit fallthrough
12064     case 'Q':   // Q_REGS
12065       if (VT == MVT::i32)
12066         return make_vector<unsigned>(X86::EAX, X86::EDX, X86::ECX, X86::EBX, 0);
12067       else if (VT == MVT::i16)
12068         return make_vector<unsigned>(X86::AX, X86::DX, X86::CX, X86::BX, 0);
12069       else if (VT == MVT::i8)
12070         return make_vector<unsigned>(X86::AL, X86::DL, X86::CL, X86::BL, 0);
12071       else if (VT == MVT::i64)
12072         return make_vector<unsigned>(X86::RAX, X86::RDX, X86::RCX, X86::RBX, 0);
12073       break;
12074     }
12075   }
12076
12077   return std::vector<unsigned>();
12078 }
12079
12080 std::pair<unsigned, const TargetRegisterClass*>
12081 X86TargetLowering::getRegForInlineAsmConstraint(const std::string &Constraint,
12082                                                 EVT VT) const {
12083   // First, see if this is a constraint that directly corresponds to an LLVM
12084   // register class.
12085   if (Constraint.size() == 1) {
12086     // GCC Constraint Letters
12087     switch (Constraint[0]) {
12088     default: break;
12089     case 'r':   // GENERAL_REGS
12090     case 'l':   // INDEX_REGS
12091       if (VT == MVT::i8)
12092         return std::make_pair(0U, X86::GR8RegisterClass);
12093       if (VT == MVT::i16)
12094         return std::make_pair(0U, X86::GR16RegisterClass);
12095       if (VT == MVT::i32 || !Subtarget->is64Bit())
12096         return std::make_pair(0U, X86::GR32RegisterClass);
12097       return std::make_pair(0U, X86::GR64RegisterClass);
12098     case 'R':   // LEGACY_REGS
12099       if (VT == MVT::i8)
12100         return std::make_pair(0U, X86::GR8_NOREXRegisterClass);
12101       if (VT == MVT::i16)
12102         return std::make_pair(0U, X86::GR16_NOREXRegisterClass);
12103       if (VT == MVT::i32 || !Subtarget->is64Bit())
12104         return std::make_pair(0U, X86::GR32_NOREXRegisterClass);
12105       return std::make_pair(0U, X86::GR64_NOREXRegisterClass);
12106     case 'f':  // FP Stack registers.
12107       // If SSE is enabled for this VT, use f80 to ensure the isel moves the
12108       // value to the correct fpstack register class.
12109       if (VT == MVT::f32 && !isScalarFPTypeInSSEReg(VT))
12110         return std::make_pair(0U, X86::RFP32RegisterClass);
12111       if (VT == MVT::f64 && !isScalarFPTypeInSSEReg(VT))
12112         return std::make_pair(0U, X86::RFP64RegisterClass);
12113       return std::make_pair(0U, X86::RFP80RegisterClass);
12114     case 'y':   // MMX_REGS if MMX allowed.
12115       if (!Subtarget->hasMMX()) break;
12116       return std::make_pair(0U, X86::VR64RegisterClass);
12117     case 'Y':   // SSE_REGS if SSE2 allowed
12118       if (!Subtarget->hasXMMInt()) break;
12119       // FALL THROUGH.
12120     case 'x':   // SSE_REGS if SSE1 allowed
12121       if (!Subtarget->hasXMM()) break;
12122
12123       switch (VT.getSimpleVT().SimpleTy) {
12124       default: break;
12125       // Scalar SSE types.
12126       case MVT::f32:
12127       case MVT::i32:
12128         return std::make_pair(0U, X86::FR32RegisterClass);
12129       case MVT::f64:
12130       case MVT::i64:
12131         return std::make_pair(0U, X86::FR64RegisterClass);
12132       // Vector types.
12133       case MVT::v16i8:
12134       case MVT::v8i16:
12135       case MVT::v4i32:
12136       case MVT::v2i64:
12137       case MVT::v4f32:
12138       case MVT::v2f64:
12139         return std::make_pair(0U, X86::VR128RegisterClass);
12140       }
12141       break;
12142     }
12143   }
12144
12145   // Use the default implementation in TargetLowering to convert the register
12146   // constraint into a member of a register class.
12147   std::pair<unsigned, const TargetRegisterClass*> Res;
12148   Res = TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
12149
12150   // Not found as a standard register?
12151   if (Res.second == 0) {
12152     // Map st(0) -> st(7) -> ST0
12153     if (Constraint.size() == 7 && Constraint[0] == '{' &&
12154         tolower(Constraint[1]) == 's' &&
12155         tolower(Constraint[2]) == 't' &&
12156         Constraint[3] == '(' &&
12157         (Constraint[4] >= '0' && Constraint[4] <= '7') &&
12158         Constraint[5] == ')' &&
12159         Constraint[6] == '}') {
12160
12161       Res.first = X86::ST0+Constraint[4]-'0';
12162       Res.second = X86::RFP80RegisterClass;
12163       return Res;
12164     }
12165
12166     // GCC allows "st(0)" to be called just plain "st".
12167     if (StringRef("{st}").equals_lower(Constraint)) {
12168       Res.first = X86::ST0;
12169       Res.second = X86::RFP80RegisterClass;
12170       return Res;
12171     }
12172
12173     // flags -> EFLAGS
12174     if (StringRef("{flags}").equals_lower(Constraint)) {
12175       Res.first = X86::EFLAGS;
12176       Res.second = X86::CCRRegisterClass;
12177       return Res;
12178     }
12179
12180     // 'A' means EAX + EDX.
12181     if (Constraint == "A") {
12182       Res.first = X86::EAX;
12183       Res.second = X86::GR32_ADRegisterClass;
12184       return Res;
12185     }
12186     return Res;
12187   }
12188
12189   // Otherwise, check to see if this is a register class of the wrong value
12190   // type.  For example, we want to map "{ax},i32" -> {eax}, we don't want it to
12191   // turn into {ax},{dx}.
12192   if (Res.second->hasType(VT))
12193     return Res;   // Correct type already, nothing to do.
12194
12195   // All of the single-register GCC register classes map their values onto
12196   // 16-bit register pieces "ax","dx","cx","bx","si","di","bp","sp".  If we
12197   // really want an 8-bit or 32-bit register, map to the appropriate register
12198   // class and return the appropriate register.
12199   if (Res.second == X86::GR16RegisterClass) {
12200     if (VT == MVT::i8) {
12201       unsigned DestReg = 0;
12202       switch (Res.first) {
12203       default: break;
12204       case X86::AX: DestReg = X86::AL; break;
12205       case X86::DX: DestReg = X86::DL; break;
12206       case X86::CX: DestReg = X86::CL; break;
12207       case X86::BX: DestReg = X86::BL; break;
12208       }
12209       if (DestReg) {
12210         Res.first = DestReg;
12211         Res.second = X86::GR8RegisterClass;
12212       }
12213     } else if (VT == MVT::i32) {
12214       unsigned DestReg = 0;
12215       switch (Res.first) {
12216       default: break;
12217       case X86::AX: DestReg = X86::EAX; break;
12218       case X86::DX: DestReg = X86::EDX; break;
12219       case X86::CX: DestReg = X86::ECX; break;
12220       case X86::BX: DestReg = X86::EBX; break;
12221       case X86::SI: DestReg = X86::ESI; break;
12222       case X86::DI: DestReg = X86::EDI; break;
12223       case X86::BP: DestReg = X86::EBP; break;
12224       case X86::SP: DestReg = X86::ESP; break;
12225       }
12226       if (DestReg) {
12227         Res.first = DestReg;
12228         Res.second = X86::GR32RegisterClass;
12229       }
12230     } else if (VT == MVT::i64) {
12231       unsigned DestReg = 0;
12232       switch (Res.first) {
12233       default: break;
12234       case X86::AX: DestReg = X86::RAX; break;
12235       case X86::DX: DestReg = X86::RDX; break;
12236       case X86::CX: DestReg = X86::RCX; break;
12237       case X86::BX: DestReg = X86::RBX; break;
12238       case X86::SI: DestReg = X86::RSI; break;
12239       case X86::DI: DestReg = X86::RDI; break;
12240       case X86::BP: DestReg = X86::RBP; break;
12241       case X86::SP: DestReg = X86::RSP; break;
12242       }
12243       if (DestReg) {
12244         Res.first = DestReg;
12245         Res.second = X86::GR64RegisterClass;
12246       }
12247     }
12248   } else if (Res.second == X86::FR32RegisterClass ||
12249              Res.second == X86::FR64RegisterClass ||
12250              Res.second == X86::VR128RegisterClass) {
12251     // Handle references to XMM physical registers that got mapped into the
12252     // wrong class.  This can happen with constraints like {xmm0} where the
12253     // target independent register mapper will just pick the first match it can
12254     // find, ignoring the required type.
12255     if (VT == MVT::f32)
12256       Res.second = X86::FR32RegisterClass;
12257     else if (VT == MVT::f64)
12258       Res.second = X86::FR64RegisterClass;
12259     else if (X86::VR128RegisterClass->hasType(VT))
12260       Res.second = X86::VR128RegisterClass;
12261   }
12262
12263   return Res;
12264 }