BUILD_VECTOR was missing out on some prime opportunities to use SSE 4.1 inserts.
[oota-llvm.git] / lib / Target / X86 / X86ISelLowering.cpp
1 //===-- X86ISelLowering.cpp - X86 DAG Lowering Implementation -------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file defines the interfaces that X86 uses to lower LLVM code into a
11 // selection DAG.
12 //
13 //===----------------------------------------------------------------------===//
14
15 #define DEBUG_TYPE "x86-isel"
16 #include "X86.h"
17 #include "X86InstrBuilder.h"
18 #include "X86ISelLowering.h"
19 #include "X86TargetMachine.h"
20 #include "X86TargetObjectFile.h"
21 #include "llvm/CallingConv.h"
22 #include "llvm/Constants.h"
23 #include "llvm/DerivedTypes.h"
24 #include "llvm/GlobalAlias.h"
25 #include "llvm/GlobalVariable.h"
26 #include "llvm/Function.h"
27 #include "llvm/Instructions.h"
28 #include "llvm/Intrinsics.h"
29 #include "llvm/LLVMContext.h"
30 #include "llvm/CodeGen/MachineFrameInfo.h"
31 #include "llvm/CodeGen/MachineFunction.h"
32 #include "llvm/CodeGen/MachineInstrBuilder.h"
33 #include "llvm/CodeGen/MachineJumpTableInfo.h"
34 #include "llvm/CodeGen/MachineModuleInfo.h"
35 #include "llvm/CodeGen/MachineRegisterInfo.h"
36 #include "llvm/CodeGen/PseudoSourceValue.h"
37 #include "llvm/MC/MCAsmInfo.h"
38 #include "llvm/MC/MCContext.h"
39 #include "llvm/MC/MCExpr.h"
40 #include "llvm/MC/MCSymbol.h"
41 #include "llvm/ADT/BitVector.h"
42 #include "llvm/ADT/SmallSet.h"
43 #include "llvm/ADT/Statistic.h"
44 #include "llvm/ADT/StringExtras.h"
45 #include "llvm/ADT/VectorExtras.h"
46 #include "llvm/Support/CommandLine.h"
47 #include "llvm/Support/Debug.h"
48 #include "llvm/Support/Dwarf.h"
49 #include "llvm/Support/ErrorHandling.h"
50 #include "llvm/Support/MathExtras.h"
51 #include "llvm/Support/raw_ostream.h"
52 using namespace llvm;
53 using namespace dwarf;
54
55 STATISTIC(NumTailCalls, "Number of tail calls");
56
57 static cl::opt<bool>
58 DisableMMX("disable-mmx", cl::Hidden, cl::desc("Disable use of MMX"));
59
60 // Disable16Bit - 16-bit operations typically have a larger encoding than
61 // corresponding 32-bit instructions, and 16-bit code is slow on some
62 // processors. This is an experimental flag to disable 16-bit operations
63 // (which forces them to be Legalized to 32-bit operations).
64 static cl::opt<bool>
65 Disable16Bit("disable-16bit", cl::Hidden,
66              cl::desc("Disable use of 16-bit instructions"));
67
68 // Forward declarations.
69 static SDValue getMOVL(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
70                        SDValue V2);
71
72 static TargetLoweringObjectFile *createTLOF(X86TargetMachine &TM) {
73   switch (TM.getSubtarget<X86Subtarget>().TargetType) {
74   default: llvm_unreachable("unknown subtarget type");
75   case X86Subtarget::isDarwin:
76     if (TM.getSubtarget<X86Subtarget>().is64Bit())
77       return new X8664_MachoTargetObjectFile();
78     return new TargetLoweringObjectFileMachO();
79   case X86Subtarget::isELF:
80    if (TM.getSubtarget<X86Subtarget>().is64Bit())
81      return new X8664_ELFTargetObjectFile(TM);
82     return new X8632_ELFTargetObjectFile(TM);
83   case X86Subtarget::isMingw:
84   case X86Subtarget::isCygwin:
85   case X86Subtarget::isWindows:
86     return new TargetLoweringObjectFileCOFF();
87   }
88 }
89
90 X86TargetLowering::X86TargetLowering(X86TargetMachine &TM)
91   : TargetLowering(TM, createTLOF(TM)) {
92   Subtarget = &TM.getSubtarget<X86Subtarget>();
93   X86ScalarSSEf64 = Subtarget->hasSSE2();
94   X86ScalarSSEf32 = Subtarget->hasSSE1();
95   X86StackPtr = Subtarget->is64Bit() ? X86::RSP : X86::ESP;
96
97   RegInfo = TM.getRegisterInfo();
98   TD = getTargetData();
99
100   // Set up the TargetLowering object.
101
102   // X86 is weird, it always uses i8 for shift amounts and setcc results.
103   setShiftAmountType(MVT::i8);
104   setBooleanContents(ZeroOrOneBooleanContent);
105   setSchedulingPreference(SchedulingForRegPressure);
106   setStackPointerRegisterToSaveRestore(X86StackPtr);
107
108   if (Subtarget->isTargetDarwin()) {
109     // Darwin should use _setjmp/_longjmp instead of setjmp/longjmp.
110     setUseUnderscoreSetJmp(false);
111     setUseUnderscoreLongJmp(false);
112   } else if (Subtarget->isTargetMingw()) {
113     // MS runtime is weird: it exports _setjmp, but longjmp!
114     setUseUnderscoreSetJmp(true);
115     setUseUnderscoreLongJmp(false);
116   } else {
117     setUseUnderscoreSetJmp(true);
118     setUseUnderscoreLongJmp(true);
119   }
120
121   // Set up the register classes.
122   addRegisterClass(MVT::i8, X86::GR8RegisterClass);
123   if (!Disable16Bit)
124     addRegisterClass(MVT::i16, X86::GR16RegisterClass);
125   addRegisterClass(MVT::i32, X86::GR32RegisterClass);
126   if (Subtarget->is64Bit())
127     addRegisterClass(MVT::i64, X86::GR64RegisterClass);
128
129   setLoadExtAction(ISD::SEXTLOAD, MVT::i1, Promote);
130
131   // We don't accept any truncstore of integer registers.
132   setTruncStoreAction(MVT::i64, MVT::i32, Expand);
133   if (!Disable16Bit)
134     setTruncStoreAction(MVT::i64, MVT::i16, Expand);
135   setTruncStoreAction(MVT::i64, MVT::i8 , Expand);
136   if (!Disable16Bit)
137     setTruncStoreAction(MVT::i32, MVT::i16, Expand);
138   setTruncStoreAction(MVT::i32, MVT::i8 , Expand);
139   setTruncStoreAction(MVT::i16, MVT::i8,  Expand);
140
141   // SETOEQ and SETUNE require checking two conditions.
142   setCondCodeAction(ISD::SETOEQ, MVT::f32, Expand);
143   setCondCodeAction(ISD::SETOEQ, MVT::f64, Expand);
144   setCondCodeAction(ISD::SETOEQ, MVT::f80, Expand);
145   setCondCodeAction(ISD::SETUNE, MVT::f32, Expand);
146   setCondCodeAction(ISD::SETUNE, MVT::f64, Expand);
147   setCondCodeAction(ISD::SETUNE, MVT::f80, Expand);
148
149   // Promote all UINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have this
150   // operation.
151   setOperationAction(ISD::UINT_TO_FP       , MVT::i1   , Promote);
152   setOperationAction(ISD::UINT_TO_FP       , MVT::i8   , Promote);
153   setOperationAction(ISD::UINT_TO_FP       , MVT::i16  , Promote);
154
155   if (Subtarget->is64Bit()) {
156     setOperationAction(ISD::UINT_TO_FP     , MVT::i32  , Promote);
157     setOperationAction(ISD::UINT_TO_FP     , MVT::i64  , Expand);
158   } else if (!UseSoftFloat) {
159     if (X86ScalarSSEf64) {
160       // We have an impenetrably clever algorithm for ui64->double only.
161       setOperationAction(ISD::UINT_TO_FP   , MVT::i64  , Custom);
162     }
163     // We have an algorithm for SSE2, and we turn this into a 64-bit
164     // FILD for other targets.
165     setOperationAction(ISD::UINT_TO_FP   , MVT::i32  , Custom);
166   }
167
168   // Promote i1/i8 SINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have
169   // this operation.
170   setOperationAction(ISD::SINT_TO_FP       , MVT::i1   , Promote);
171   setOperationAction(ISD::SINT_TO_FP       , MVT::i8   , Promote);
172
173   if (!UseSoftFloat) {
174     // SSE has no i16 to fp conversion, only i32
175     if (X86ScalarSSEf32) {
176       setOperationAction(ISD::SINT_TO_FP     , MVT::i16  , Promote);
177       // f32 and f64 cases are Legal, f80 case is not
178       setOperationAction(ISD::SINT_TO_FP     , MVT::i32  , Custom);
179     } else {
180       setOperationAction(ISD::SINT_TO_FP     , MVT::i16  , Custom);
181       setOperationAction(ISD::SINT_TO_FP     , MVT::i32  , Custom);
182     }
183   } else {
184     setOperationAction(ISD::SINT_TO_FP     , MVT::i16  , Promote);
185     setOperationAction(ISD::SINT_TO_FP     , MVT::i32  , Promote);
186   }
187
188   // In 32-bit mode these are custom lowered.  In 64-bit mode F32 and F64
189   // are Legal, f80 is custom lowered.
190   setOperationAction(ISD::FP_TO_SINT     , MVT::i64  , Custom);
191   setOperationAction(ISD::SINT_TO_FP     , MVT::i64  , Custom);
192
193   // Promote i1/i8 FP_TO_SINT to larger FP_TO_SINTS's, as X86 doesn't have
194   // this operation.
195   setOperationAction(ISD::FP_TO_SINT       , MVT::i1   , Promote);
196   setOperationAction(ISD::FP_TO_SINT       , MVT::i8   , Promote);
197
198   if (X86ScalarSSEf32) {
199     setOperationAction(ISD::FP_TO_SINT     , MVT::i16  , Promote);
200     // f32 and f64 cases are Legal, f80 case is not
201     setOperationAction(ISD::FP_TO_SINT     , MVT::i32  , Custom);
202   } else {
203     setOperationAction(ISD::FP_TO_SINT     , MVT::i16  , Custom);
204     setOperationAction(ISD::FP_TO_SINT     , MVT::i32  , Custom);
205   }
206
207   // Handle FP_TO_UINT by promoting the destination to a larger signed
208   // conversion.
209   setOperationAction(ISD::FP_TO_UINT       , MVT::i1   , Promote);
210   setOperationAction(ISD::FP_TO_UINT       , MVT::i8   , Promote);
211   setOperationAction(ISD::FP_TO_UINT       , MVT::i16  , Promote);
212
213   if (Subtarget->is64Bit()) {
214     setOperationAction(ISD::FP_TO_UINT     , MVT::i64  , Expand);
215     setOperationAction(ISD::FP_TO_UINT     , MVT::i32  , Promote);
216   } else if (!UseSoftFloat) {
217     if (X86ScalarSSEf32 && !Subtarget->hasSSE3())
218       // Expand FP_TO_UINT into a select.
219       // FIXME: We would like to use a Custom expander here eventually to do
220       // the optimal thing for SSE vs. the default expansion in the legalizer.
221       setOperationAction(ISD::FP_TO_UINT   , MVT::i32  , Expand);
222     else
223       // With SSE3 we can use fisttpll to convert to a signed i64; without
224       // SSE, we're stuck with a fistpll.
225       setOperationAction(ISD::FP_TO_UINT   , MVT::i32  , Custom);
226   }
227
228   // TODO: when we have SSE, these could be more efficient, by using movd/movq.
229   if (!X86ScalarSSEf64) {
230     setOperationAction(ISD::BIT_CONVERT      , MVT::f32  , Expand);
231     setOperationAction(ISD::BIT_CONVERT      , MVT::i32  , Expand);
232   }
233
234   // Scalar integer divide and remainder are lowered to use operations that
235   // produce two results, to match the available instructions. This exposes
236   // the two-result form to trivial CSE, which is able to combine x/y and x%y
237   // into a single instruction.
238   //
239   // Scalar integer multiply-high is also lowered to use two-result
240   // operations, to match the available instructions. However, plain multiply
241   // (low) operations are left as Legal, as there are single-result
242   // instructions for this in x86. Using the two-result multiply instructions
243   // when both high and low results are needed must be arranged by dagcombine.
244   setOperationAction(ISD::MULHS           , MVT::i8    , Expand);
245   setOperationAction(ISD::MULHU           , MVT::i8    , Expand);
246   setOperationAction(ISD::SDIV            , MVT::i8    , Expand);
247   setOperationAction(ISD::UDIV            , MVT::i8    , Expand);
248   setOperationAction(ISD::SREM            , MVT::i8    , Expand);
249   setOperationAction(ISD::UREM            , MVT::i8    , Expand);
250   setOperationAction(ISD::MULHS           , MVT::i16   , Expand);
251   setOperationAction(ISD::MULHU           , MVT::i16   , Expand);
252   setOperationAction(ISD::SDIV            , MVT::i16   , Expand);
253   setOperationAction(ISD::UDIV            , MVT::i16   , Expand);
254   setOperationAction(ISD::SREM            , MVT::i16   , Expand);
255   setOperationAction(ISD::UREM            , MVT::i16   , Expand);
256   setOperationAction(ISD::MULHS           , MVT::i32   , Expand);
257   setOperationAction(ISD::MULHU           , MVT::i32   , Expand);
258   setOperationAction(ISD::SDIV            , MVT::i32   , Expand);
259   setOperationAction(ISD::UDIV            , MVT::i32   , Expand);
260   setOperationAction(ISD::SREM            , MVT::i32   , Expand);
261   setOperationAction(ISD::UREM            , MVT::i32   , Expand);
262   setOperationAction(ISD::MULHS           , MVT::i64   , Expand);
263   setOperationAction(ISD::MULHU           , MVT::i64   , Expand);
264   setOperationAction(ISD::SDIV            , MVT::i64   , Expand);
265   setOperationAction(ISD::UDIV            , MVT::i64   , Expand);
266   setOperationAction(ISD::SREM            , MVT::i64   , Expand);
267   setOperationAction(ISD::UREM            , MVT::i64   , Expand);
268
269   setOperationAction(ISD::BR_JT            , MVT::Other, Expand);
270   setOperationAction(ISD::BRCOND           , MVT::Other, Custom);
271   setOperationAction(ISD::BR_CC            , MVT::Other, Expand);
272   setOperationAction(ISD::SELECT_CC        , MVT::Other, Expand);
273   if (Subtarget->is64Bit())
274     setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i32, Legal);
275   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16  , Legal);
276   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8   , Legal);
277   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1   , Expand);
278   setOperationAction(ISD::FP_ROUND_INREG   , MVT::f32  , Expand);
279   setOperationAction(ISD::FREM             , MVT::f32  , Expand);
280   setOperationAction(ISD::FREM             , MVT::f64  , Expand);
281   setOperationAction(ISD::FREM             , MVT::f80  , Expand);
282   setOperationAction(ISD::FLT_ROUNDS_      , MVT::i32  , Custom);
283
284   setOperationAction(ISD::CTPOP            , MVT::i8   , Expand);
285   setOperationAction(ISD::CTTZ             , MVT::i8   , Custom);
286   setOperationAction(ISD::CTLZ             , MVT::i8   , Custom);
287   setOperationAction(ISD::CTPOP            , MVT::i16  , Expand);
288   if (Disable16Bit) {
289     setOperationAction(ISD::CTTZ           , MVT::i16  , Expand);
290     setOperationAction(ISD::CTLZ           , MVT::i16  , Expand);
291   } else {
292     setOperationAction(ISD::CTTZ           , MVT::i16  , Custom);
293     setOperationAction(ISD::CTLZ           , MVT::i16  , Custom);
294   }
295   setOperationAction(ISD::CTPOP            , MVT::i32  , Expand);
296   setOperationAction(ISD::CTTZ             , MVT::i32  , Custom);
297   setOperationAction(ISD::CTLZ             , MVT::i32  , Custom);
298   if (Subtarget->is64Bit()) {
299     setOperationAction(ISD::CTPOP          , MVT::i64  , Expand);
300     setOperationAction(ISD::CTTZ           , MVT::i64  , Custom);
301     setOperationAction(ISD::CTLZ           , MVT::i64  , Custom);
302   }
303
304   setOperationAction(ISD::READCYCLECOUNTER , MVT::i64  , Custom);
305   setOperationAction(ISD::BSWAP            , MVT::i16  , Expand);
306
307   // These should be promoted to a larger select which is supported.
308   setOperationAction(ISD::SELECT          , MVT::i1   , Promote);
309   // X86 wants to expand cmov itself.
310   setOperationAction(ISD::SELECT          , MVT::i8   , Custom);
311   if (Disable16Bit)
312     setOperationAction(ISD::SELECT        , MVT::i16  , Expand);
313   else
314     setOperationAction(ISD::SELECT        , MVT::i16  , Custom);
315   setOperationAction(ISD::SELECT          , MVT::i32  , Custom);
316   setOperationAction(ISD::SELECT          , MVT::f32  , Custom);
317   setOperationAction(ISD::SELECT          , MVT::f64  , Custom);
318   setOperationAction(ISD::SELECT          , MVT::f80  , Custom);
319   setOperationAction(ISD::SETCC           , MVT::i8   , Custom);
320   if (Disable16Bit)
321     setOperationAction(ISD::SETCC         , MVT::i16  , Expand);
322   else
323     setOperationAction(ISD::SETCC         , MVT::i16  , Custom);
324   setOperationAction(ISD::SETCC           , MVT::i32  , Custom);
325   setOperationAction(ISD::SETCC           , MVT::f32  , Custom);
326   setOperationAction(ISD::SETCC           , MVT::f64  , Custom);
327   setOperationAction(ISD::SETCC           , MVT::f80  , Custom);
328   if (Subtarget->is64Bit()) {
329     setOperationAction(ISD::SELECT        , MVT::i64  , Custom);
330     setOperationAction(ISD::SETCC         , MVT::i64  , Custom);
331   }
332   setOperationAction(ISD::EH_RETURN       , MVT::Other, Custom);
333
334   // Darwin ABI issue.
335   setOperationAction(ISD::ConstantPool    , MVT::i32  , Custom);
336   setOperationAction(ISD::JumpTable       , MVT::i32  , Custom);
337   setOperationAction(ISD::GlobalAddress   , MVT::i32  , Custom);
338   setOperationAction(ISD::GlobalTLSAddress, MVT::i32  , Custom);
339   if (Subtarget->is64Bit())
340     setOperationAction(ISD::GlobalTLSAddress, MVT::i64, Custom);
341   setOperationAction(ISD::ExternalSymbol  , MVT::i32  , Custom);
342   setOperationAction(ISD::BlockAddress    , MVT::i32  , Custom);
343   if (Subtarget->is64Bit()) {
344     setOperationAction(ISD::ConstantPool  , MVT::i64  , Custom);
345     setOperationAction(ISD::JumpTable     , MVT::i64  , Custom);
346     setOperationAction(ISD::GlobalAddress , MVT::i64  , Custom);
347     setOperationAction(ISD::ExternalSymbol, MVT::i64  , Custom);
348     setOperationAction(ISD::BlockAddress  , MVT::i64  , Custom);
349   }
350   // 64-bit addm sub, shl, sra, srl (iff 32-bit x86)
351   setOperationAction(ISD::SHL_PARTS       , MVT::i32  , Custom);
352   setOperationAction(ISD::SRA_PARTS       , MVT::i32  , Custom);
353   setOperationAction(ISD::SRL_PARTS       , MVT::i32  , Custom);
354   if (Subtarget->is64Bit()) {
355     setOperationAction(ISD::SHL_PARTS     , MVT::i64  , Custom);
356     setOperationAction(ISD::SRA_PARTS     , MVT::i64  , Custom);
357     setOperationAction(ISD::SRL_PARTS     , MVT::i64  , Custom);
358   }
359
360   if (Subtarget->hasSSE1())
361     setOperationAction(ISD::PREFETCH      , MVT::Other, Legal);
362
363   if (!Subtarget->hasSSE2())
364     setOperationAction(ISD::MEMBARRIER    , MVT::Other, Expand);
365
366   // Expand certain atomics
367   setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i8, Custom);
368   setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i16, Custom);
369   setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i32, Custom);
370   setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i64, Custom);
371
372   setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i8, Custom);
373   setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i16, Custom);
374   setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i32, Custom);
375   setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i64, Custom);
376
377   if (!Subtarget->is64Bit()) {
378     setOperationAction(ISD::ATOMIC_LOAD_ADD, MVT::i64, Custom);
379     setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i64, Custom);
380     setOperationAction(ISD::ATOMIC_LOAD_AND, MVT::i64, Custom);
381     setOperationAction(ISD::ATOMIC_LOAD_OR, MVT::i64, Custom);
382     setOperationAction(ISD::ATOMIC_LOAD_XOR, MVT::i64, Custom);
383     setOperationAction(ISD::ATOMIC_LOAD_NAND, MVT::i64, Custom);
384     setOperationAction(ISD::ATOMIC_SWAP, MVT::i64, Custom);
385   }
386
387   // FIXME - use subtarget debug flags
388   if (!Subtarget->isTargetDarwin() &&
389       !Subtarget->isTargetELF() &&
390       !Subtarget->isTargetCygMing()) {
391     setOperationAction(ISD::EH_LABEL, MVT::Other, Expand);
392   }
393
394   setOperationAction(ISD::EXCEPTIONADDR, MVT::i64, Expand);
395   setOperationAction(ISD::EHSELECTION,   MVT::i64, Expand);
396   setOperationAction(ISD::EXCEPTIONADDR, MVT::i32, Expand);
397   setOperationAction(ISD::EHSELECTION,   MVT::i32, Expand);
398   if (Subtarget->is64Bit()) {
399     setExceptionPointerRegister(X86::RAX);
400     setExceptionSelectorRegister(X86::RDX);
401   } else {
402     setExceptionPointerRegister(X86::EAX);
403     setExceptionSelectorRegister(X86::EDX);
404   }
405   setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i32, Custom);
406   setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i64, Custom);
407
408   setOperationAction(ISD::TRAMPOLINE, MVT::Other, Custom);
409
410   setOperationAction(ISD::TRAP, MVT::Other, Legal);
411
412   // VASTART needs to be custom lowered to use the VarArgsFrameIndex
413   setOperationAction(ISD::VASTART           , MVT::Other, Custom);
414   setOperationAction(ISD::VAEND             , MVT::Other, Expand);
415   if (Subtarget->is64Bit()) {
416     setOperationAction(ISD::VAARG           , MVT::Other, Custom);
417     setOperationAction(ISD::VACOPY          , MVT::Other, Custom);
418   } else {
419     setOperationAction(ISD::VAARG           , MVT::Other, Expand);
420     setOperationAction(ISD::VACOPY          , MVT::Other, Expand);
421   }
422
423   setOperationAction(ISD::STACKSAVE,          MVT::Other, Expand);
424   setOperationAction(ISD::STACKRESTORE,       MVT::Other, Expand);
425   if (Subtarget->is64Bit())
426     setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i64, Expand);
427   if (Subtarget->isTargetCygMing())
428     setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Custom);
429   else
430     setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Expand);
431
432   if (!UseSoftFloat && X86ScalarSSEf64) {
433     // f32 and f64 use SSE.
434     // Set up the FP register classes.
435     addRegisterClass(MVT::f32, X86::FR32RegisterClass);
436     addRegisterClass(MVT::f64, X86::FR64RegisterClass);
437
438     // Use ANDPD to simulate FABS.
439     setOperationAction(ISD::FABS , MVT::f64, Custom);
440     setOperationAction(ISD::FABS , MVT::f32, Custom);
441
442     // Use XORP to simulate FNEG.
443     setOperationAction(ISD::FNEG , MVT::f64, Custom);
444     setOperationAction(ISD::FNEG , MVT::f32, Custom);
445
446     // Use ANDPD and ORPD to simulate FCOPYSIGN.
447     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
448     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
449
450     // We don't support sin/cos/fmod
451     setOperationAction(ISD::FSIN , MVT::f64, Expand);
452     setOperationAction(ISD::FCOS , MVT::f64, Expand);
453     setOperationAction(ISD::FSIN , MVT::f32, Expand);
454     setOperationAction(ISD::FCOS , MVT::f32, Expand);
455
456     // Expand FP immediates into loads from the stack, except for the special
457     // cases we handle.
458     addLegalFPImmediate(APFloat(+0.0)); // xorpd
459     addLegalFPImmediate(APFloat(+0.0f)); // xorps
460   } else if (!UseSoftFloat && X86ScalarSSEf32) {
461     // Use SSE for f32, x87 for f64.
462     // Set up the FP register classes.
463     addRegisterClass(MVT::f32, X86::FR32RegisterClass);
464     addRegisterClass(MVT::f64, X86::RFP64RegisterClass);
465
466     // Use ANDPS to simulate FABS.
467     setOperationAction(ISD::FABS , MVT::f32, Custom);
468
469     // Use XORP to simulate FNEG.
470     setOperationAction(ISD::FNEG , MVT::f32, Custom);
471
472     setOperationAction(ISD::UNDEF,     MVT::f64, Expand);
473
474     // Use ANDPS and ORPS to simulate FCOPYSIGN.
475     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
476     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
477
478     // We don't support sin/cos/fmod
479     setOperationAction(ISD::FSIN , MVT::f32, Expand);
480     setOperationAction(ISD::FCOS , MVT::f32, Expand);
481
482     // Special cases we handle for FP constants.
483     addLegalFPImmediate(APFloat(+0.0f)); // xorps
484     addLegalFPImmediate(APFloat(+0.0)); // FLD0
485     addLegalFPImmediate(APFloat(+1.0)); // FLD1
486     addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
487     addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
488
489     if (!UnsafeFPMath) {
490       setOperationAction(ISD::FSIN           , MVT::f64  , Expand);
491       setOperationAction(ISD::FCOS           , MVT::f64  , Expand);
492     }
493   } else if (!UseSoftFloat) {
494     // f32 and f64 in x87.
495     // Set up the FP register classes.
496     addRegisterClass(MVT::f64, X86::RFP64RegisterClass);
497     addRegisterClass(MVT::f32, X86::RFP32RegisterClass);
498
499     setOperationAction(ISD::UNDEF,     MVT::f64, Expand);
500     setOperationAction(ISD::UNDEF,     MVT::f32, Expand);
501     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
502     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand);
503
504     if (!UnsafeFPMath) {
505       setOperationAction(ISD::FSIN           , MVT::f64  , Expand);
506       setOperationAction(ISD::FCOS           , MVT::f64  , Expand);
507     }
508     addLegalFPImmediate(APFloat(+0.0)); // FLD0
509     addLegalFPImmediate(APFloat(+1.0)); // FLD1
510     addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
511     addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
512     addLegalFPImmediate(APFloat(+0.0f)); // FLD0
513     addLegalFPImmediate(APFloat(+1.0f)); // FLD1
514     addLegalFPImmediate(APFloat(-0.0f)); // FLD0/FCHS
515     addLegalFPImmediate(APFloat(-1.0f)); // FLD1/FCHS
516   }
517
518   // Long double always uses X87.
519   if (!UseSoftFloat) {
520     addRegisterClass(MVT::f80, X86::RFP80RegisterClass);
521     setOperationAction(ISD::UNDEF,     MVT::f80, Expand);
522     setOperationAction(ISD::FCOPYSIGN, MVT::f80, Expand);
523     {
524       bool ignored;
525       APFloat TmpFlt(+0.0);
526       TmpFlt.convert(APFloat::x87DoubleExtended, APFloat::rmNearestTiesToEven,
527                      &ignored);
528       addLegalFPImmediate(TmpFlt);  // FLD0
529       TmpFlt.changeSign();
530       addLegalFPImmediate(TmpFlt);  // FLD0/FCHS
531       APFloat TmpFlt2(+1.0);
532       TmpFlt2.convert(APFloat::x87DoubleExtended, APFloat::rmNearestTiesToEven,
533                       &ignored);
534       addLegalFPImmediate(TmpFlt2);  // FLD1
535       TmpFlt2.changeSign();
536       addLegalFPImmediate(TmpFlt2);  // FLD1/FCHS
537     }
538
539     if (!UnsafeFPMath) {
540       setOperationAction(ISD::FSIN           , MVT::f80  , Expand);
541       setOperationAction(ISD::FCOS           , MVT::f80  , Expand);
542     }
543   }
544
545   // Always use a library call for pow.
546   setOperationAction(ISD::FPOW             , MVT::f32  , Expand);
547   setOperationAction(ISD::FPOW             , MVT::f64  , Expand);
548   setOperationAction(ISD::FPOW             , MVT::f80  , Expand);
549
550   setOperationAction(ISD::FLOG, MVT::f80, Expand);
551   setOperationAction(ISD::FLOG2, MVT::f80, Expand);
552   setOperationAction(ISD::FLOG10, MVT::f80, Expand);
553   setOperationAction(ISD::FEXP, MVT::f80, Expand);
554   setOperationAction(ISD::FEXP2, MVT::f80, Expand);
555
556   // First set operation action for all vector types to either promote
557   // (for widening) or expand (for scalarization). Then we will selectively
558   // turn on ones that can be effectively codegen'd.
559   for (unsigned VT = (unsigned)MVT::FIRST_VECTOR_VALUETYPE;
560        VT <= (unsigned)MVT::LAST_VECTOR_VALUETYPE; ++VT) {
561     setOperationAction(ISD::ADD , (MVT::SimpleValueType)VT, Expand);
562     setOperationAction(ISD::SUB , (MVT::SimpleValueType)VT, Expand);
563     setOperationAction(ISD::FADD, (MVT::SimpleValueType)VT, Expand);
564     setOperationAction(ISD::FNEG, (MVT::SimpleValueType)VT, Expand);
565     setOperationAction(ISD::FSUB, (MVT::SimpleValueType)VT, Expand);
566     setOperationAction(ISD::MUL , (MVT::SimpleValueType)VT, Expand);
567     setOperationAction(ISD::FMUL, (MVT::SimpleValueType)VT, Expand);
568     setOperationAction(ISD::SDIV, (MVT::SimpleValueType)VT, Expand);
569     setOperationAction(ISD::UDIV, (MVT::SimpleValueType)VT, Expand);
570     setOperationAction(ISD::FDIV, (MVT::SimpleValueType)VT, Expand);
571     setOperationAction(ISD::SREM, (MVT::SimpleValueType)VT, Expand);
572     setOperationAction(ISD::UREM, (MVT::SimpleValueType)VT, Expand);
573     setOperationAction(ISD::LOAD, (MVT::SimpleValueType)VT, Expand);
574     setOperationAction(ISD::VECTOR_SHUFFLE, (MVT::SimpleValueType)VT, Expand);
575     setOperationAction(ISD::EXTRACT_VECTOR_ELT,(MVT::SimpleValueType)VT,Expand);
576     setOperationAction(ISD::EXTRACT_SUBVECTOR,(MVT::SimpleValueType)VT,Expand);
577     setOperationAction(ISD::INSERT_VECTOR_ELT,(MVT::SimpleValueType)VT, Expand);
578     setOperationAction(ISD::FABS, (MVT::SimpleValueType)VT, Expand);
579     setOperationAction(ISD::FSIN, (MVT::SimpleValueType)VT, Expand);
580     setOperationAction(ISD::FCOS, (MVT::SimpleValueType)VT, Expand);
581     setOperationAction(ISD::FREM, (MVT::SimpleValueType)VT, Expand);
582     setOperationAction(ISD::FPOWI, (MVT::SimpleValueType)VT, Expand);
583     setOperationAction(ISD::FSQRT, (MVT::SimpleValueType)VT, Expand);
584     setOperationAction(ISD::FCOPYSIGN, (MVT::SimpleValueType)VT, Expand);
585     setOperationAction(ISD::SMUL_LOHI, (MVT::SimpleValueType)VT, Expand);
586     setOperationAction(ISD::UMUL_LOHI, (MVT::SimpleValueType)VT, Expand);
587     setOperationAction(ISD::SDIVREM, (MVT::SimpleValueType)VT, Expand);
588     setOperationAction(ISD::UDIVREM, (MVT::SimpleValueType)VT, Expand);
589     setOperationAction(ISD::FPOW, (MVT::SimpleValueType)VT, Expand);
590     setOperationAction(ISD::CTPOP, (MVT::SimpleValueType)VT, Expand);
591     setOperationAction(ISD::CTTZ, (MVT::SimpleValueType)VT, Expand);
592     setOperationAction(ISD::CTLZ, (MVT::SimpleValueType)VT, Expand);
593     setOperationAction(ISD::SHL, (MVT::SimpleValueType)VT, Expand);
594     setOperationAction(ISD::SRA, (MVT::SimpleValueType)VT, Expand);
595     setOperationAction(ISD::SRL, (MVT::SimpleValueType)VT, Expand);
596     setOperationAction(ISD::ROTL, (MVT::SimpleValueType)VT, Expand);
597     setOperationAction(ISD::ROTR, (MVT::SimpleValueType)VT, Expand);
598     setOperationAction(ISD::BSWAP, (MVT::SimpleValueType)VT, Expand);
599     setOperationAction(ISD::VSETCC, (MVT::SimpleValueType)VT, Expand);
600     setOperationAction(ISD::FLOG, (MVT::SimpleValueType)VT, Expand);
601     setOperationAction(ISD::FLOG2, (MVT::SimpleValueType)VT, Expand);
602     setOperationAction(ISD::FLOG10, (MVT::SimpleValueType)VT, Expand);
603     setOperationAction(ISD::FEXP, (MVT::SimpleValueType)VT, Expand);
604     setOperationAction(ISD::FEXP2, (MVT::SimpleValueType)VT, Expand);
605     setOperationAction(ISD::FP_TO_UINT, (MVT::SimpleValueType)VT, Expand);
606     setOperationAction(ISD::FP_TO_SINT, (MVT::SimpleValueType)VT, Expand);
607     setOperationAction(ISD::UINT_TO_FP, (MVT::SimpleValueType)VT, Expand);
608     setOperationAction(ISD::SINT_TO_FP, (MVT::SimpleValueType)VT, Expand);
609     setOperationAction(ISD::SIGN_EXTEND_INREG, (MVT::SimpleValueType)VT,Expand);
610     setOperationAction(ISD::TRUNCATE,  (MVT::SimpleValueType)VT, Expand);
611     setOperationAction(ISD::SIGN_EXTEND,  (MVT::SimpleValueType)VT, Expand);
612     setOperationAction(ISD::ZERO_EXTEND,  (MVT::SimpleValueType)VT, Expand);
613     setOperationAction(ISD::ANY_EXTEND,  (MVT::SimpleValueType)VT, Expand);
614     for (unsigned InnerVT = (unsigned)MVT::FIRST_VECTOR_VALUETYPE;
615          InnerVT <= (unsigned)MVT::LAST_VECTOR_VALUETYPE; ++InnerVT)
616       setTruncStoreAction((MVT::SimpleValueType)VT,
617                           (MVT::SimpleValueType)InnerVT, Expand);
618     setLoadExtAction(ISD::SEXTLOAD, (MVT::SimpleValueType)VT, Expand);
619     setLoadExtAction(ISD::ZEXTLOAD, (MVT::SimpleValueType)VT, Expand);
620     setLoadExtAction(ISD::EXTLOAD, (MVT::SimpleValueType)VT, Expand);
621   }
622
623   // FIXME: In order to prevent SSE instructions being expanded to MMX ones
624   // with -msoft-float, disable use of MMX as well.
625   if (!UseSoftFloat && !DisableMMX && Subtarget->hasMMX()) {
626     addRegisterClass(MVT::v8i8,  X86::VR64RegisterClass);
627     addRegisterClass(MVT::v4i16, X86::VR64RegisterClass);
628     addRegisterClass(MVT::v2i32, X86::VR64RegisterClass);
629     addRegisterClass(MVT::v2f32, X86::VR64RegisterClass);
630     addRegisterClass(MVT::v1i64, X86::VR64RegisterClass);
631
632     setOperationAction(ISD::ADD,                MVT::v8i8,  Legal);
633     setOperationAction(ISD::ADD,                MVT::v4i16, Legal);
634     setOperationAction(ISD::ADD,                MVT::v2i32, Legal);
635     setOperationAction(ISD::ADD,                MVT::v1i64, Legal);
636
637     setOperationAction(ISD::SUB,                MVT::v8i8,  Legal);
638     setOperationAction(ISD::SUB,                MVT::v4i16, Legal);
639     setOperationAction(ISD::SUB,                MVT::v2i32, Legal);
640     setOperationAction(ISD::SUB,                MVT::v1i64, Legal);
641
642     setOperationAction(ISD::MULHS,              MVT::v4i16, Legal);
643     setOperationAction(ISD::MUL,                MVT::v4i16, Legal);
644
645     setOperationAction(ISD::AND,                MVT::v8i8,  Promote);
646     AddPromotedToType (ISD::AND,                MVT::v8i8,  MVT::v1i64);
647     setOperationAction(ISD::AND,                MVT::v4i16, Promote);
648     AddPromotedToType (ISD::AND,                MVT::v4i16, MVT::v1i64);
649     setOperationAction(ISD::AND,                MVT::v2i32, Promote);
650     AddPromotedToType (ISD::AND,                MVT::v2i32, MVT::v1i64);
651     setOperationAction(ISD::AND,                MVT::v1i64, Legal);
652
653     setOperationAction(ISD::OR,                 MVT::v8i8,  Promote);
654     AddPromotedToType (ISD::OR,                 MVT::v8i8,  MVT::v1i64);
655     setOperationAction(ISD::OR,                 MVT::v4i16, Promote);
656     AddPromotedToType (ISD::OR,                 MVT::v4i16, MVT::v1i64);
657     setOperationAction(ISD::OR,                 MVT::v2i32, Promote);
658     AddPromotedToType (ISD::OR,                 MVT::v2i32, MVT::v1i64);
659     setOperationAction(ISD::OR,                 MVT::v1i64, Legal);
660
661     setOperationAction(ISD::XOR,                MVT::v8i8,  Promote);
662     AddPromotedToType (ISD::XOR,                MVT::v8i8,  MVT::v1i64);
663     setOperationAction(ISD::XOR,                MVT::v4i16, Promote);
664     AddPromotedToType (ISD::XOR,                MVT::v4i16, MVT::v1i64);
665     setOperationAction(ISD::XOR,                MVT::v2i32, Promote);
666     AddPromotedToType (ISD::XOR,                MVT::v2i32, MVT::v1i64);
667     setOperationAction(ISD::XOR,                MVT::v1i64, Legal);
668
669     setOperationAction(ISD::LOAD,               MVT::v8i8,  Promote);
670     AddPromotedToType (ISD::LOAD,               MVT::v8i8,  MVT::v1i64);
671     setOperationAction(ISD::LOAD,               MVT::v4i16, Promote);
672     AddPromotedToType (ISD::LOAD,               MVT::v4i16, MVT::v1i64);
673     setOperationAction(ISD::LOAD,               MVT::v2i32, Promote);
674     AddPromotedToType (ISD::LOAD,               MVT::v2i32, MVT::v1i64);
675     setOperationAction(ISD::LOAD,               MVT::v2f32, Promote);
676     AddPromotedToType (ISD::LOAD,               MVT::v2f32, MVT::v1i64);
677     setOperationAction(ISD::LOAD,               MVT::v1i64, Legal);
678
679     setOperationAction(ISD::BUILD_VECTOR,       MVT::v8i8,  Custom);
680     setOperationAction(ISD::BUILD_VECTOR,       MVT::v4i16, Custom);
681     setOperationAction(ISD::BUILD_VECTOR,       MVT::v2i32, Custom);
682     setOperationAction(ISD::BUILD_VECTOR,       MVT::v2f32, Custom);
683     setOperationAction(ISD::BUILD_VECTOR,       MVT::v1i64, Custom);
684
685     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v8i8,  Custom);
686     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v4i16, Custom);
687     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v2i32, Custom);
688     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v1i64, Custom);
689
690     setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v2f32, Custom);
691     setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v8i8,  Custom);
692     setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v4i16, Custom);
693     setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v1i64, Custom);
694
695     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4i16, Custom);
696
697     setOperationAction(ISD::SELECT,             MVT::v8i8, Promote);
698     setOperationAction(ISD::SELECT,             MVT::v4i16, Promote);
699     setOperationAction(ISD::SELECT,             MVT::v2i32, Promote);
700     setOperationAction(ISD::SELECT,             MVT::v1i64, Custom);
701     setOperationAction(ISD::VSETCC,             MVT::v8i8, Custom);
702     setOperationAction(ISD::VSETCC,             MVT::v4i16, Custom);
703     setOperationAction(ISD::VSETCC,             MVT::v2i32, Custom);
704   }
705
706   if (!UseSoftFloat && Subtarget->hasSSE1()) {
707     addRegisterClass(MVT::v4f32, X86::VR128RegisterClass);
708
709     setOperationAction(ISD::FADD,               MVT::v4f32, Legal);
710     setOperationAction(ISD::FSUB,               MVT::v4f32, Legal);
711     setOperationAction(ISD::FMUL,               MVT::v4f32, Legal);
712     setOperationAction(ISD::FDIV,               MVT::v4f32, Legal);
713     setOperationAction(ISD::FSQRT,              MVT::v4f32, Legal);
714     setOperationAction(ISD::FNEG,               MVT::v4f32, Custom);
715     setOperationAction(ISD::LOAD,               MVT::v4f32, Legal);
716     setOperationAction(ISD::BUILD_VECTOR,       MVT::v4f32, Custom);
717     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v4f32, Custom);
718     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
719     setOperationAction(ISD::SELECT,             MVT::v4f32, Custom);
720     setOperationAction(ISD::VSETCC,             MVT::v4f32, Custom);
721   }
722
723   if (!UseSoftFloat && Subtarget->hasSSE2()) {
724     addRegisterClass(MVT::v2f64, X86::VR128RegisterClass);
725
726     // FIXME: Unfortunately -soft-float and -no-implicit-float means XMM
727     // registers cannot be used even for integer operations.
728     addRegisterClass(MVT::v16i8, X86::VR128RegisterClass);
729     addRegisterClass(MVT::v8i16, X86::VR128RegisterClass);
730     addRegisterClass(MVT::v4i32, X86::VR128RegisterClass);
731     addRegisterClass(MVT::v2i64, X86::VR128RegisterClass);
732
733     setOperationAction(ISD::ADD,                MVT::v16i8, Legal);
734     setOperationAction(ISD::ADD,                MVT::v8i16, Legal);
735     setOperationAction(ISD::ADD,                MVT::v4i32, Legal);
736     setOperationAction(ISD::ADD,                MVT::v2i64, Legal);
737     setOperationAction(ISD::MUL,                MVT::v2i64, Custom);
738     setOperationAction(ISD::SUB,                MVT::v16i8, Legal);
739     setOperationAction(ISD::SUB,                MVT::v8i16, Legal);
740     setOperationAction(ISD::SUB,                MVT::v4i32, Legal);
741     setOperationAction(ISD::SUB,                MVT::v2i64, Legal);
742     setOperationAction(ISD::MUL,                MVT::v8i16, Legal);
743     setOperationAction(ISD::FADD,               MVT::v2f64, Legal);
744     setOperationAction(ISD::FSUB,               MVT::v2f64, Legal);
745     setOperationAction(ISD::FMUL,               MVT::v2f64, Legal);
746     setOperationAction(ISD::FDIV,               MVT::v2f64, Legal);
747     setOperationAction(ISD::FSQRT,              MVT::v2f64, Legal);
748     setOperationAction(ISD::FNEG,               MVT::v2f64, Custom);
749
750     setOperationAction(ISD::VSETCC,             MVT::v2f64, Custom);
751     setOperationAction(ISD::VSETCC,             MVT::v16i8, Custom);
752     setOperationAction(ISD::VSETCC,             MVT::v8i16, Custom);
753     setOperationAction(ISD::VSETCC,             MVT::v4i32, Custom);
754
755     setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v16i8, Custom);
756     setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v8i16, Custom);
757     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v8i16, Custom);
758     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4i32, Custom);
759     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4f32, Custom);
760
761     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v2f64, Custom);
762     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v2i64, Custom);
763     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v16i8, Custom);
764     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v8i16, Custom);
765     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v4i32, Custom);
766
767     // Custom lower build_vector, vector_shuffle, and extract_vector_elt.
768     for (unsigned i = (unsigned)MVT::v16i8; i != (unsigned)MVT::v2i64; ++i) {
769       EVT VT = (MVT::SimpleValueType)i;
770       // Do not attempt to custom lower non-power-of-2 vectors
771       if (!isPowerOf2_32(VT.getVectorNumElements()))
772         continue;
773       // Do not attempt to custom lower non-128-bit vectors
774       if (!VT.is128BitVector())
775         continue;
776       setOperationAction(ISD::BUILD_VECTOR,
777                          VT.getSimpleVT().SimpleTy, Custom);
778       setOperationAction(ISD::VECTOR_SHUFFLE,
779                          VT.getSimpleVT().SimpleTy, Custom);
780       setOperationAction(ISD::EXTRACT_VECTOR_ELT,
781                          VT.getSimpleVT().SimpleTy, Custom);
782     }
783
784     setOperationAction(ISD::BUILD_VECTOR,       MVT::v2f64, Custom);
785     setOperationAction(ISD::BUILD_VECTOR,       MVT::v2i64, Custom);
786     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v2f64, Custom);
787     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v2i64, Custom);
788     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2f64, Custom);
789     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Custom);
790
791     if (Subtarget->is64Bit()) {
792       setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2i64, Custom);
793       setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
794     }
795
796     // Promote v16i8, v8i16, v4i32 load, select, and, or, xor to v2i64.
797     for (unsigned i = (unsigned)MVT::v16i8; i != (unsigned)MVT::v2i64; i++) {
798       MVT::SimpleValueType SVT = (MVT::SimpleValueType)i;
799       EVT VT = SVT;
800
801       // Do not attempt to promote non-128-bit vectors
802       if (!VT.is128BitVector()) {
803         continue;
804       }
805       setOperationAction(ISD::AND,    SVT, Promote);
806       AddPromotedToType (ISD::AND,    SVT, MVT::v2i64);
807       setOperationAction(ISD::OR,     SVT, Promote);
808       AddPromotedToType (ISD::OR,     SVT, MVT::v2i64);
809       setOperationAction(ISD::XOR,    SVT, Promote);
810       AddPromotedToType (ISD::XOR,    SVT, MVT::v2i64);
811       setOperationAction(ISD::LOAD,   SVT, Promote);
812       AddPromotedToType (ISD::LOAD,   SVT, MVT::v2i64);
813       setOperationAction(ISD::SELECT, SVT, Promote);
814       AddPromotedToType (ISD::SELECT, SVT, MVT::v2i64);
815     }
816
817     setTruncStoreAction(MVT::f64, MVT::f32, Expand);
818
819     // Custom lower v2i64 and v2f64 selects.
820     setOperationAction(ISD::LOAD,               MVT::v2f64, Legal);
821     setOperationAction(ISD::LOAD,               MVT::v2i64, Legal);
822     setOperationAction(ISD::SELECT,             MVT::v2f64, Custom);
823     setOperationAction(ISD::SELECT,             MVT::v2i64, Custom);
824
825     setOperationAction(ISD::FP_TO_SINT,         MVT::v4i32, Legal);
826     setOperationAction(ISD::SINT_TO_FP,         MVT::v4i32, Legal);
827     if (!DisableMMX && Subtarget->hasMMX()) {
828       setOperationAction(ISD::FP_TO_SINT,         MVT::v2i32, Custom);
829       setOperationAction(ISD::SINT_TO_FP,         MVT::v2i32, Custom);
830     }
831   }
832
833   if (Subtarget->hasSSE41()) {
834     // FIXME: Do we need to handle scalar-to-vector here?
835     setOperationAction(ISD::MUL,                MVT::v4i32, Legal);
836
837     // i8 and i16 vectors are custom , because the source register and source
838     // source memory operand types are not the same width.  f32 vectors are
839     // custom since the immediate controlling the insert encodes additional
840     // information.
841     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v16i8, Custom);
842     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v8i16, Custom);
843     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4i32, Custom);
844     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4f32, Custom);
845
846     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i8, Custom);
847     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i16, Custom);
848     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i32, Custom);
849     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
850
851     if (Subtarget->is64Bit()) {
852       setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2i64, Legal);
853       setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Legal);
854     }
855   }
856
857   if (Subtarget->hasSSE42()) {
858     setOperationAction(ISD::VSETCC,             MVT::v2i64, Custom);
859   }
860
861   if (!UseSoftFloat && Subtarget->hasAVX()) {
862     addRegisterClass(MVT::v8f32, X86::VR256RegisterClass);
863     addRegisterClass(MVT::v4f64, X86::VR256RegisterClass);
864     addRegisterClass(MVT::v8i32, X86::VR256RegisterClass);
865     addRegisterClass(MVT::v4i64, X86::VR256RegisterClass);
866
867     setOperationAction(ISD::LOAD,               MVT::v8f32, Legal);
868     setOperationAction(ISD::LOAD,               MVT::v8i32, Legal);
869     setOperationAction(ISD::LOAD,               MVT::v4f64, Legal);
870     setOperationAction(ISD::LOAD,               MVT::v4i64, Legal);
871     setOperationAction(ISD::FADD,               MVT::v8f32, Legal);
872     setOperationAction(ISD::FSUB,               MVT::v8f32, Legal);
873     setOperationAction(ISD::FMUL,               MVT::v8f32, Legal);
874     setOperationAction(ISD::FDIV,               MVT::v8f32, Legal);
875     setOperationAction(ISD::FSQRT,              MVT::v8f32, Legal);
876     setOperationAction(ISD::FNEG,               MVT::v8f32, Custom);
877     //setOperationAction(ISD::BUILD_VECTOR,       MVT::v8f32, Custom);
878     //setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v8f32, Custom);
879     //setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8f32, Custom);
880     //setOperationAction(ISD::SELECT,             MVT::v8f32, Custom);
881     //setOperationAction(ISD::VSETCC,             MVT::v8f32, Custom);
882
883     // Operations to consider commented out -v16i16 v32i8
884     //setOperationAction(ISD::ADD,                MVT::v16i16, Legal);
885     setOperationAction(ISD::ADD,                MVT::v8i32, Custom);
886     setOperationAction(ISD::ADD,                MVT::v4i64, Custom);
887     //setOperationAction(ISD::SUB,                MVT::v32i8, Legal);
888     //setOperationAction(ISD::SUB,                MVT::v16i16, Legal);
889     setOperationAction(ISD::SUB,                MVT::v8i32, Custom);
890     setOperationAction(ISD::SUB,                MVT::v4i64, Custom);
891     //setOperationAction(ISD::MUL,                MVT::v16i16, Legal);
892     setOperationAction(ISD::FADD,               MVT::v4f64, Legal);
893     setOperationAction(ISD::FSUB,               MVT::v4f64, Legal);
894     setOperationAction(ISD::FMUL,               MVT::v4f64, Legal);
895     setOperationAction(ISD::FDIV,               MVT::v4f64, Legal);
896     setOperationAction(ISD::FSQRT,              MVT::v4f64, Legal);
897     setOperationAction(ISD::FNEG,               MVT::v4f64, Custom);
898
899     setOperationAction(ISD::VSETCC,             MVT::v4f64, Custom);
900     // setOperationAction(ISD::VSETCC,             MVT::v32i8, Custom);
901     // setOperationAction(ISD::VSETCC,             MVT::v16i16, Custom);
902     setOperationAction(ISD::VSETCC,             MVT::v8i32, Custom);
903
904     // setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v32i8, Custom);
905     // setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v16i16, Custom);
906     // setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v16i16, Custom);
907     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v8i32, Custom);
908     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v8f32, Custom);
909
910     setOperationAction(ISD::BUILD_VECTOR,       MVT::v4f64, Custom);
911     setOperationAction(ISD::BUILD_VECTOR,       MVT::v4i64, Custom);
912     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v4f64, Custom);
913     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v4i64, Custom);
914     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4f64, Custom);
915     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f64, Custom);
916
917 #if 0
918     // Not sure we want to do this since there are no 256-bit integer
919     // operations in AVX
920
921     // Custom lower build_vector, vector_shuffle, and extract_vector_elt.
922     // This includes 256-bit vectors
923     for (unsigned i = (unsigned)MVT::v16i8; i != (unsigned)MVT::v4i64; ++i) {
924       EVT VT = (MVT::SimpleValueType)i;
925
926       // Do not attempt to custom lower non-power-of-2 vectors
927       if (!isPowerOf2_32(VT.getVectorNumElements()))
928         continue;
929
930       setOperationAction(ISD::BUILD_VECTOR,       VT, Custom);
931       setOperationAction(ISD::VECTOR_SHUFFLE,     VT, Custom);
932       setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
933     }
934
935     if (Subtarget->is64Bit()) {
936       setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4i64, Custom);
937       setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i64, Custom);
938     }
939 #endif
940
941 #if 0
942     // Not sure we want to do this since there are no 256-bit integer
943     // operations in AVX
944
945     // Promote v32i8, v16i16, v8i32 load, select, and, or, xor to v4i64.
946     // Including 256-bit vectors
947     for (unsigned i = (unsigned)MVT::v16i8; i != (unsigned)MVT::v4i64; i++) {
948       EVT VT = (MVT::SimpleValueType)i;
949
950       if (!VT.is256BitVector()) {
951         continue;
952       }
953       setOperationAction(ISD::AND,    VT, Promote);
954       AddPromotedToType (ISD::AND,    VT, MVT::v4i64);
955       setOperationAction(ISD::OR,     VT, Promote);
956       AddPromotedToType (ISD::OR,     VT, MVT::v4i64);
957       setOperationAction(ISD::XOR,    VT, Promote);
958       AddPromotedToType (ISD::XOR,    VT, MVT::v4i64);
959       setOperationAction(ISD::LOAD,   VT, Promote);
960       AddPromotedToType (ISD::LOAD,   VT, MVT::v4i64);
961       setOperationAction(ISD::SELECT, VT, Promote);
962       AddPromotedToType (ISD::SELECT, VT, MVT::v4i64);
963     }
964
965     setTruncStoreAction(MVT::f64, MVT::f32, Expand);
966 #endif
967   }
968
969   // We want to custom lower some of our intrinsics.
970   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
971
972   // Add/Sub/Mul with overflow operations are custom lowered.
973   setOperationAction(ISD::SADDO, MVT::i32, Custom);
974   setOperationAction(ISD::SADDO, MVT::i64, Custom);
975   setOperationAction(ISD::UADDO, MVT::i32, Custom);
976   setOperationAction(ISD::UADDO, MVT::i64, Custom);
977   setOperationAction(ISD::SSUBO, MVT::i32, Custom);
978   setOperationAction(ISD::SSUBO, MVT::i64, Custom);
979   setOperationAction(ISD::USUBO, MVT::i32, Custom);
980   setOperationAction(ISD::USUBO, MVT::i64, Custom);
981   setOperationAction(ISD::SMULO, MVT::i32, Custom);
982   setOperationAction(ISD::SMULO, MVT::i64, Custom);
983
984   if (!Subtarget->is64Bit()) {
985     // These libcalls are not available in 32-bit.
986     setLibcallName(RTLIB::SHL_I128, 0);
987     setLibcallName(RTLIB::SRL_I128, 0);
988     setLibcallName(RTLIB::SRA_I128, 0);
989   }
990
991   // We have target-specific dag combine patterns for the following nodes:
992   setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
993   setTargetDAGCombine(ISD::EXTRACT_VECTOR_ELT);
994   setTargetDAGCombine(ISD::BUILD_VECTOR);
995   setTargetDAGCombine(ISD::SELECT);
996   setTargetDAGCombine(ISD::SHL);
997   setTargetDAGCombine(ISD::SRA);
998   setTargetDAGCombine(ISD::SRL);
999   setTargetDAGCombine(ISD::OR);
1000   setTargetDAGCombine(ISD::STORE);
1001   setTargetDAGCombine(ISD::MEMBARRIER);
1002   setTargetDAGCombine(ISD::ZERO_EXTEND);
1003   if (Subtarget->is64Bit())
1004     setTargetDAGCombine(ISD::MUL);
1005
1006   computeRegisterProperties();
1007
1008   // FIXME: These should be based on subtarget info. Plus, the values should
1009   // be smaller when we are in optimizing for size mode.
1010   maxStoresPerMemset = 16; // For @llvm.memset -> sequence of stores
1011   maxStoresPerMemcpy = 16; // For @llvm.memcpy -> sequence of stores
1012   maxStoresPerMemmove = 3; // For @llvm.memmove -> sequence of stores
1013   setPrefLoopAlignment(16);
1014   benefitFromCodePlacementOpt = true;
1015 }
1016
1017
1018 MVT::SimpleValueType X86TargetLowering::getSetCCResultType(EVT VT) const {
1019   return MVT::i8;
1020 }
1021
1022
1023 /// getMaxByValAlign - Helper for getByValTypeAlignment to determine
1024 /// the desired ByVal argument alignment.
1025 static void getMaxByValAlign(const Type *Ty, unsigned &MaxAlign) {
1026   if (MaxAlign == 16)
1027     return;
1028   if (const VectorType *VTy = dyn_cast<VectorType>(Ty)) {
1029     if (VTy->getBitWidth() == 128)
1030       MaxAlign = 16;
1031   } else if (const ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
1032     unsigned EltAlign = 0;
1033     getMaxByValAlign(ATy->getElementType(), EltAlign);
1034     if (EltAlign > MaxAlign)
1035       MaxAlign = EltAlign;
1036   } else if (const StructType *STy = dyn_cast<StructType>(Ty)) {
1037     for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
1038       unsigned EltAlign = 0;
1039       getMaxByValAlign(STy->getElementType(i), EltAlign);
1040       if (EltAlign > MaxAlign)
1041         MaxAlign = EltAlign;
1042       if (MaxAlign == 16)
1043         break;
1044     }
1045   }
1046   return;
1047 }
1048
1049 /// getByValTypeAlignment - Return the desired alignment for ByVal aggregate
1050 /// function arguments in the caller parameter area. For X86, aggregates
1051 /// that contain SSE vectors are placed at 16-byte boundaries while the rest
1052 /// are at 4-byte boundaries.
1053 unsigned X86TargetLowering::getByValTypeAlignment(const Type *Ty) const {
1054   if (Subtarget->is64Bit()) {
1055     // Max of 8 and alignment of type.
1056     unsigned TyAlign = TD->getABITypeAlignment(Ty);
1057     if (TyAlign > 8)
1058       return TyAlign;
1059     return 8;
1060   }
1061
1062   unsigned Align = 4;
1063   if (Subtarget->hasSSE1())
1064     getMaxByValAlign(Ty, Align);
1065   return Align;
1066 }
1067
1068 /// getOptimalMemOpType - Returns the target specific optimal type for load
1069 /// and store operations as a result of memset, memcpy, and memmove
1070 /// lowering. It returns MVT::iAny if SelectionDAG should be responsible for
1071 /// determining it.
1072 EVT
1073 X86TargetLowering::getOptimalMemOpType(uint64_t Size, unsigned Align,
1074                                        bool isSrcConst, bool isSrcStr,
1075                                        SelectionDAG &DAG) const {
1076   // FIXME: This turns off use of xmm stores for memset/memcpy on targets like
1077   // linux.  This is because the stack realignment code can't handle certain
1078   // cases like PR2962.  This should be removed when PR2962 is fixed.
1079   const Function *F = DAG.getMachineFunction().getFunction();
1080   bool NoImplicitFloatOps = F->hasFnAttr(Attribute::NoImplicitFloat);
1081   if (!NoImplicitFloatOps && Subtarget->getStackAlignment() >= 16) {
1082     if ((isSrcConst || isSrcStr) && Subtarget->hasSSE2() && Size >= 16)
1083       return MVT::v4i32;
1084     if ((isSrcConst || isSrcStr) && Subtarget->hasSSE1() && Size >= 16)
1085       return MVT::v4f32;
1086   }
1087   if (Subtarget->is64Bit() && Size >= 8)
1088     return MVT::i64;
1089   return MVT::i32;
1090 }
1091
1092 /// getJumpTableEncoding - Return the entry encoding for a jump table in the
1093 /// current function.  The returned value is a member of the
1094 /// MachineJumpTableInfo::JTEntryKind enum.
1095 unsigned X86TargetLowering::getJumpTableEncoding() const {
1096   // In GOT pic mode, each entry in the jump table is emitted as a @GOTOFF
1097   // symbol.
1098   if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1099       Subtarget->isPICStyleGOT())
1100     return MachineJumpTableInfo::EK_Custom32;
1101   
1102   // Otherwise, use the normal jump table encoding heuristics.
1103   return TargetLowering::getJumpTableEncoding();
1104 }
1105
1106 /// getPICBaseSymbol - Return the X86-32 PIC base.
1107 MCSymbol *
1108 X86TargetLowering::getPICBaseSymbol(const MachineFunction *MF,
1109                                     MCContext &Ctx) const {
1110   const MCAsmInfo &MAI = *getTargetMachine().getMCAsmInfo();
1111   return Ctx.GetOrCreateTemporarySymbol(Twine(MAI.getPrivateGlobalPrefix())+
1112                                         Twine(MF->getFunctionNumber())+"$pb");
1113 }
1114
1115
1116 const MCExpr *
1117 X86TargetLowering::LowerCustomJumpTableEntry(const MachineJumpTableInfo *MJTI,
1118                                              const MachineBasicBlock *MBB,
1119                                              unsigned uid,MCContext &Ctx) const{
1120   assert(getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1121          Subtarget->isPICStyleGOT());
1122   // In 32-bit ELF systems, our jump table entries are formed with @GOTOFF
1123   // entries.
1124   return MCSymbolRefExpr::Create(MBB->getSymbol(),
1125                                  MCSymbolRefExpr::VK_GOTOFF, Ctx);
1126 }
1127
1128 /// getPICJumpTableRelocaBase - Returns relocation base for the given PIC
1129 /// jumptable.
1130 SDValue X86TargetLowering::getPICJumpTableRelocBase(SDValue Table,
1131                                                     SelectionDAG &DAG) const {
1132   if (!Subtarget->is64Bit())
1133     // This doesn't have DebugLoc associated with it, but is not really the
1134     // same as a Register.
1135     return DAG.getNode(X86ISD::GlobalBaseReg, DebugLoc::getUnknownLoc(),
1136                        getPointerTy());
1137   return Table;
1138 }
1139
1140 /// getPICJumpTableRelocBaseExpr - This returns the relocation base for the
1141 /// given PIC jumptable, the same as getPICJumpTableRelocBase, but as an
1142 /// MCExpr.
1143 const MCExpr *X86TargetLowering::
1144 getPICJumpTableRelocBaseExpr(const MachineFunction *MF, unsigned JTI,
1145                              MCContext &Ctx) const {
1146   // X86-64 uses RIP relative addressing based on the jump table label.
1147   if (Subtarget->isPICStyleRIPRel())
1148     return TargetLowering::getPICJumpTableRelocBaseExpr(MF, JTI, Ctx);
1149
1150   // Otherwise, the reference is relative to the PIC base.
1151   return MCSymbolRefExpr::Create(getPICBaseSymbol(MF, Ctx), Ctx);
1152 }
1153
1154 /// getFunctionAlignment - Return the Log2 alignment of this function.
1155 unsigned X86TargetLowering::getFunctionAlignment(const Function *F) const {
1156   return F->hasFnAttr(Attribute::OptimizeForSize) ? 0 : 4;
1157 }
1158
1159 //===----------------------------------------------------------------------===//
1160 //               Return Value Calling Convention Implementation
1161 //===----------------------------------------------------------------------===//
1162
1163 #include "X86GenCallingConv.inc"
1164
1165 bool 
1166 X86TargetLowering::CanLowerReturn(CallingConv::ID CallConv, bool isVarArg,
1167                         const SmallVectorImpl<EVT> &OutTys,
1168                         const SmallVectorImpl<ISD::ArgFlagsTy> &ArgsFlags,
1169                         SelectionDAG &DAG) {
1170   SmallVector<CCValAssign, 16> RVLocs;
1171   CCState CCInfo(CallConv, isVarArg, getTargetMachine(),
1172                  RVLocs, *DAG.getContext());
1173   return CCInfo.CheckReturn(OutTys, ArgsFlags, RetCC_X86);
1174 }
1175
1176 SDValue
1177 X86TargetLowering::LowerReturn(SDValue Chain,
1178                                CallingConv::ID CallConv, bool isVarArg,
1179                                const SmallVectorImpl<ISD::OutputArg> &Outs,
1180                                DebugLoc dl, SelectionDAG &DAG) {
1181
1182   SmallVector<CCValAssign, 16> RVLocs;
1183   CCState CCInfo(CallConv, isVarArg, getTargetMachine(),
1184                  RVLocs, *DAG.getContext());
1185   CCInfo.AnalyzeReturn(Outs, RetCC_X86);
1186
1187   // Add the regs to the liveout set for the function.
1188   MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo();
1189   for (unsigned i = 0; i != RVLocs.size(); ++i)
1190     if (RVLocs[i].isRegLoc() && !MRI.isLiveOut(RVLocs[i].getLocReg()))
1191       MRI.addLiveOut(RVLocs[i].getLocReg());
1192
1193   SDValue Flag;
1194
1195   SmallVector<SDValue, 6> RetOps;
1196   RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
1197   // Operand #1 = Bytes To Pop
1198   RetOps.push_back(DAG.getTargetConstant(getBytesToPopOnReturn(), MVT::i16));
1199
1200   // Copy the result values into the output registers.
1201   for (unsigned i = 0; i != RVLocs.size(); ++i) {
1202     CCValAssign &VA = RVLocs[i];
1203     assert(VA.isRegLoc() && "Can only return in registers!");
1204     SDValue ValToCopy = Outs[i].Val;
1205
1206     // Returns in ST0/ST1 are handled specially: these are pushed as operands to
1207     // the RET instruction and handled by the FP Stackifier.
1208     if (VA.getLocReg() == X86::ST0 ||
1209         VA.getLocReg() == X86::ST1) {
1210       // If this is a copy from an xmm register to ST(0), use an FPExtend to
1211       // change the value to the FP stack register class.
1212       if (isScalarFPTypeInSSEReg(VA.getValVT()))
1213         ValToCopy = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f80, ValToCopy);
1214       RetOps.push_back(ValToCopy);
1215       // Don't emit a copytoreg.
1216       continue;
1217     }
1218
1219     // 64-bit vector (MMX) values are returned in XMM0 / XMM1 except for v1i64
1220     // which is returned in RAX / RDX.
1221     if (Subtarget->is64Bit()) {
1222       EVT ValVT = ValToCopy.getValueType();
1223       if (ValVT.isVector() && ValVT.getSizeInBits() == 64) {
1224         ValToCopy = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::i64, ValToCopy);
1225         if (VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1)
1226           ValToCopy = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64, ValToCopy);
1227       }
1228     }
1229
1230     Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), ValToCopy, Flag);
1231     Flag = Chain.getValue(1);
1232   }
1233
1234   // The x86-64 ABI for returning structs by value requires that we copy
1235   // the sret argument into %rax for the return. We saved the argument into
1236   // a virtual register in the entry block, so now we copy the value out
1237   // and into %rax.
1238   if (Subtarget->is64Bit() &&
1239       DAG.getMachineFunction().getFunction()->hasStructRetAttr()) {
1240     MachineFunction &MF = DAG.getMachineFunction();
1241     X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1242     unsigned Reg = FuncInfo->getSRetReturnReg();
1243     if (!Reg) {
1244       Reg = MRI.createVirtualRegister(getRegClassFor(MVT::i64));
1245       FuncInfo->setSRetReturnReg(Reg);
1246     }
1247     SDValue Val = DAG.getCopyFromReg(Chain, dl, Reg, getPointerTy());
1248
1249     Chain = DAG.getCopyToReg(Chain, dl, X86::RAX, Val, Flag);
1250     Flag = Chain.getValue(1);
1251
1252     // RAX now acts like a return value.
1253     MRI.addLiveOut(X86::RAX);
1254   }
1255
1256   RetOps[0] = Chain;  // Update chain.
1257
1258   // Add the flag if we have it.
1259   if (Flag.getNode())
1260     RetOps.push_back(Flag);
1261
1262   return DAG.getNode(X86ISD::RET_FLAG, dl,
1263                      MVT::Other, &RetOps[0], RetOps.size());
1264 }
1265
1266 /// LowerCallResult - Lower the result values of a call into the
1267 /// appropriate copies out of appropriate physical registers.
1268 ///
1269 SDValue
1270 X86TargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
1271                                    CallingConv::ID CallConv, bool isVarArg,
1272                                    const SmallVectorImpl<ISD::InputArg> &Ins,
1273                                    DebugLoc dl, SelectionDAG &DAG,
1274                                    SmallVectorImpl<SDValue> &InVals) {
1275
1276   // Assign locations to each value returned by this call.
1277   SmallVector<CCValAssign, 16> RVLocs;
1278   bool Is64Bit = Subtarget->is64Bit();
1279   CCState CCInfo(CallConv, isVarArg, getTargetMachine(),
1280                  RVLocs, *DAG.getContext());
1281   CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
1282
1283   // Copy all of the result registers out of their specified physreg.
1284   for (unsigned i = 0; i != RVLocs.size(); ++i) {
1285     CCValAssign &VA = RVLocs[i];
1286     EVT CopyVT = VA.getValVT();
1287
1288     // If this is x86-64, and we disabled SSE, we can't return FP values
1289     if ((CopyVT == MVT::f32 || CopyVT == MVT::f64) &&
1290         ((Is64Bit || Ins[i].Flags.isInReg()) && !Subtarget->hasSSE1())) {
1291       llvm_report_error("SSE register return with SSE disabled");
1292     }
1293
1294     // If this is a call to a function that returns an fp value on the floating
1295     // point stack, but where we prefer to use the value in xmm registers, copy
1296     // it out as F80 and use a truncate to move it from fp stack reg to xmm reg.
1297     if ((VA.getLocReg() == X86::ST0 ||
1298          VA.getLocReg() == X86::ST1) &&
1299         isScalarFPTypeInSSEReg(VA.getValVT())) {
1300       CopyVT = MVT::f80;
1301     }
1302
1303     SDValue Val;
1304     if (Is64Bit && CopyVT.isVector() && CopyVT.getSizeInBits() == 64) {
1305       // For x86-64, MMX values are returned in XMM0 / XMM1 except for v1i64.
1306       if (VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) {
1307         Chain = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(),
1308                                    MVT::v2i64, InFlag).getValue(1);
1309         Val = Chain.getValue(0);
1310         Val = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i64,
1311                           Val, DAG.getConstant(0, MVT::i64));
1312       } else {
1313         Chain = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(),
1314                                    MVT::i64, InFlag).getValue(1);
1315         Val = Chain.getValue(0);
1316       }
1317       Val = DAG.getNode(ISD::BIT_CONVERT, dl, CopyVT, Val);
1318     } else {
1319       Chain = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(),
1320                                  CopyVT, InFlag).getValue(1);
1321       Val = Chain.getValue(0);
1322     }
1323     InFlag = Chain.getValue(2);
1324
1325     if (CopyVT != VA.getValVT()) {
1326       // Round the F80 the right size, which also moves to the appropriate xmm
1327       // register.
1328       Val = DAG.getNode(ISD::FP_ROUND, dl, VA.getValVT(), Val,
1329                         // This truncation won't change the value.
1330                         DAG.getIntPtrConstant(1));
1331     }
1332
1333     InVals.push_back(Val);
1334   }
1335
1336   return Chain;
1337 }
1338
1339
1340 //===----------------------------------------------------------------------===//
1341 //                C & StdCall & Fast Calling Convention implementation
1342 //===----------------------------------------------------------------------===//
1343 //  StdCall calling convention seems to be standard for many Windows' API
1344 //  routines and around. It differs from C calling convention just a little:
1345 //  callee should clean up the stack, not caller. Symbols should be also
1346 //  decorated in some fancy way :) It doesn't support any vector arguments.
1347 //  For info on fast calling convention see Fast Calling Convention (tail call)
1348 //  implementation LowerX86_32FastCCCallTo.
1349
1350 /// CallIsStructReturn - Determines whether a call uses struct return
1351 /// semantics.
1352 static bool CallIsStructReturn(const SmallVectorImpl<ISD::OutputArg> &Outs) {
1353   if (Outs.empty())
1354     return false;
1355
1356   return Outs[0].Flags.isSRet();
1357 }
1358
1359 /// ArgsAreStructReturn - Determines whether a function uses struct
1360 /// return semantics.
1361 static bool
1362 ArgsAreStructReturn(const SmallVectorImpl<ISD::InputArg> &Ins) {
1363   if (Ins.empty())
1364     return false;
1365
1366   return Ins[0].Flags.isSRet();
1367 }
1368
1369 /// IsCalleePop - Determines whether the callee is required to pop its
1370 /// own arguments. Callee pop is necessary to support tail calls.
1371 bool X86TargetLowering::IsCalleePop(bool IsVarArg, CallingConv::ID CallingConv){
1372   if (IsVarArg)
1373     return false;
1374
1375   switch (CallingConv) {
1376   default:
1377     return false;
1378   case CallingConv::X86_StdCall:
1379     return !Subtarget->is64Bit();
1380   case CallingConv::X86_FastCall:
1381     return !Subtarget->is64Bit();
1382   case CallingConv::Fast:
1383     return GuaranteedTailCallOpt;
1384   case CallingConv::GHC:
1385     return GuaranteedTailCallOpt;
1386   }
1387 }
1388
1389 /// CCAssignFnForNode - Selects the correct CCAssignFn for a the
1390 /// given CallingConvention value.
1391 CCAssignFn *X86TargetLowering::CCAssignFnForNode(CallingConv::ID CC) const {
1392   if (Subtarget->is64Bit()) {
1393     if (CC == CallingConv::GHC)
1394       return CC_X86_64_GHC;
1395     else if (Subtarget->isTargetWin64())
1396       return CC_X86_Win64_C;
1397     else
1398       return CC_X86_64_C;
1399   }
1400
1401   if (CC == CallingConv::X86_FastCall)
1402     return CC_X86_32_FastCall;
1403   else if (CC == CallingConv::Fast)
1404     return CC_X86_32_FastCC;
1405   else if (CC == CallingConv::GHC)
1406     return CC_X86_32_GHC;
1407   else
1408     return CC_X86_32_C;
1409 }
1410
1411 /// CreateCopyOfByValArgument - Make a copy of an aggregate at address specified
1412 /// by "Src" to address "Dst" with size and alignment information specified by
1413 /// the specific parameter attribute. The copy will be passed as a byval
1414 /// function parameter.
1415 static SDValue
1416 CreateCopyOfByValArgument(SDValue Src, SDValue Dst, SDValue Chain,
1417                           ISD::ArgFlagsTy Flags, SelectionDAG &DAG,
1418                           DebugLoc dl) {
1419   SDValue SizeNode     = DAG.getConstant(Flags.getByValSize(), MVT::i32);
1420   return DAG.getMemcpy(Chain, dl, Dst, Src, SizeNode, Flags.getByValAlign(),
1421                        /*AlwaysInline=*/true, NULL, 0, NULL, 0);
1422 }
1423
1424 /// IsTailCallConvention - Return true if the calling convention is one that
1425 /// supports tail call optimization.
1426 static bool IsTailCallConvention(CallingConv::ID CC) {
1427   return (CC == CallingConv::Fast || CC == CallingConv::GHC);
1428 }
1429
1430 /// FuncIsMadeTailCallSafe - Return true if the function is being made into
1431 /// a tailcall target by changing its ABI.
1432 static bool FuncIsMadeTailCallSafe(CallingConv::ID CC) {
1433   return GuaranteedTailCallOpt && IsTailCallConvention(CC);
1434 }
1435
1436 SDValue
1437 X86TargetLowering::LowerMemArgument(SDValue Chain,
1438                                     CallingConv::ID CallConv,
1439                                     const SmallVectorImpl<ISD::InputArg> &Ins,
1440                                     DebugLoc dl, SelectionDAG &DAG,
1441                                     const CCValAssign &VA,
1442                                     MachineFrameInfo *MFI,
1443                                     unsigned i) {
1444   // Create the nodes corresponding to a load from this parameter slot.
1445   ISD::ArgFlagsTy Flags = Ins[i].Flags;
1446   bool AlwaysUseMutable = FuncIsMadeTailCallSafe(CallConv);
1447   bool isImmutable = !AlwaysUseMutable && !Flags.isByVal();
1448   EVT ValVT;
1449
1450   // If value is passed by pointer we have address passed instead of the value
1451   // itself.
1452   if (VA.getLocInfo() == CCValAssign::Indirect)
1453     ValVT = VA.getLocVT();
1454   else
1455     ValVT = VA.getValVT();
1456
1457   // FIXME: For now, all byval parameter objects are marked mutable. This can be
1458   // changed with more analysis.
1459   // In case of tail call optimization mark all arguments mutable. Since they
1460   // could be overwritten by lowering of arguments in case of a tail call.
1461   if (Flags.isByVal()) {
1462     int FI = MFI->CreateFixedObject(Flags.getByValSize(),
1463                                     VA.getLocMemOffset(), isImmutable, false);
1464     return DAG.getFrameIndex(FI, getPointerTy());
1465   } else {
1466     int FI = MFI->CreateFixedObject(ValVT.getSizeInBits()/8,
1467                                     VA.getLocMemOffset(), isImmutable, false);
1468     SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
1469     return DAG.getLoad(ValVT, dl, Chain, FIN,
1470                        PseudoSourceValue::getFixedStack(FI), 0,
1471                        false, false, 0);
1472   }
1473 }
1474
1475 SDValue
1476 X86TargetLowering::LowerFormalArguments(SDValue Chain,
1477                                         CallingConv::ID CallConv,
1478                                         bool isVarArg,
1479                                       const SmallVectorImpl<ISD::InputArg> &Ins,
1480                                         DebugLoc dl,
1481                                         SelectionDAG &DAG,
1482                                         SmallVectorImpl<SDValue> &InVals) {
1483   MachineFunction &MF = DAG.getMachineFunction();
1484   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1485
1486   const Function* Fn = MF.getFunction();
1487   if (Fn->hasExternalLinkage() &&
1488       Subtarget->isTargetCygMing() &&
1489       Fn->getName() == "main")
1490     FuncInfo->setForceFramePointer(true);
1491
1492   MachineFrameInfo *MFI = MF.getFrameInfo();
1493   bool Is64Bit = Subtarget->is64Bit();
1494   bool IsWin64 = Subtarget->isTargetWin64();
1495
1496   assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
1497          "Var args not supported with calling convention fastcc or ghc");
1498
1499   // Assign locations to all of the incoming arguments.
1500   SmallVector<CCValAssign, 16> ArgLocs;
1501   CCState CCInfo(CallConv, isVarArg, getTargetMachine(),
1502                  ArgLocs, *DAG.getContext());
1503   CCInfo.AnalyzeFormalArguments(Ins, CCAssignFnForNode(CallConv));
1504
1505   unsigned LastVal = ~0U;
1506   SDValue ArgValue;
1507   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
1508     CCValAssign &VA = ArgLocs[i];
1509     // TODO: If an arg is passed in two places (e.g. reg and stack), skip later
1510     // places.
1511     assert(VA.getValNo() != LastVal &&
1512            "Don't support value assigned to multiple locs yet");
1513     LastVal = VA.getValNo();
1514
1515     if (VA.isRegLoc()) {
1516       EVT RegVT = VA.getLocVT();
1517       TargetRegisterClass *RC = NULL;
1518       if (RegVT == MVT::i32)
1519         RC = X86::GR32RegisterClass;
1520       else if (Is64Bit && RegVT == MVT::i64)
1521         RC = X86::GR64RegisterClass;
1522       else if (RegVT == MVT::f32)
1523         RC = X86::FR32RegisterClass;
1524       else if (RegVT == MVT::f64)
1525         RC = X86::FR64RegisterClass;
1526       else if (RegVT.isVector() && RegVT.getSizeInBits() == 128)
1527         RC = X86::VR128RegisterClass;
1528       else if (RegVT.isVector() && RegVT.getSizeInBits() == 64)
1529         RC = X86::VR64RegisterClass;
1530       else
1531         llvm_unreachable("Unknown argument type!");
1532
1533       unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
1534       ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
1535
1536       // If this is an 8 or 16-bit value, it is really passed promoted to 32
1537       // bits.  Insert an assert[sz]ext to capture this, then truncate to the
1538       // right size.
1539       if (VA.getLocInfo() == CCValAssign::SExt)
1540         ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
1541                                DAG.getValueType(VA.getValVT()));
1542       else if (VA.getLocInfo() == CCValAssign::ZExt)
1543         ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
1544                                DAG.getValueType(VA.getValVT()));
1545       else if (VA.getLocInfo() == CCValAssign::BCvt)
1546         ArgValue = DAG.getNode(ISD::BIT_CONVERT, dl, VA.getValVT(), ArgValue);
1547
1548       if (VA.isExtInLoc()) {
1549         // Handle MMX values passed in XMM regs.
1550         if (RegVT.isVector()) {
1551           ArgValue = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i64,
1552                                  ArgValue, DAG.getConstant(0, MVT::i64));
1553           ArgValue = DAG.getNode(ISD::BIT_CONVERT, dl, VA.getValVT(), ArgValue);
1554         } else
1555           ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
1556       }
1557     } else {
1558       assert(VA.isMemLoc());
1559       ArgValue = LowerMemArgument(Chain, CallConv, Ins, dl, DAG, VA, MFI, i);
1560     }
1561
1562     // If value is passed via pointer - do a load.
1563     if (VA.getLocInfo() == CCValAssign::Indirect)
1564       ArgValue = DAG.getLoad(VA.getValVT(), dl, Chain, ArgValue, NULL, 0,
1565                              false, false, 0);
1566
1567     InVals.push_back(ArgValue);
1568   }
1569
1570   // The x86-64 ABI for returning structs by value requires that we copy
1571   // the sret argument into %rax for the return. Save the argument into
1572   // a virtual register so that we can access it from the return points.
1573   if (Is64Bit && MF.getFunction()->hasStructRetAttr()) {
1574     X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1575     unsigned Reg = FuncInfo->getSRetReturnReg();
1576     if (!Reg) {
1577       Reg = MF.getRegInfo().createVirtualRegister(getRegClassFor(MVT::i64));
1578       FuncInfo->setSRetReturnReg(Reg);
1579     }
1580     SDValue Copy = DAG.getCopyToReg(DAG.getEntryNode(), dl, Reg, InVals[0]);
1581     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Copy, Chain);
1582   }
1583
1584   unsigned StackSize = CCInfo.getNextStackOffset();
1585   // Align stack specially for tail calls.
1586   if (FuncIsMadeTailCallSafe(CallConv))
1587     StackSize = GetAlignedArgumentStackSize(StackSize, DAG);
1588
1589   // If the function takes variable number of arguments, make a frame index for
1590   // the start of the first vararg value... for expansion of llvm.va_start.
1591   if (isVarArg) {
1592     if (Is64Bit || CallConv != CallingConv::X86_FastCall) {
1593       VarArgsFrameIndex = MFI->CreateFixedObject(1, StackSize, true, false);
1594     }
1595     if (Is64Bit) {
1596       unsigned TotalNumIntRegs = 0, TotalNumXMMRegs = 0;
1597
1598       // FIXME: We should really autogenerate these arrays
1599       static const unsigned GPR64ArgRegsWin64[] = {
1600         X86::RCX, X86::RDX, X86::R8,  X86::R9
1601       };
1602       static const unsigned XMMArgRegsWin64[] = {
1603         X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3
1604       };
1605       static const unsigned GPR64ArgRegs64Bit[] = {
1606         X86::RDI, X86::RSI, X86::RDX, X86::RCX, X86::R8, X86::R9
1607       };
1608       static const unsigned XMMArgRegs64Bit[] = {
1609         X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
1610         X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
1611       };
1612       const unsigned *GPR64ArgRegs, *XMMArgRegs;
1613
1614       if (IsWin64) {
1615         TotalNumIntRegs = 4; TotalNumXMMRegs = 4;
1616         GPR64ArgRegs = GPR64ArgRegsWin64;
1617         XMMArgRegs = XMMArgRegsWin64;
1618       } else {
1619         TotalNumIntRegs = 6; TotalNumXMMRegs = 8;
1620         GPR64ArgRegs = GPR64ArgRegs64Bit;
1621         XMMArgRegs = XMMArgRegs64Bit;
1622       }
1623       unsigned NumIntRegs = CCInfo.getFirstUnallocated(GPR64ArgRegs,
1624                                                        TotalNumIntRegs);
1625       unsigned NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs,
1626                                                        TotalNumXMMRegs);
1627
1628       bool NoImplicitFloatOps = Fn->hasFnAttr(Attribute::NoImplicitFloat);
1629       assert(!(NumXMMRegs && !Subtarget->hasSSE1()) &&
1630              "SSE register cannot be used when SSE is disabled!");
1631       assert(!(NumXMMRegs && UseSoftFloat && NoImplicitFloatOps) &&
1632              "SSE register cannot be used when SSE is disabled!");
1633       if (UseSoftFloat || NoImplicitFloatOps || !Subtarget->hasSSE1())
1634         // Kernel mode asks for SSE to be disabled, so don't push them
1635         // on the stack.
1636         TotalNumXMMRegs = 0;
1637
1638       // For X86-64, if there are vararg parameters that are passed via
1639       // registers, then we must store them to their spots on the stack so they
1640       // may be loaded by deferencing the result of va_next.
1641       VarArgsGPOffset = NumIntRegs * 8;
1642       VarArgsFPOffset = TotalNumIntRegs * 8 + NumXMMRegs * 16;
1643       RegSaveFrameIndex = MFI->CreateStackObject(TotalNumIntRegs * 8 +
1644                                                  TotalNumXMMRegs * 16, 16,
1645                                                  false);
1646
1647       // Store the integer parameter registers.
1648       SmallVector<SDValue, 8> MemOps;
1649       SDValue RSFIN = DAG.getFrameIndex(RegSaveFrameIndex, getPointerTy());
1650       unsigned Offset = VarArgsGPOffset;
1651       for (; NumIntRegs != TotalNumIntRegs; ++NumIntRegs) {
1652         SDValue FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(), RSFIN,
1653                                   DAG.getIntPtrConstant(Offset));
1654         unsigned VReg = MF.addLiveIn(GPR64ArgRegs[NumIntRegs],
1655                                      X86::GR64RegisterClass);
1656         SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
1657         SDValue Store =
1658           DAG.getStore(Val.getValue(1), dl, Val, FIN,
1659                        PseudoSourceValue::getFixedStack(RegSaveFrameIndex),
1660                        Offset, false, false, 0);
1661         MemOps.push_back(Store);
1662         Offset += 8;
1663       }
1664
1665       if (TotalNumXMMRegs != 0 && NumXMMRegs != TotalNumXMMRegs) {
1666         // Now store the XMM (fp + vector) parameter registers.
1667         SmallVector<SDValue, 11> SaveXMMOps;
1668         SaveXMMOps.push_back(Chain);
1669
1670         unsigned AL = MF.addLiveIn(X86::AL, X86::GR8RegisterClass);
1671         SDValue ALVal = DAG.getCopyFromReg(DAG.getEntryNode(), dl, AL, MVT::i8);
1672         SaveXMMOps.push_back(ALVal);
1673
1674         SaveXMMOps.push_back(DAG.getIntPtrConstant(RegSaveFrameIndex));
1675         SaveXMMOps.push_back(DAG.getIntPtrConstant(VarArgsFPOffset));
1676
1677         for (; NumXMMRegs != TotalNumXMMRegs; ++NumXMMRegs) {
1678           unsigned VReg = MF.addLiveIn(XMMArgRegs[NumXMMRegs],
1679                                        X86::VR128RegisterClass);
1680           SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::v4f32);
1681           SaveXMMOps.push_back(Val);
1682         }
1683         MemOps.push_back(DAG.getNode(X86ISD::VASTART_SAVE_XMM_REGS, dl,
1684                                      MVT::Other,
1685                                      &SaveXMMOps[0], SaveXMMOps.size()));
1686       }
1687
1688       if (!MemOps.empty())
1689         Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
1690                             &MemOps[0], MemOps.size());
1691     }
1692   }
1693
1694   // Some CCs need callee pop.
1695   if (IsCalleePop(isVarArg, CallConv)) {
1696     BytesToPopOnReturn  = StackSize; // Callee pops everything.
1697   } else {
1698     BytesToPopOnReturn  = 0; // Callee pops nothing.
1699     // If this is an sret function, the return should pop the hidden pointer.
1700     if (!Is64Bit && !IsTailCallConvention(CallConv) && ArgsAreStructReturn(Ins))
1701       BytesToPopOnReturn = 4;
1702   }
1703
1704   if (!Is64Bit) {
1705     RegSaveFrameIndex = 0xAAAAAAA;   // RegSaveFrameIndex is X86-64 only.
1706     if (CallConv == CallingConv::X86_FastCall)
1707       VarArgsFrameIndex = 0xAAAAAAA;   // fastcc functions can't have varargs.
1708   }
1709
1710   FuncInfo->setBytesToPopOnReturn(BytesToPopOnReturn);
1711
1712   return Chain;
1713 }
1714
1715 SDValue
1716 X86TargetLowering::LowerMemOpCallTo(SDValue Chain,
1717                                     SDValue StackPtr, SDValue Arg,
1718                                     DebugLoc dl, SelectionDAG &DAG,
1719                                     const CCValAssign &VA,
1720                                     ISD::ArgFlagsTy Flags) {
1721   const unsigned FirstStackArgOffset = (Subtarget->isTargetWin64() ? 32 : 0);
1722   unsigned LocMemOffset = FirstStackArgOffset + VA.getLocMemOffset();
1723   SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset);
1724   PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, PtrOff);
1725   if (Flags.isByVal()) {
1726     return CreateCopyOfByValArgument(Arg, PtrOff, Chain, Flags, DAG, dl);
1727   }
1728   return DAG.getStore(Chain, dl, Arg, PtrOff,
1729                       PseudoSourceValue::getStack(), LocMemOffset,
1730                       false, false, 0);
1731 }
1732
1733 /// EmitTailCallLoadRetAddr - Emit a load of return address if tail call
1734 /// optimization is performed and it is required.
1735 SDValue
1736 X86TargetLowering::EmitTailCallLoadRetAddr(SelectionDAG &DAG,
1737                                            SDValue &OutRetAddr, SDValue Chain,
1738                                            bool IsTailCall, bool Is64Bit,
1739                                            int FPDiff, DebugLoc dl) {
1740   // Adjust the Return address stack slot.
1741   EVT VT = getPointerTy();
1742   OutRetAddr = getReturnAddressFrameIndex(DAG);
1743
1744   // Load the "old" Return address.
1745   OutRetAddr = DAG.getLoad(VT, dl, Chain, OutRetAddr, NULL, 0, false, false, 0);
1746   return SDValue(OutRetAddr.getNode(), 1);
1747 }
1748
1749 /// EmitTailCallStoreRetAddr - Emit a store of the return adress if tail call
1750 /// optimization is performed and it is required (FPDiff!=0).
1751 static SDValue
1752 EmitTailCallStoreRetAddr(SelectionDAG & DAG, MachineFunction &MF,
1753                          SDValue Chain, SDValue RetAddrFrIdx,
1754                          bool Is64Bit, int FPDiff, DebugLoc dl) {
1755   // Store the return address to the appropriate stack slot.
1756   if (!FPDiff) return Chain;
1757   // Calculate the new stack slot for the return address.
1758   int SlotSize = Is64Bit ? 8 : 4;
1759   int NewReturnAddrFI =
1760     MF.getFrameInfo()->CreateFixedObject(SlotSize, FPDiff-SlotSize, false, false);
1761   EVT VT = Is64Bit ? MVT::i64 : MVT::i32;
1762   SDValue NewRetAddrFrIdx = DAG.getFrameIndex(NewReturnAddrFI, VT);
1763   Chain = DAG.getStore(Chain, dl, RetAddrFrIdx, NewRetAddrFrIdx,
1764                        PseudoSourceValue::getFixedStack(NewReturnAddrFI), 0,
1765                        false, false, 0);
1766   return Chain;
1767 }
1768
1769 SDValue
1770 X86TargetLowering::LowerCall(SDValue Chain, SDValue Callee,
1771                              CallingConv::ID CallConv, bool isVarArg,
1772                              bool &isTailCall,
1773                              const SmallVectorImpl<ISD::OutputArg> &Outs,
1774                              const SmallVectorImpl<ISD::InputArg> &Ins,
1775                              DebugLoc dl, SelectionDAG &DAG,
1776                              SmallVectorImpl<SDValue> &InVals) {
1777   MachineFunction &MF = DAG.getMachineFunction();
1778   bool Is64Bit        = Subtarget->is64Bit();
1779   bool IsStructRet    = CallIsStructReturn(Outs);
1780   bool IsSibcall      = false;
1781
1782   if (isTailCall) {
1783     // Check if it's really possible to do a tail call.
1784     isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv,
1785                     isVarArg, IsStructRet, MF.getFunction()->hasStructRetAttr(),
1786                                                    Outs, Ins, DAG);
1787
1788     // Sibcalls are automatically detected tailcalls which do not require
1789     // ABI changes.
1790     if (!GuaranteedTailCallOpt && isTailCall)
1791       IsSibcall = true;
1792
1793     if (isTailCall)
1794       ++NumTailCalls;
1795   }
1796
1797   assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
1798          "Var args not supported with calling convention fastcc or ghc");
1799
1800   // Analyze operands of the call, assigning locations to each operand.
1801   SmallVector<CCValAssign, 16> ArgLocs;
1802   CCState CCInfo(CallConv, isVarArg, getTargetMachine(),
1803                  ArgLocs, *DAG.getContext());
1804   CCInfo.AnalyzeCallOperands(Outs, CCAssignFnForNode(CallConv));
1805
1806   // Get a count of how many bytes are to be pushed on the stack.
1807   unsigned NumBytes = CCInfo.getNextStackOffset();
1808   if (IsSibcall)
1809     // This is a sibcall. The memory operands are available in caller's
1810     // own caller's stack.
1811     NumBytes = 0;
1812   else if (GuaranteedTailCallOpt && IsTailCallConvention(CallConv))
1813     NumBytes = GetAlignedArgumentStackSize(NumBytes, DAG);
1814
1815   int FPDiff = 0;
1816   if (isTailCall && !IsSibcall) {
1817     // Lower arguments at fp - stackoffset + fpdiff.
1818     unsigned NumBytesCallerPushed =
1819       MF.getInfo<X86MachineFunctionInfo>()->getBytesToPopOnReturn();
1820     FPDiff = NumBytesCallerPushed - NumBytes;
1821
1822     // Set the delta of movement of the returnaddr stackslot.
1823     // But only set if delta is greater than previous delta.
1824     if (FPDiff < (MF.getInfo<X86MachineFunctionInfo>()->getTCReturnAddrDelta()))
1825       MF.getInfo<X86MachineFunctionInfo>()->setTCReturnAddrDelta(FPDiff);
1826   }
1827
1828   if (!IsSibcall)
1829     Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes, true));
1830
1831   SDValue RetAddrFrIdx;
1832   // Load return adress for tail calls.
1833   if (isTailCall && FPDiff)
1834     Chain = EmitTailCallLoadRetAddr(DAG, RetAddrFrIdx, Chain, isTailCall,
1835                                     Is64Bit, FPDiff, dl);
1836
1837   SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
1838   SmallVector<SDValue, 8> MemOpChains;
1839   SDValue StackPtr;
1840
1841   // Walk the register/memloc assignments, inserting copies/loads.  In the case
1842   // of tail call optimization arguments are handle later.
1843   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
1844     CCValAssign &VA = ArgLocs[i];
1845     EVT RegVT = VA.getLocVT();
1846     SDValue Arg = Outs[i].Val;
1847     ISD::ArgFlagsTy Flags = Outs[i].Flags;
1848     bool isByVal = Flags.isByVal();
1849
1850     // Promote the value if needed.
1851     switch (VA.getLocInfo()) {
1852     default: llvm_unreachable("Unknown loc info!");
1853     case CCValAssign::Full: break;
1854     case CCValAssign::SExt:
1855       Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, RegVT, Arg);
1856       break;
1857     case CCValAssign::ZExt:
1858       Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, RegVT, Arg);
1859       break;
1860     case CCValAssign::AExt:
1861       if (RegVT.isVector() && RegVT.getSizeInBits() == 128) {
1862         // Special case: passing MMX values in XMM registers.
1863         Arg = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::i64, Arg);
1864         Arg = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64, Arg);
1865         Arg = getMOVL(DAG, dl, MVT::v2i64, DAG.getUNDEF(MVT::v2i64), Arg);
1866       } else
1867         Arg = DAG.getNode(ISD::ANY_EXTEND, dl, RegVT, Arg);
1868       break;
1869     case CCValAssign::BCvt:
1870       Arg = DAG.getNode(ISD::BIT_CONVERT, dl, RegVT, Arg);
1871       break;
1872     case CCValAssign::Indirect: {
1873       // Store the argument.
1874       SDValue SpillSlot = DAG.CreateStackTemporary(VA.getValVT());
1875       int FI = cast<FrameIndexSDNode>(SpillSlot)->getIndex();
1876       Chain = DAG.getStore(Chain, dl, Arg, SpillSlot,
1877                            PseudoSourceValue::getFixedStack(FI), 0,
1878                            false, false, 0);
1879       Arg = SpillSlot;
1880       break;
1881     }
1882     }
1883
1884     if (VA.isRegLoc()) {
1885       RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
1886     } else if (!IsSibcall && (!isTailCall || isByVal)) {
1887       assert(VA.isMemLoc());
1888       if (StackPtr.getNode() == 0)
1889         StackPtr = DAG.getCopyFromReg(Chain, dl, X86StackPtr, getPointerTy());
1890       MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg,
1891                                              dl, DAG, VA, Flags));
1892     }
1893   }
1894
1895   if (!MemOpChains.empty())
1896     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
1897                         &MemOpChains[0], MemOpChains.size());
1898
1899   // Build a sequence of copy-to-reg nodes chained together with token chain
1900   // and flag operands which copy the outgoing args into registers.
1901   SDValue InFlag;
1902   // Tail call byval lowering might overwrite argument registers so in case of
1903   // tail call optimization the copies to registers are lowered later.
1904   if (!isTailCall)
1905     for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
1906       Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
1907                                RegsToPass[i].second, InFlag);
1908       InFlag = Chain.getValue(1);
1909     }
1910
1911   if (Subtarget->isPICStyleGOT()) {
1912     // ELF / PIC requires GOT in the EBX register before function calls via PLT
1913     // GOT pointer.
1914     if (!isTailCall) {
1915       Chain = DAG.getCopyToReg(Chain, dl, X86::EBX,
1916                                DAG.getNode(X86ISD::GlobalBaseReg,
1917                                            DebugLoc::getUnknownLoc(),
1918                                            getPointerTy()),
1919                                InFlag);
1920       InFlag = Chain.getValue(1);
1921     } else {
1922       // If we are tail calling and generating PIC/GOT style code load the
1923       // address of the callee into ECX. The value in ecx is used as target of
1924       // the tail jump. This is done to circumvent the ebx/callee-saved problem
1925       // for tail calls on PIC/GOT architectures. Normally we would just put the
1926       // address of GOT into ebx and then call target@PLT. But for tail calls
1927       // ebx would be restored (since ebx is callee saved) before jumping to the
1928       // target@PLT.
1929
1930       // Note: The actual moving to ECX is done further down.
1931       GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee);
1932       if (G && !G->getGlobal()->hasHiddenVisibility() &&
1933           !G->getGlobal()->hasProtectedVisibility())
1934         Callee = LowerGlobalAddress(Callee, DAG);
1935       else if (isa<ExternalSymbolSDNode>(Callee))
1936         Callee = LowerExternalSymbol(Callee, DAG);
1937     }
1938   }
1939
1940   if (Is64Bit && isVarArg) {
1941     // From AMD64 ABI document:
1942     // For calls that may call functions that use varargs or stdargs
1943     // (prototype-less calls or calls to functions containing ellipsis (...) in
1944     // the declaration) %al is used as hidden argument to specify the number
1945     // of SSE registers used. The contents of %al do not need to match exactly
1946     // the number of registers, but must be an ubound on the number of SSE
1947     // registers used and is in the range 0 - 8 inclusive.
1948
1949     // FIXME: Verify this on Win64
1950     // Count the number of XMM registers allocated.
1951     static const unsigned XMMArgRegs[] = {
1952       X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
1953       X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
1954     };
1955     unsigned NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs, 8);
1956     assert((Subtarget->hasSSE1() || !NumXMMRegs)
1957            && "SSE registers cannot be used when SSE is disabled");
1958
1959     Chain = DAG.getCopyToReg(Chain, dl, X86::AL,
1960                              DAG.getConstant(NumXMMRegs, MVT::i8), InFlag);
1961     InFlag = Chain.getValue(1);
1962   }
1963
1964
1965   // For tail calls lower the arguments to the 'real' stack slot.
1966   if (isTailCall) {
1967     // Force all the incoming stack arguments to be loaded from the stack
1968     // before any new outgoing arguments are stored to the stack, because the
1969     // outgoing stack slots may alias the incoming argument stack slots, and
1970     // the alias isn't otherwise explicit. This is slightly more conservative
1971     // than necessary, because it means that each store effectively depends
1972     // on every argument instead of just those arguments it would clobber.
1973     SDValue ArgChain = DAG.getStackArgumentTokenFactor(Chain);
1974
1975     SmallVector<SDValue, 8> MemOpChains2;
1976     SDValue FIN;
1977     int FI = 0;
1978     // Do not flag preceeding copytoreg stuff together with the following stuff.
1979     InFlag = SDValue();
1980     if (GuaranteedTailCallOpt) {
1981       for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
1982         CCValAssign &VA = ArgLocs[i];
1983         if (VA.isRegLoc())
1984           continue;
1985         assert(VA.isMemLoc());
1986         SDValue Arg = Outs[i].Val;
1987         ISD::ArgFlagsTy Flags = Outs[i].Flags;
1988         // Create frame index.
1989         int32_t Offset = VA.getLocMemOffset()+FPDiff;
1990         uint32_t OpSize = (VA.getLocVT().getSizeInBits()+7)/8;
1991         FI = MF.getFrameInfo()->CreateFixedObject(OpSize, Offset, true, false);
1992         FIN = DAG.getFrameIndex(FI, getPointerTy());
1993
1994         if (Flags.isByVal()) {
1995           // Copy relative to framepointer.
1996           SDValue Source = DAG.getIntPtrConstant(VA.getLocMemOffset());
1997           if (StackPtr.getNode() == 0)
1998             StackPtr = DAG.getCopyFromReg(Chain, dl, X86StackPtr,
1999                                           getPointerTy());
2000           Source = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, Source);
2001
2002           MemOpChains2.push_back(CreateCopyOfByValArgument(Source, FIN,
2003                                                            ArgChain,
2004                                                            Flags, DAG, dl));
2005         } else {
2006           // Store relative to framepointer.
2007           MemOpChains2.push_back(
2008             DAG.getStore(ArgChain, dl, Arg, FIN,
2009                          PseudoSourceValue::getFixedStack(FI), 0,
2010                          false, false, 0));
2011         }
2012       }
2013     }
2014
2015     if (!MemOpChains2.empty())
2016       Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
2017                           &MemOpChains2[0], MemOpChains2.size());
2018
2019     // Copy arguments to their registers.
2020     for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
2021       Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
2022                                RegsToPass[i].second, InFlag);
2023       InFlag = Chain.getValue(1);
2024     }
2025     InFlag =SDValue();
2026
2027     // Store the return address to the appropriate stack slot.
2028     Chain = EmitTailCallStoreRetAddr(DAG, MF, Chain, RetAddrFrIdx, Is64Bit,
2029                                      FPDiff, dl);
2030   }
2031
2032   bool WasGlobalOrExternal = false;
2033   if (getTargetMachine().getCodeModel() == CodeModel::Large) {
2034     assert(Is64Bit && "Large code model is only legal in 64-bit mode.");
2035     // In the 64-bit large code model, we have to make all calls
2036     // through a register, since the call instruction's 32-bit
2037     // pc-relative offset may not be large enough to hold the whole
2038     // address.
2039   } else if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
2040     WasGlobalOrExternal = true;
2041     // If the callee is a GlobalAddress node (quite common, every direct call
2042     // is) turn it into a TargetGlobalAddress node so that legalize doesn't hack
2043     // it.
2044
2045     // We should use extra load for direct calls to dllimported functions in
2046     // non-JIT mode.
2047     GlobalValue *GV = G->getGlobal();
2048     if (!GV->hasDLLImportLinkage()) {
2049       unsigned char OpFlags = 0;
2050
2051       // On ELF targets, in both X86-64 and X86-32 mode, direct calls to
2052       // external symbols most go through the PLT in PIC mode.  If the symbol
2053       // has hidden or protected visibility, or if it is static or local, then
2054       // we don't need to use the PLT - we can directly call it.
2055       if (Subtarget->isTargetELF() &&
2056           getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
2057           GV->hasDefaultVisibility() && !GV->hasLocalLinkage()) {
2058         OpFlags = X86II::MO_PLT;
2059       } else if (Subtarget->isPICStyleStubAny() &&
2060                (GV->isDeclaration() || GV->isWeakForLinker()) &&
2061                Subtarget->getDarwinVers() < 9) {
2062         // PC-relative references to external symbols should go through $stub,
2063         // unless we're building with the leopard linker or later, which
2064         // automatically synthesizes these stubs.
2065         OpFlags = X86II::MO_DARWIN_STUB;
2066       }
2067
2068       Callee = DAG.getTargetGlobalAddress(GV, getPointerTy(),
2069                                           G->getOffset(), OpFlags);
2070     }
2071   } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
2072     WasGlobalOrExternal = true;
2073     unsigned char OpFlags = 0;
2074
2075     // On ELF targets, in either X86-64 or X86-32 mode, direct calls to external
2076     // symbols should go through the PLT.
2077     if (Subtarget->isTargetELF() &&
2078         getTargetMachine().getRelocationModel() == Reloc::PIC_) {
2079       OpFlags = X86II::MO_PLT;
2080     } else if (Subtarget->isPICStyleStubAny() &&
2081              Subtarget->getDarwinVers() < 9) {
2082       // PC-relative references to external symbols should go through $stub,
2083       // unless we're building with the leopard linker or later, which
2084       // automatically synthesizes these stubs.
2085       OpFlags = X86II::MO_DARWIN_STUB;
2086     }
2087
2088     Callee = DAG.getTargetExternalSymbol(S->getSymbol(), getPointerTy(),
2089                                          OpFlags);
2090   }
2091
2092   // Returns a chain & a flag for retval copy to use.
2093   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Flag);
2094   SmallVector<SDValue, 8> Ops;
2095
2096   if (!IsSibcall && isTailCall) {
2097     Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, true),
2098                            DAG.getIntPtrConstant(0, true), InFlag);
2099     InFlag = Chain.getValue(1);
2100   }
2101
2102   Ops.push_back(Chain);
2103   Ops.push_back(Callee);
2104
2105   if (isTailCall)
2106     Ops.push_back(DAG.getConstant(FPDiff, MVT::i32));
2107
2108   // Add argument registers to the end of the list so that they are known live
2109   // into the call.
2110   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
2111     Ops.push_back(DAG.getRegister(RegsToPass[i].first,
2112                                   RegsToPass[i].second.getValueType()));
2113
2114   // Add an implicit use GOT pointer in EBX.
2115   if (!isTailCall && Subtarget->isPICStyleGOT())
2116     Ops.push_back(DAG.getRegister(X86::EBX, getPointerTy()));
2117
2118   // Add an implicit use of AL for x86 vararg functions.
2119   if (Is64Bit && isVarArg)
2120     Ops.push_back(DAG.getRegister(X86::AL, MVT::i8));
2121
2122   if (InFlag.getNode())
2123     Ops.push_back(InFlag);
2124
2125   if (isTailCall) {
2126     // If this is the first return lowered for this function, add the regs
2127     // to the liveout set for the function.
2128     if (MF.getRegInfo().liveout_empty()) {
2129       SmallVector<CCValAssign, 16> RVLocs;
2130       CCState CCInfo(CallConv, isVarArg, getTargetMachine(), RVLocs,
2131                      *DAG.getContext());
2132       CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
2133       for (unsigned i = 0; i != RVLocs.size(); ++i)
2134         if (RVLocs[i].isRegLoc())
2135           MF.getRegInfo().addLiveOut(RVLocs[i].getLocReg());
2136     }
2137     return DAG.getNode(X86ISD::TC_RETURN, dl,
2138                        NodeTys, &Ops[0], Ops.size());
2139   }
2140
2141   Chain = DAG.getNode(X86ISD::CALL, dl, NodeTys, &Ops[0], Ops.size());
2142   InFlag = Chain.getValue(1);
2143
2144   // Create the CALLSEQ_END node.
2145   unsigned NumBytesForCalleeToPush;
2146   if (IsCalleePop(isVarArg, CallConv))
2147     NumBytesForCalleeToPush = NumBytes;    // Callee pops everything
2148   else if (!Is64Bit && !IsTailCallConvention(CallConv) && IsStructRet)
2149     // If this is a call to a struct-return function, the callee
2150     // pops the hidden struct pointer, so we have to push it back.
2151     // This is common for Darwin/X86, Linux & Mingw32 targets.
2152     NumBytesForCalleeToPush = 4;
2153   else
2154     NumBytesForCalleeToPush = 0;  // Callee pops nothing.
2155
2156   // Returns a flag for retval copy to use.
2157   if (!IsSibcall) {
2158     Chain = DAG.getCALLSEQ_END(Chain,
2159                                DAG.getIntPtrConstant(NumBytes, true),
2160                                DAG.getIntPtrConstant(NumBytesForCalleeToPush,
2161                                                      true),
2162                                InFlag);
2163     InFlag = Chain.getValue(1);
2164   }
2165
2166   // Handle result values, copying them out of physregs into vregs that we
2167   // return.
2168   return LowerCallResult(Chain, InFlag, CallConv, isVarArg,
2169                          Ins, dl, DAG, InVals);
2170 }
2171
2172
2173 //===----------------------------------------------------------------------===//
2174 //                Fast Calling Convention (tail call) implementation
2175 //===----------------------------------------------------------------------===//
2176
2177 //  Like std call, callee cleans arguments, convention except that ECX is
2178 //  reserved for storing the tail called function address. Only 2 registers are
2179 //  free for argument passing (inreg). Tail call optimization is performed
2180 //  provided:
2181 //                * tailcallopt is enabled
2182 //                * caller/callee are fastcc
2183 //  On X86_64 architecture with GOT-style position independent code only local
2184 //  (within module) calls are supported at the moment.
2185 //  To keep the stack aligned according to platform abi the function
2186 //  GetAlignedArgumentStackSize ensures that argument delta is always multiples
2187 //  of stack alignment. (Dynamic linkers need this - darwin's dyld for example)
2188 //  If a tail called function callee has more arguments than the caller the
2189 //  caller needs to make sure that there is room to move the RETADDR to. This is
2190 //  achieved by reserving an area the size of the argument delta right after the
2191 //  original REtADDR, but before the saved framepointer or the spilled registers
2192 //  e.g. caller(arg1, arg2) calls callee(arg1, arg2,arg3,arg4)
2193 //  stack layout:
2194 //    arg1
2195 //    arg2
2196 //    RETADDR
2197 //    [ new RETADDR
2198 //      move area ]
2199 //    (possible EBP)
2200 //    ESI
2201 //    EDI
2202 //    local1 ..
2203
2204 /// GetAlignedArgumentStackSize - Make the stack size align e.g 16n + 12 aligned
2205 /// for a 16 byte align requirement.
2206 unsigned X86TargetLowering::GetAlignedArgumentStackSize(unsigned StackSize,
2207                                                         SelectionDAG& DAG) {
2208   MachineFunction &MF = DAG.getMachineFunction();
2209   const TargetMachine &TM = MF.getTarget();
2210   const TargetFrameInfo &TFI = *TM.getFrameInfo();
2211   unsigned StackAlignment = TFI.getStackAlignment();
2212   uint64_t AlignMask = StackAlignment - 1;
2213   int64_t Offset = StackSize;
2214   uint64_t SlotSize = TD->getPointerSize();
2215   if ( (Offset & AlignMask) <= (StackAlignment - SlotSize) ) {
2216     // Number smaller than 12 so just add the difference.
2217     Offset += ((StackAlignment - SlotSize) - (Offset & AlignMask));
2218   } else {
2219     // Mask out lower bits, add stackalignment once plus the 12 bytes.
2220     Offset = ((~AlignMask) & Offset) + StackAlignment +
2221       (StackAlignment-SlotSize);
2222   }
2223   return Offset;
2224 }
2225
2226 /// MatchingStackOffset - Return true if the given stack call argument is
2227 /// already available in the same position (relatively) of the caller's
2228 /// incoming argument stack.
2229 static
2230 bool MatchingStackOffset(SDValue Arg, unsigned Offset, ISD::ArgFlagsTy Flags,
2231                          MachineFrameInfo *MFI, const MachineRegisterInfo *MRI,
2232                          const X86InstrInfo *TII) {
2233   unsigned Bytes = Arg.getValueType().getSizeInBits() / 8;
2234   int FI = INT_MAX;
2235   if (Arg.getOpcode() == ISD::CopyFromReg) {
2236     unsigned VR = cast<RegisterSDNode>(Arg.getOperand(1))->getReg();
2237     if (!VR || TargetRegisterInfo::isPhysicalRegister(VR))
2238       return false;
2239     MachineInstr *Def = MRI->getVRegDef(VR);
2240     if (!Def)
2241       return false;
2242     if (!Flags.isByVal()) {
2243       if (!TII->isLoadFromStackSlot(Def, FI))
2244         return false;
2245     } else {
2246       unsigned Opcode = Def->getOpcode();
2247       if ((Opcode == X86::LEA32r || Opcode == X86::LEA64r) &&
2248           Def->getOperand(1).isFI()) {
2249         FI = Def->getOperand(1).getIndex();
2250         Bytes = Flags.getByValSize();
2251       } else
2252         return false;
2253     }
2254   } else if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Arg)) {
2255     if (Flags.isByVal())
2256       // ByVal argument is passed in as a pointer but it's now being
2257       // dereferenced. e.g.
2258       // define @foo(%struct.X* %A) {
2259       //   tail call @bar(%struct.X* byval %A)
2260       // }
2261       return false;
2262     SDValue Ptr = Ld->getBasePtr();
2263     FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr);
2264     if (!FINode)
2265       return false;
2266     FI = FINode->getIndex();
2267   } else
2268     return false;
2269
2270   assert(FI != INT_MAX);
2271   if (!MFI->isFixedObjectIndex(FI))
2272     return false;
2273   return Offset == MFI->getObjectOffset(FI) && Bytes == MFI->getObjectSize(FI);
2274 }
2275
2276 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
2277 /// for tail call optimization. Targets which want to do tail call
2278 /// optimization should implement this function.
2279 bool
2280 X86TargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
2281                                                      CallingConv::ID CalleeCC,
2282                                                      bool isVarArg,
2283                                                      bool isCalleeStructRet,
2284                                                      bool isCallerStructRet,
2285                                     const SmallVectorImpl<ISD::OutputArg> &Outs,
2286                                     const SmallVectorImpl<ISD::InputArg> &Ins,
2287                                                      SelectionDAG& DAG) const {
2288   if (!IsTailCallConvention(CalleeCC) &&
2289       CalleeCC != CallingConv::C)
2290     return false;
2291
2292   // If -tailcallopt is specified, make fastcc functions tail-callable.
2293   const Function *CallerF = DAG.getMachineFunction().getFunction();
2294   if (GuaranteedTailCallOpt) {
2295     if (IsTailCallConvention(CalleeCC) &&
2296         CallerF->getCallingConv() == CalleeCC)
2297       return true;
2298     return false;
2299   }
2300
2301   // Look for obvious safe cases to perform tail call optimization that does not
2302   // requite ABI changes. This is what gcc calls sibcall.
2303
2304   // Do not sibcall optimize vararg calls for now.
2305   if (isVarArg)
2306     return false;
2307
2308   // Also avoid sibcall optimization if either caller or callee uses struct
2309   // return semantics.
2310   if (isCalleeStructRet || isCallerStructRet)
2311     return false;
2312
2313   // If the call result is in ST0 / ST1, it needs to be popped off the x87 stack.
2314   // Therefore if it's not used by the call it is not safe to optimize this into
2315   // a sibcall.
2316   bool Unused = false;
2317   for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
2318     if (!Ins[i].Used) {
2319       Unused = true;
2320       break;
2321     }
2322   }
2323   if (Unused) {
2324     SmallVector<CCValAssign, 16> RVLocs;
2325     CCState CCInfo(CalleeCC, false, getTargetMachine(),
2326                    RVLocs, *DAG.getContext());
2327     CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
2328     for (unsigned i = 0; i != RVLocs.size(); ++i) {
2329       CCValAssign &VA = RVLocs[i];
2330       if (VA.getLocReg() == X86::ST0 || VA.getLocReg() == X86::ST1)
2331         return false;
2332     }
2333   }
2334
2335   // If the callee takes no arguments then go on to check the results of the
2336   // call.
2337   if (!Outs.empty()) {
2338     // Check if stack adjustment is needed. For now, do not do this if any
2339     // argument is passed on the stack.
2340     SmallVector<CCValAssign, 16> ArgLocs;
2341     CCState CCInfo(CalleeCC, isVarArg, getTargetMachine(),
2342                    ArgLocs, *DAG.getContext());
2343     CCInfo.AnalyzeCallOperands(Outs, CCAssignFnForNode(CalleeCC));
2344     if (CCInfo.getNextStackOffset()) {
2345       MachineFunction &MF = DAG.getMachineFunction();
2346       if (MF.getInfo<X86MachineFunctionInfo>()->getBytesToPopOnReturn())
2347         return false;
2348       if (Subtarget->isTargetWin64())
2349         // Win64 ABI has additional complications.
2350         return false;
2351
2352       // Check if the arguments are already laid out in the right way as
2353       // the caller's fixed stack objects.
2354       MachineFrameInfo *MFI = MF.getFrameInfo();
2355       const MachineRegisterInfo *MRI = &MF.getRegInfo();
2356       const X86InstrInfo *TII =
2357         ((X86TargetMachine&)getTargetMachine()).getInstrInfo();
2358       for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2359         CCValAssign &VA = ArgLocs[i];
2360         EVT RegVT = VA.getLocVT();
2361         SDValue Arg = Outs[i].Val;
2362         ISD::ArgFlagsTy Flags = Outs[i].Flags;
2363         if (VA.getLocInfo() == CCValAssign::Indirect)
2364           return false;
2365         if (!VA.isRegLoc()) {
2366           if (!MatchingStackOffset(Arg, VA.getLocMemOffset(), Flags,
2367                                    MFI, MRI, TII))
2368             return false;
2369         }
2370       }
2371     }
2372   }
2373
2374   return true;
2375 }
2376
2377 FastISel *
2378 X86TargetLowering::createFastISel(MachineFunction &mf, MachineModuleInfo *mmo,
2379                             DwarfWriter *dw,
2380                             DenseMap<const Value *, unsigned> &vm,
2381                             DenseMap<const BasicBlock*, MachineBasicBlock*> &bm,
2382                             DenseMap<const AllocaInst *, int> &am
2383 #ifndef NDEBUG
2384                           , SmallSet<Instruction*, 8> &cil
2385 #endif
2386                                   ) {
2387   return X86::createFastISel(mf, mmo, dw, vm, bm, am
2388 #ifndef NDEBUG
2389                              , cil
2390 #endif
2391                              );
2392 }
2393
2394
2395 //===----------------------------------------------------------------------===//
2396 //                           Other Lowering Hooks
2397 //===----------------------------------------------------------------------===//
2398
2399
2400 SDValue X86TargetLowering::getReturnAddressFrameIndex(SelectionDAG &DAG) {
2401   MachineFunction &MF = DAG.getMachineFunction();
2402   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
2403   int ReturnAddrIndex = FuncInfo->getRAIndex();
2404
2405   if (ReturnAddrIndex == 0) {
2406     // Set up a frame object for the return address.
2407     uint64_t SlotSize = TD->getPointerSize();
2408     ReturnAddrIndex = MF.getFrameInfo()->CreateFixedObject(SlotSize, -SlotSize,
2409                                                            false, false);
2410     FuncInfo->setRAIndex(ReturnAddrIndex);
2411   }
2412
2413   return DAG.getFrameIndex(ReturnAddrIndex, getPointerTy());
2414 }
2415
2416
2417 bool X86::isOffsetSuitableForCodeModel(int64_t Offset, CodeModel::Model M,
2418                                        bool hasSymbolicDisplacement) {
2419   // Offset should fit into 32 bit immediate field.
2420   if (!isInt32(Offset))
2421     return false;
2422
2423   // If we don't have a symbolic displacement - we don't have any extra
2424   // restrictions.
2425   if (!hasSymbolicDisplacement)
2426     return true;
2427
2428   // FIXME: Some tweaks might be needed for medium code model.
2429   if (M != CodeModel::Small && M != CodeModel::Kernel)
2430     return false;
2431
2432   // For small code model we assume that latest object is 16MB before end of 31
2433   // bits boundary. We may also accept pretty large negative constants knowing
2434   // that all objects are in the positive half of address space.
2435   if (M == CodeModel::Small && Offset < 16*1024*1024)
2436     return true;
2437
2438   // For kernel code model we know that all object resist in the negative half
2439   // of 32bits address space. We may not accept negative offsets, since they may
2440   // be just off and we may accept pretty large positive ones.
2441   if (M == CodeModel::Kernel && Offset > 0)
2442     return true;
2443
2444   return false;
2445 }
2446
2447 /// TranslateX86CC - do a one to one translation of a ISD::CondCode to the X86
2448 /// specific condition code, returning the condition code and the LHS/RHS of the
2449 /// comparison to make.
2450 static unsigned TranslateX86CC(ISD::CondCode SetCCOpcode, bool isFP,
2451                                SDValue &LHS, SDValue &RHS, SelectionDAG &DAG) {
2452   if (!isFP) {
2453     if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) {
2454       if (SetCCOpcode == ISD::SETGT && RHSC->isAllOnesValue()) {
2455         // X > -1   -> X == 0, jump !sign.
2456         RHS = DAG.getConstant(0, RHS.getValueType());
2457         return X86::COND_NS;
2458       } else if (SetCCOpcode == ISD::SETLT && RHSC->isNullValue()) {
2459         // X < 0   -> X == 0, jump on sign.
2460         return X86::COND_S;
2461       } else if (SetCCOpcode == ISD::SETLT && RHSC->getZExtValue() == 1) {
2462         // X < 1   -> X <= 0
2463         RHS = DAG.getConstant(0, RHS.getValueType());
2464         return X86::COND_LE;
2465       }
2466     }
2467
2468     switch (SetCCOpcode) {
2469     default: llvm_unreachable("Invalid integer condition!");
2470     case ISD::SETEQ:  return X86::COND_E;
2471     case ISD::SETGT:  return X86::COND_G;
2472     case ISD::SETGE:  return X86::COND_GE;
2473     case ISD::SETLT:  return X86::COND_L;
2474     case ISD::SETLE:  return X86::COND_LE;
2475     case ISD::SETNE:  return X86::COND_NE;
2476     case ISD::SETULT: return X86::COND_B;
2477     case ISD::SETUGT: return X86::COND_A;
2478     case ISD::SETULE: return X86::COND_BE;
2479     case ISD::SETUGE: return X86::COND_AE;
2480     }
2481   }
2482
2483   // First determine if it is required or is profitable to flip the operands.
2484
2485   // If LHS is a foldable load, but RHS is not, flip the condition.
2486   if ((ISD::isNON_EXTLoad(LHS.getNode()) && LHS.hasOneUse()) &&
2487       !(ISD::isNON_EXTLoad(RHS.getNode()) && RHS.hasOneUse())) {
2488     SetCCOpcode = getSetCCSwappedOperands(SetCCOpcode);
2489     std::swap(LHS, RHS);
2490   }
2491
2492   switch (SetCCOpcode) {
2493   default: break;
2494   case ISD::SETOLT:
2495   case ISD::SETOLE:
2496   case ISD::SETUGT:
2497   case ISD::SETUGE:
2498     std::swap(LHS, RHS);
2499     break;
2500   }
2501
2502   // On a floating point condition, the flags are set as follows:
2503   // ZF  PF  CF   op
2504   //  0 | 0 | 0 | X > Y
2505   //  0 | 0 | 1 | X < Y
2506   //  1 | 0 | 0 | X == Y
2507   //  1 | 1 | 1 | unordered
2508   switch (SetCCOpcode) {
2509   default: llvm_unreachable("Condcode should be pre-legalized away");
2510   case ISD::SETUEQ:
2511   case ISD::SETEQ:   return X86::COND_E;
2512   case ISD::SETOLT:              // flipped
2513   case ISD::SETOGT:
2514   case ISD::SETGT:   return X86::COND_A;
2515   case ISD::SETOLE:              // flipped
2516   case ISD::SETOGE:
2517   case ISD::SETGE:   return X86::COND_AE;
2518   case ISD::SETUGT:              // flipped
2519   case ISD::SETULT:
2520   case ISD::SETLT:   return X86::COND_B;
2521   case ISD::SETUGE:              // flipped
2522   case ISD::SETULE:
2523   case ISD::SETLE:   return X86::COND_BE;
2524   case ISD::SETONE:
2525   case ISD::SETNE:   return X86::COND_NE;
2526   case ISD::SETUO:   return X86::COND_P;
2527   case ISD::SETO:    return X86::COND_NP;
2528   case ISD::SETOEQ:
2529   case ISD::SETUNE:  return X86::COND_INVALID;
2530   }
2531 }
2532
2533 /// hasFPCMov - is there a floating point cmov for the specific X86 condition
2534 /// code. Current x86 isa includes the following FP cmov instructions:
2535 /// fcmovb, fcomvbe, fcomve, fcmovu, fcmovae, fcmova, fcmovne, fcmovnu.
2536 static bool hasFPCMov(unsigned X86CC) {
2537   switch (X86CC) {
2538   default:
2539     return false;
2540   case X86::COND_B:
2541   case X86::COND_BE:
2542   case X86::COND_E:
2543   case X86::COND_P:
2544   case X86::COND_A:
2545   case X86::COND_AE:
2546   case X86::COND_NE:
2547   case X86::COND_NP:
2548     return true;
2549   }
2550 }
2551
2552 /// isFPImmLegal - Returns true if the target can instruction select the
2553 /// specified FP immediate natively. If false, the legalizer will
2554 /// materialize the FP immediate as a load from a constant pool.
2555 bool X86TargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
2556   for (unsigned i = 0, e = LegalFPImmediates.size(); i != e; ++i) {
2557     if (Imm.bitwiseIsEqual(LegalFPImmediates[i]))
2558       return true;
2559   }
2560   return false;
2561 }
2562
2563 /// isUndefOrInRange - Return true if Val is undef or if its value falls within
2564 /// the specified range (L, H].
2565 static bool isUndefOrInRange(int Val, int Low, int Hi) {
2566   return (Val < 0) || (Val >= Low && Val < Hi);
2567 }
2568
2569 /// isUndefOrEqual - Val is either less than zero (undef) or equal to the
2570 /// specified value.
2571 static bool isUndefOrEqual(int Val, int CmpVal) {
2572   if (Val < 0 || Val == CmpVal)
2573     return true;
2574   return false;
2575 }
2576
2577 /// isPSHUFDMask - Return true if the node specifies a shuffle of elements that
2578 /// is suitable for input to PSHUFD or PSHUFW.  That is, it doesn't reference
2579 /// the second operand.
2580 static bool isPSHUFDMask(const SmallVectorImpl<int> &Mask, EVT VT) {
2581   if (VT == MVT::v4f32 || VT == MVT::v4i32 || VT == MVT::v4i16)
2582     return (Mask[0] < 4 && Mask[1] < 4 && Mask[2] < 4 && Mask[3] < 4);
2583   if (VT == MVT::v2f64 || VT == MVT::v2i64)
2584     return (Mask[0] < 2 && Mask[1] < 2);
2585   return false;
2586 }
2587
2588 bool X86::isPSHUFDMask(ShuffleVectorSDNode *N) {
2589   SmallVector<int, 8> M;
2590   N->getMask(M);
2591   return ::isPSHUFDMask(M, N->getValueType(0));
2592 }
2593
2594 /// isPSHUFHWMask - Return true if the node specifies a shuffle of elements that
2595 /// is suitable for input to PSHUFHW.
2596 static bool isPSHUFHWMask(const SmallVectorImpl<int> &Mask, EVT VT) {
2597   if (VT != MVT::v8i16)
2598     return false;
2599
2600   // Lower quadword copied in order or undef.
2601   for (int i = 0; i != 4; ++i)
2602     if (Mask[i] >= 0 && Mask[i] != i)
2603       return false;
2604
2605   // Upper quadword shuffled.
2606   for (int i = 4; i != 8; ++i)
2607     if (Mask[i] >= 0 && (Mask[i] < 4 || Mask[i] > 7))
2608       return false;
2609
2610   return true;
2611 }
2612
2613 bool X86::isPSHUFHWMask(ShuffleVectorSDNode *N) {
2614   SmallVector<int, 8> M;
2615   N->getMask(M);
2616   return ::isPSHUFHWMask(M, N->getValueType(0));
2617 }
2618
2619 /// isPSHUFLWMask - Return true if the node specifies a shuffle of elements that
2620 /// is suitable for input to PSHUFLW.
2621 static bool isPSHUFLWMask(const SmallVectorImpl<int> &Mask, EVT VT) {
2622   if (VT != MVT::v8i16)
2623     return false;
2624
2625   // Upper quadword copied in order.
2626   for (int i = 4; i != 8; ++i)
2627     if (Mask[i] >= 0 && Mask[i] != i)
2628       return false;
2629
2630   // Lower quadword shuffled.
2631   for (int i = 0; i != 4; ++i)
2632     if (Mask[i] >= 4)
2633       return false;
2634
2635   return true;
2636 }
2637
2638 bool X86::isPSHUFLWMask(ShuffleVectorSDNode *N) {
2639   SmallVector<int, 8> M;
2640   N->getMask(M);
2641   return ::isPSHUFLWMask(M, N->getValueType(0));
2642 }
2643
2644 /// isPALIGNRMask - Return true if the node specifies a shuffle of elements that
2645 /// is suitable for input to PALIGNR.
2646 static bool isPALIGNRMask(const SmallVectorImpl<int> &Mask, EVT VT,
2647                           bool hasSSSE3) {
2648   int i, e = VT.getVectorNumElements();
2649   
2650   // Do not handle v2i64 / v2f64 shuffles with palignr.
2651   if (e < 4 || !hasSSSE3)
2652     return false;
2653   
2654   for (i = 0; i != e; ++i)
2655     if (Mask[i] >= 0)
2656       break;
2657   
2658   // All undef, not a palignr.
2659   if (i == e)
2660     return false;
2661
2662   // Determine if it's ok to perform a palignr with only the LHS, since we
2663   // don't have access to the actual shuffle elements to see if RHS is undef.
2664   bool Unary = Mask[i] < (int)e;
2665   bool NeedsUnary = false;
2666
2667   int s = Mask[i] - i;
2668   
2669   // Check the rest of the elements to see if they are consecutive.
2670   for (++i; i != e; ++i) {
2671     int m = Mask[i];
2672     if (m < 0) 
2673       continue;
2674     
2675     Unary = Unary && (m < (int)e);
2676     NeedsUnary = NeedsUnary || (m < s);
2677
2678     if (NeedsUnary && !Unary)
2679       return false;
2680     if (Unary && m != ((s+i) & (e-1)))
2681       return false;
2682     if (!Unary && m != (s+i))
2683       return false;
2684   }
2685   return true;
2686 }
2687
2688 bool X86::isPALIGNRMask(ShuffleVectorSDNode *N) {
2689   SmallVector<int, 8> M;
2690   N->getMask(M);
2691   return ::isPALIGNRMask(M, N->getValueType(0), true);
2692 }
2693
2694 /// isSHUFPMask - Return true if the specified VECTOR_SHUFFLE operand
2695 /// specifies a shuffle of elements that is suitable for input to SHUFP*.
2696 static bool isSHUFPMask(const SmallVectorImpl<int> &Mask, EVT VT) {
2697   int NumElems = VT.getVectorNumElements();
2698   if (NumElems != 2 && NumElems != 4)
2699     return false;
2700
2701   int Half = NumElems / 2;
2702   for (int i = 0; i < Half; ++i)
2703     if (!isUndefOrInRange(Mask[i], 0, NumElems))
2704       return false;
2705   for (int i = Half; i < NumElems; ++i)
2706     if (!isUndefOrInRange(Mask[i], NumElems, NumElems*2))
2707       return false;
2708
2709   return true;
2710 }
2711
2712 bool X86::isSHUFPMask(ShuffleVectorSDNode *N) {
2713   SmallVector<int, 8> M;
2714   N->getMask(M);
2715   return ::isSHUFPMask(M, N->getValueType(0));
2716 }
2717
2718 /// isCommutedSHUFP - Returns true if the shuffle mask is exactly
2719 /// the reverse of what x86 shuffles want. x86 shuffles requires the lower
2720 /// half elements to come from vector 1 (which would equal the dest.) and
2721 /// the upper half to come from vector 2.
2722 static bool isCommutedSHUFPMask(const SmallVectorImpl<int> &Mask, EVT VT) {
2723   int NumElems = VT.getVectorNumElements();
2724
2725   if (NumElems != 2 && NumElems != 4)
2726     return false;
2727
2728   int Half = NumElems / 2;
2729   for (int i = 0; i < Half; ++i)
2730     if (!isUndefOrInRange(Mask[i], NumElems, NumElems*2))
2731       return false;
2732   for (int i = Half; i < NumElems; ++i)
2733     if (!isUndefOrInRange(Mask[i], 0, NumElems))
2734       return false;
2735   return true;
2736 }
2737
2738 static bool isCommutedSHUFP(ShuffleVectorSDNode *N) {
2739   SmallVector<int, 8> M;
2740   N->getMask(M);
2741   return isCommutedSHUFPMask(M, N->getValueType(0));
2742 }
2743
2744 /// isMOVHLPSMask - Return true if the specified VECTOR_SHUFFLE operand
2745 /// specifies a shuffle of elements that is suitable for input to MOVHLPS.
2746 bool X86::isMOVHLPSMask(ShuffleVectorSDNode *N) {
2747   if (N->getValueType(0).getVectorNumElements() != 4)
2748     return false;
2749
2750   // Expect bit0 == 6, bit1 == 7, bit2 == 2, bit3 == 3
2751   return isUndefOrEqual(N->getMaskElt(0), 6) &&
2752          isUndefOrEqual(N->getMaskElt(1), 7) &&
2753          isUndefOrEqual(N->getMaskElt(2), 2) &&
2754          isUndefOrEqual(N->getMaskElt(3), 3);
2755 }
2756
2757 /// isMOVHLPS_v_undef_Mask - Special case of isMOVHLPSMask for canonical form
2758 /// of vector_shuffle v, v, <2, 3, 2, 3>, i.e. vector_shuffle v, undef,
2759 /// <2, 3, 2, 3>
2760 bool X86::isMOVHLPS_v_undef_Mask(ShuffleVectorSDNode *N) {
2761   unsigned NumElems = N->getValueType(0).getVectorNumElements();
2762   
2763   if (NumElems != 4)
2764     return false;
2765   
2766   return isUndefOrEqual(N->getMaskElt(0), 2) &&
2767   isUndefOrEqual(N->getMaskElt(1), 3) &&
2768   isUndefOrEqual(N->getMaskElt(2), 2) &&
2769   isUndefOrEqual(N->getMaskElt(3), 3);
2770 }
2771
2772 /// isMOVLPMask - Return true if the specified VECTOR_SHUFFLE operand
2773 /// specifies a shuffle of elements that is suitable for input to MOVLP{S|D}.
2774 bool X86::isMOVLPMask(ShuffleVectorSDNode *N) {
2775   unsigned NumElems = N->getValueType(0).getVectorNumElements();
2776
2777   if (NumElems != 2 && NumElems != 4)
2778     return false;
2779
2780   for (unsigned i = 0; i < NumElems/2; ++i)
2781     if (!isUndefOrEqual(N->getMaskElt(i), i + NumElems))
2782       return false;
2783
2784   for (unsigned i = NumElems/2; i < NumElems; ++i)
2785     if (!isUndefOrEqual(N->getMaskElt(i), i))
2786       return false;
2787
2788   return true;
2789 }
2790
2791 /// isMOVLHPSMask - Return true if the specified VECTOR_SHUFFLE operand
2792 /// specifies a shuffle of elements that is suitable for input to MOVLHPS.
2793 bool X86::isMOVLHPSMask(ShuffleVectorSDNode *N) {
2794   unsigned NumElems = N->getValueType(0).getVectorNumElements();
2795
2796   if (NumElems != 2 && NumElems != 4)
2797     return false;
2798
2799   for (unsigned i = 0; i < NumElems/2; ++i)
2800     if (!isUndefOrEqual(N->getMaskElt(i), i))
2801       return false;
2802
2803   for (unsigned i = 0; i < NumElems/2; ++i)
2804     if (!isUndefOrEqual(N->getMaskElt(i + NumElems/2), i + NumElems))
2805       return false;
2806
2807   return true;
2808 }
2809
2810 /// isUNPCKLMask - Return true if the specified VECTOR_SHUFFLE operand
2811 /// specifies a shuffle of elements that is suitable for input to UNPCKL.
2812 static bool isUNPCKLMask(const SmallVectorImpl<int> &Mask, EVT VT,
2813                          bool V2IsSplat = false) {
2814   int NumElts = VT.getVectorNumElements();
2815   if (NumElts != 2 && NumElts != 4 && NumElts != 8 && NumElts != 16)
2816     return false;
2817
2818   for (int i = 0, j = 0; i != NumElts; i += 2, ++j) {
2819     int BitI  = Mask[i];
2820     int BitI1 = Mask[i+1];
2821     if (!isUndefOrEqual(BitI, j))
2822       return false;
2823     if (V2IsSplat) {
2824       if (!isUndefOrEqual(BitI1, NumElts))
2825         return false;
2826     } else {
2827       if (!isUndefOrEqual(BitI1, j + NumElts))
2828         return false;
2829     }
2830   }
2831   return true;
2832 }
2833
2834 bool X86::isUNPCKLMask(ShuffleVectorSDNode *N, bool V2IsSplat) {
2835   SmallVector<int, 8> M;
2836   N->getMask(M);
2837   return ::isUNPCKLMask(M, N->getValueType(0), V2IsSplat);
2838 }
2839
2840 /// isUNPCKHMask - Return true if the specified VECTOR_SHUFFLE operand
2841 /// specifies a shuffle of elements that is suitable for input to UNPCKH.
2842 static bool isUNPCKHMask(const SmallVectorImpl<int> &Mask, EVT VT,
2843                          bool V2IsSplat = false) {
2844   int NumElts = VT.getVectorNumElements();
2845   if (NumElts != 2 && NumElts != 4 && NumElts != 8 && NumElts != 16)
2846     return false;
2847
2848   for (int i = 0, j = 0; i != NumElts; i += 2, ++j) {
2849     int BitI  = Mask[i];
2850     int BitI1 = Mask[i+1];
2851     if (!isUndefOrEqual(BitI, j + NumElts/2))
2852       return false;
2853     if (V2IsSplat) {
2854       if (isUndefOrEqual(BitI1, NumElts))
2855         return false;
2856     } else {
2857       if (!isUndefOrEqual(BitI1, j + NumElts/2 + NumElts))
2858         return false;
2859     }
2860   }
2861   return true;
2862 }
2863
2864 bool X86::isUNPCKHMask(ShuffleVectorSDNode *N, bool V2IsSplat) {
2865   SmallVector<int, 8> M;
2866   N->getMask(M);
2867   return ::isUNPCKHMask(M, N->getValueType(0), V2IsSplat);
2868 }
2869
2870 /// isUNPCKL_v_undef_Mask - Special case of isUNPCKLMask for canonical form
2871 /// of vector_shuffle v, v, <0, 4, 1, 5>, i.e. vector_shuffle v, undef,
2872 /// <0, 0, 1, 1>
2873 static bool isUNPCKL_v_undef_Mask(const SmallVectorImpl<int> &Mask, EVT VT) {
2874   int NumElems = VT.getVectorNumElements();
2875   if (NumElems != 2 && NumElems != 4 && NumElems != 8 && NumElems != 16)
2876     return false;
2877
2878   for (int i = 0, j = 0; i != NumElems; i += 2, ++j) {
2879     int BitI  = Mask[i];
2880     int BitI1 = Mask[i+1];
2881     if (!isUndefOrEqual(BitI, j))
2882       return false;
2883     if (!isUndefOrEqual(BitI1, j))
2884       return false;
2885   }
2886   return true;
2887 }
2888
2889 bool X86::isUNPCKL_v_undef_Mask(ShuffleVectorSDNode *N) {
2890   SmallVector<int, 8> M;
2891   N->getMask(M);
2892   return ::isUNPCKL_v_undef_Mask(M, N->getValueType(0));
2893 }
2894
2895 /// isUNPCKH_v_undef_Mask - Special case of isUNPCKHMask for canonical form
2896 /// of vector_shuffle v, v, <2, 6, 3, 7>, i.e. vector_shuffle v, undef,
2897 /// <2, 2, 3, 3>
2898 static bool isUNPCKH_v_undef_Mask(const SmallVectorImpl<int> &Mask, EVT VT) {
2899   int NumElems = VT.getVectorNumElements();
2900   if (NumElems != 2 && NumElems != 4 && NumElems != 8 && NumElems != 16)
2901     return false;
2902
2903   for (int i = 0, j = NumElems / 2; i != NumElems; i += 2, ++j) {
2904     int BitI  = Mask[i];
2905     int BitI1 = Mask[i+1];
2906     if (!isUndefOrEqual(BitI, j))
2907       return false;
2908     if (!isUndefOrEqual(BitI1, j))
2909       return false;
2910   }
2911   return true;
2912 }
2913
2914 bool X86::isUNPCKH_v_undef_Mask(ShuffleVectorSDNode *N) {
2915   SmallVector<int, 8> M;
2916   N->getMask(M);
2917   return ::isUNPCKH_v_undef_Mask(M, N->getValueType(0));
2918 }
2919
2920 /// isMOVLMask - Return true if the specified VECTOR_SHUFFLE operand
2921 /// specifies a shuffle of elements that is suitable for input to MOVSS,
2922 /// MOVSD, and MOVD, i.e. setting the lowest element.
2923 static bool isMOVLMask(const SmallVectorImpl<int> &Mask, EVT VT) {
2924   if (VT.getVectorElementType().getSizeInBits() < 32)
2925     return false;
2926
2927   int NumElts = VT.getVectorNumElements();
2928
2929   if (!isUndefOrEqual(Mask[0], NumElts))
2930     return false;
2931
2932   for (int i = 1; i < NumElts; ++i)
2933     if (!isUndefOrEqual(Mask[i], i))
2934       return false;
2935
2936   return true;
2937 }
2938
2939 bool X86::isMOVLMask(ShuffleVectorSDNode *N) {
2940   SmallVector<int, 8> M;
2941   N->getMask(M);
2942   return ::isMOVLMask(M, N->getValueType(0));
2943 }
2944
2945 /// isCommutedMOVL - Returns true if the shuffle mask is except the reverse
2946 /// of what x86 movss want. X86 movs requires the lowest  element to be lowest
2947 /// element of vector 2 and the other elements to come from vector 1 in order.
2948 static bool isCommutedMOVLMask(const SmallVectorImpl<int> &Mask, EVT VT,
2949                                bool V2IsSplat = false, bool V2IsUndef = false) {
2950   int NumOps = VT.getVectorNumElements();
2951   if (NumOps != 2 && NumOps != 4 && NumOps != 8 && NumOps != 16)
2952     return false;
2953
2954   if (!isUndefOrEqual(Mask[0], 0))
2955     return false;
2956
2957   for (int i = 1; i < NumOps; ++i)
2958     if (!(isUndefOrEqual(Mask[i], i+NumOps) ||
2959           (V2IsUndef && isUndefOrInRange(Mask[i], NumOps, NumOps*2)) ||
2960           (V2IsSplat && isUndefOrEqual(Mask[i], NumOps))))
2961       return false;
2962
2963   return true;
2964 }
2965
2966 static bool isCommutedMOVL(ShuffleVectorSDNode *N, bool V2IsSplat = false,
2967                            bool V2IsUndef = false) {
2968   SmallVector<int, 8> M;
2969   N->getMask(M);
2970   return isCommutedMOVLMask(M, N->getValueType(0), V2IsSplat, V2IsUndef);
2971 }
2972
2973 /// isMOVSHDUPMask - Return true if the specified VECTOR_SHUFFLE operand
2974 /// specifies a shuffle of elements that is suitable for input to MOVSHDUP.
2975 bool X86::isMOVSHDUPMask(ShuffleVectorSDNode *N) {
2976   if (N->getValueType(0).getVectorNumElements() != 4)
2977     return false;
2978
2979   // Expect 1, 1, 3, 3
2980   for (unsigned i = 0; i < 2; ++i) {
2981     int Elt = N->getMaskElt(i);
2982     if (Elt >= 0 && Elt != 1)
2983       return false;
2984   }
2985
2986   bool HasHi = false;
2987   for (unsigned i = 2; i < 4; ++i) {
2988     int Elt = N->getMaskElt(i);
2989     if (Elt >= 0 && Elt != 3)
2990       return false;
2991     if (Elt == 3)
2992       HasHi = true;
2993   }
2994   // Don't use movshdup if it can be done with a shufps.
2995   // FIXME: verify that matching u, u, 3, 3 is what we want.
2996   return HasHi;
2997 }
2998
2999 /// isMOVSLDUPMask - Return true if the specified VECTOR_SHUFFLE operand
3000 /// specifies a shuffle of elements that is suitable for input to MOVSLDUP.
3001 bool X86::isMOVSLDUPMask(ShuffleVectorSDNode *N) {
3002   if (N->getValueType(0).getVectorNumElements() != 4)
3003     return false;
3004
3005   // Expect 0, 0, 2, 2
3006   for (unsigned i = 0; i < 2; ++i)
3007     if (N->getMaskElt(i) > 0)
3008       return false;
3009
3010   bool HasHi = false;
3011   for (unsigned i = 2; i < 4; ++i) {
3012     int Elt = N->getMaskElt(i);
3013     if (Elt >= 0 && Elt != 2)
3014       return false;
3015     if (Elt == 2)
3016       HasHi = true;
3017   }
3018   // Don't use movsldup if it can be done with a shufps.
3019   return HasHi;
3020 }
3021
3022 /// isMOVDDUPMask - Return true if the specified VECTOR_SHUFFLE operand
3023 /// specifies a shuffle of elements that is suitable for input to MOVDDUP.
3024 bool X86::isMOVDDUPMask(ShuffleVectorSDNode *N) {
3025   int e = N->getValueType(0).getVectorNumElements() / 2;
3026
3027   for (int i = 0; i < e; ++i)
3028     if (!isUndefOrEqual(N->getMaskElt(i), i))
3029       return false;
3030   for (int i = 0; i < e; ++i)
3031     if (!isUndefOrEqual(N->getMaskElt(e+i), i))
3032       return false;
3033   return true;
3034 }
3035
3036 /// getShuffleSHUFImmediate - Return the appropriate immediate to shuffle
3037 /// the specified VECTOR_SHUFFLE mask with PSHUF* and SHUFP* instructions.
3038 unsigned X86::getShuffleSHUFImmediate(SDNode *N) {
3039   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
3040   int NumOperands = SVOp->getValueType(0).getVectorNumElements();
3041
3042   unsigned Shift = (NumOperands == 4) ? 2 : 1;
3043   unsigned Mask = 0;
3044   for (int i = 0; i < NumOperands; ++i) {
3045     int Val = SVOp->getMaskElt(NumOperands-i-1);
3046     if (Val < 0) Val = 0;
3047     if (Val >= NumOperands) Val -= NumOperands;
3048     Mask |= Val;
3049     if (i != NumOperands - 1)
3050       Mask <<= Shift;
3051   }
3052   return Mask;
3053 }
3054
3055 /// getShufflePSHUFHWImmediate - Return the appropriate immediate to shuffle
3056 /// the specified VECTOR_SHUFFLE mask with the PSHUFHW instruction.
3057 unsigned X86::getShufflePSHUFHWImmediate(SDNode *N) {
3058   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
3059   unsigned Mask = 0;
3060   // 8 nodes, but we only care about the last 4.
3061   for (unsigned i = 7; i >= 4; --i) {
3062     int Val = SVOp->getMaskElt(i);
3063     if (Val >= 0)
3064       Mask |= (Val - 4);
3065     if (i != 4)
3066       Mask <<= 2;
3067   }
3068   return Mask;
3069 }
3070
3071 /// getShufflePSHUFLWImmediate - Return the appropriate immediate to shuffle
3072 /// the specified VECTOR_SHUFFLE mask with the PSHUFLW instruction.
3073 unsigned X86::getShufflePSHUFLWImmediate(SDNode *N) {
3074   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
3075   unsigned Mask = 0;
3076   // 8 nodes, but we only care about the first 4.
3077   for (int i = 3; i >= 0; --i) {
3078     int Val = SVOp->getMaskElt(i);
3079     if (Val >= 0)
3080       Mask |= Val;
3081     if (i != 0)
3082       Mask <<= 2;
3083   }
3084   return Mask;
3085 }
3086
3087 /// getShufflePALIGNRImmediate - Return the appropriate immediate to shuffle
3088 /// the specified VECTOR_SHUFFLE mask with the PALIGNR instruction.
3089 unsigned X86::getShufflePALIGNRImmediate(SDNode *N) {
3090   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
3091   EVT VVT = N->getValueType(0);
3092   unsigned EltSize = VVT.getVectorElementType().getSizeInBits() >> 3;
3093   int Val = 0;
3094
3095   unsigned i, e;
3096   for (i = 0, e = VVT.getVectorNumElements(); i != e; ++i) {
3097     Val = SVOp->getMaskElt(i);
3098     if (Val >= 0)
3099       break;
3100   }
3101   return (Val - i) * EltSize;
3102 }
3103
3104 /// isZeroNode - Returns true if Elt is a constant zero or a floating point
3105 /// constant +0.0.
3106 bool X86::isZeroNode(SDValue Elt) {
3107   return ((isa<ConstantSDNode>(Elt) &&
3108            cast<ConstantSDNode>(Elt)->getZExtValue() == 0) ||
3109           (isa<ConstantFPSDNode>(Elt) &&
3110            cast<ConstantFPSDNode>(Elt)->getValueAPF().isPosZero()));
3111 }
3112
3113 /// CommuteVectorShuffle - Swap vector_shuffle operands as well as values in
3114 /// their permute mask.
3115 static SDValue CommuteVectorShuffle(ShuffleVectorSDNode *SVOp,
3116                                     SelectionDAG &DAG) {
3117   EVT VT = SVOp->getValueType(0);
3118   unsigned NumElems = VT.getVectorNumElements();
3119   SmallVector<int, 8> MaskVec;
3120
3121   for (unsigned i = 0; i != NumElems; ++i) {
3122     int idx = SVOp->getMaskElt(i);
3123     if (idx < 0)
3124       MaskVec.push_back(idx);
3125     else if (idx < (int)NumElems)
3126       MaskVec.push_back(idx + NumElems);
3127     else
3128       MaskVec.push_back(idx - NumElems);
3129   }
3130   return DAG.getVectorShuffle(VT, SVOp->getDebugLoc(), SVOp->getOperand(1),
3131                               SVOp->getOperand(0), &MaskVec[0]);
3132 }
3133
3134 /// CommuteVectorShuffleMask - Change values in a shuffle permute mask assuming
3135 /// the two vector operands have swapped position.
3136 static void CommuteVectorShuffleMask(SmallVectorImpl<int> &Mask, EVT VT) {
3137   unsigned NumElems = VT.getVectorNumElements();
3138   for (unsigned i = 0; i != NumElems; ++i) {
3139     int idx = Mask[i];
3140     if (idx < 0)
3141       continue;
3142     else if (idx < (int)NumElems)
3143       Mask[i] = idx + NumElems;
3144     else
3145       Mask[i] = idx - NumElems;
3146   }
3147 }
3148
3149 /// ShouldXformToMOVHLPS - Return true if the node should be transformed to
3150 /// match movhlps. The lower half elements should come from upper half of
3151 /// V1 (and in order), and the upper half elements should come from the upper
3152 /// half of V2 (and in order).
3153 static bool ShouldXformToMOVHLPS(ShuffleVectorSDNode *Op) {
3154   if (Op->getValueType(0).getVectorNumElements() != 4)
3155     return false;
3156   for (unsigned i = 0, e = 2; i != e; ++i)
3157     if (!isUndefOrEqual(Op->getMaskElt(i), i+2))
3158       return false;
3159   for (unsigned i = 2; i != 4; ++i)
3160     if (!isUndefOrEqual(Op->getMaskElt(i), i+4))
3161       return false;
3162   return true;
3163 }
3164
3165 /// isScalarLoadToVector - Returns true if the node is a scalar load that
3166 /// is promoted to a vector. It also returns the LoadSDNode by reference if
3167 /// required.
3168 static bool isScalarLoadToVector(SDNode *N, LoadSDNode **LD = NULL) {
3169   if (N->getOpcode() != ISD::SCALAR_TO_VECTOR)
3170     return false;
3171   N = N->getOperand(0).getNode();
3172   if (!ISD::isNON_EXTLoad(N))
3173     return false;
3174   if (LD)
3175     *LD = cast<LoadSDNode>(N);
3176   return true;
3177 }
3178
3179 /// ShouldXformToMOVLP{S|D} - Return true if the node should be transformed to
3180 /// match movlp{s|d}. The lower half elements should come from lower half of
3181 /// V1 (and in order), and the upper half elements should come from the upper
3182 /// half of V2 (and in order). And since V1 will become the source of the
3183 /// MOVLP, it must be either a vector load or a scalar load to vector.
3184 static bool ShouldXformToMOVLP(SDNode *V1, SDNode *V2,
3185                                ShuffleVectorSDNode *Op) {
3186   if (!ISD::isNON_EXTLoad(V1) && !isScalarLoadToVector(V1))
3187     return false;
3188   // Is V2 is a vector load, don't do this transformation. We will try to use
3189   // load folding shufps op.
3190   if (ISD::isNON_EXTLoad(V2))
3191     return false;
3192
3193   unsigned NumElems = Op->getValueType(0).getVectorNumElements();
3194
3195   if (NumElems != 2 && NumElems != 4)
3196     return false;
3197   for (unsigned i = 0, e = NumElems/2; i != e; ++i)
3198     if (!isUndefOrEqual(Op->getMaskElt(i), i))
3199       return false;
3200   for (unsigned i = NumElems/2; i != NumElems; ++i)
3201     if (!isUndefOrEqual(Op->getMaskElt(i), i+NumElems))
3202       return false;
3203   return true;
3204 }
3205
3206 /// isSplatVector - Returns true if N is a BUILD_VECTOR node whose elements are
3207 /// all the same.
3208 static bool isSplatVector(SDNode *N) {
3209   if (N->getOpcode() != ISD::BUILD_VECTOR)
3210     return false;
3211
3212   SDValue SplatValue = N->getOperand(0);
3213   for (unsigned i = 1, e = N->getNumOperands(); i != e; ++i)
3214     if (N->getOperand(i) != SplatValue)
3215       return false;
3216   return true;
3217 }
3218
3219 /// isZeroShuffle - Returns true if N is a VECTOR_SHUFFLE that can be resolved
3220 /// to an zero vector.
3221 /// FIXME: move to dag combiner / method on ShuffleVectorSDNode
3222 static bool isZeroShuffle(ShuffleVectorSDNode *N) {
3223   SDValue V1 = N->getOperand(0);
3224   SDValue V2 = N->getOperand(1);
3225   unsigned NumElems = N->getValueType(0).getVectorNumElements();
3226   for (unsigned i = 0; i != NumElems; ++i) {
3227     int Idx = N->getMaskElt(i);
3228     if (Idx >= (int)NumElems) {
3229       unsigned Opc = V2.getOpcode();
3230       if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V2.getNode()))
3231         continue;
3232       if (Opc != ISD::BUILD_VECTOR ||
3233           !X86::isZeroNode(V2.getOperand(Idx-NumElems)))
3234         return false;
3235     } else if (Idx >= 0) {
3236       unsigned Opc = V1.getOpcode();
3237       if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V1.getNode()))
3238         continue;
3239       if (Opc != ISD::BUILD_VECTOR ||
3240           !X86::isZeroNode(V1.getOperand(Idx)))
3241         return false;
3242     }
3243   }
3244   return true;
3245 }
3246
3247 /// getZeroVector - Returns a vector of specified type with all zero elements.
3248 ///
3249 static SDValue getZeroVector(EVT VT, bool HasSSE2, SelectionDAG &DAG,
3250                              DebugLoc dl) {
3251   assert(VT.isVector() && "Expected a vector type");
3252
3253   // Always build zero vectors as <4 x i32> or <2 x i32> bitcasted to their dest
3254   // type.  This ensures they get CSE'd.
3255   SDValue Vec;
3256   if (VT.getSizeInBits() == 64) { // MMX
3257     SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
3258     Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v2i32, Cst, Cst);
3259   } else if (HasSSE2) {  // SSE2
3260     SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
3261     Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
3262   } else { // SSE1
3263     SDValue Cst = DAG.getTargetConstantFP(+0.0, MVT::f32);
3264     Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4f32, Cst, Cst, Cst, Cst);
3265   }
3266   return DAG.getNode(ISD::BIT_CONVERT, dl, VT, Vec);
3267 }
3268
3269 /// getOnesVector - Returns a vector of specified type with all bits set.
3270 ///
3271 static SDValue getOnesVector(EVT VT, SelectionDAG &DAG, DebugLoc dl) {
3272   assert(VT.isVector() && "Expected a vector type");
3273
3274   // Always build ones vectors as <4 x i32> or <2 x i32> bitcasted to their dest
3275   // type.  This ensures they get CSE'd.
3276   SDValue Cst = DAG.getTargetConstant(~0U, MVT::i32);
3277   SDValue Vec;
3278   if (VT.getSizeInBits() == 64)  // MMX
3279     Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v2i32, Cst, Cst);
3280   else                                              // SSE
3281     Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
3282   return DAG.getNode(ISD::BIT_CONVERT, dl, VT, Vec);
3283 }
3284
3285
3286 /// NormalizeMask - V2 is a splat, modify the mask (if needed) so all elements
3287 /// that point to V2 points to its first element.
3288 static SDValue NormalizeMask(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
3289   EVT VT = SVOp->getValueType(0);
3290   unsigned NumElems = VT.getVectorNumElements();
3291
3292   bool Changed = false;
3293   SmallVector<int, 8> MaskVec;
3294   SVOp->getMask(MaskVec);
3295
3296   for (unsigned i = 0; i != NumElems; ++i) {
3297     if (MaskVec[i] > (int)NumElems) {
3298       MaskVec[i] = NumElems;
3299       Changed = true;
3300     }
3301   }
3302   if (Changed)
3303     return DAG.getVectorShuffle(VT, SVOp->getDebugLoc(), SVOp->getOperand(0),
3304                                 SVOp->getOperand(1), &MaskVec[0]);
3305   return SDValue(SVOp, 0);
3306 }
3307
3308 /// getMOVLMask - Returns a vector_shuffle mask for an movs{s|d}, movd
3309 /// operation of specified width.
3310 static SDValue getMOVL(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
3311                        SDValue V2) {
3312   unsigned NumElems = VT.getVectorNumElements();
3313   SmallVector<int, 8> Mask;
3314   Mask.push_back(NumElems);
3315   for (unsigned i = 1; i != NumElems; ++i)
3316     Mask.push_back(i);
3317   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
3318 }
3319
3320 /// getUnpackl - Returns a vector_shuffle node for an unpackl operation.
3321 static SDValue getUnpackl(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
3322                           SDValue V2) {
3323   unsigned NumElems = VT.getVectorNumElements();
3324   SmallVector<int, 8> Mask;
3325   for (unsigned i = 0, e = NumElems/2; i != e; ++i) {
3326     Mask.push_back(i);
3327     Mask.push_back(i + NumElems);
3328   }
3329   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
3330 }
3331
3332 /// getUnpackhMask - Returns a vector_shuffle node for an unpackh operation.
3333 static SDValue getUnpackh(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
3334                           SDValue V2) {
3335   unsigned NumElems = VT.getVectorNumElements();
3336   unsigned Half = NumElems/2;
3337   SmallVector<int, 8> Mask;
3338   for (unsigned i = 0; i != Half; ++i) {
3339     Mask.push_back(i + Half);
3340     Mask.push_back(i + NumElems + Half);
3341   }
3342   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
3343 }
3344
3345 /// PromoteSplat - Promote a splat of v4f32, v8i16 or v16i8 to v4i32.
3346 static SDValue PromoteSplat(ShuffleVectorSDNode *SV, SelectionDAG &DAG,
3347                             bool HasSSE2) {
3348   if (SV->getValueType(0).getVectorNumElements() <= 4)
3349     return SDValue(SV, 0);
3350
3351   EVT PVT = MVT::v4f32;
3352   EVT VT = SV->getValueType(0);
3353   DebugLoc dl = SV->getDebugLoc();
3354   SDValue V1 = SV->getOperand(0);
3355   int NumElems = VT.getVectorNumElements();
3356   int EltNo = SV->getSplatIndex();
3357
3358   // unpack elements to the correct location
3359   while (NumElems > 4) {
3360     if (EltNo < NumElems/2) {
3361       V1 = getUnpackl(DAG, dl, VT, V1, V1);
3362     } else {
3363       V1 = getUnpackh(DAG, dl, VT, V1, V1);
3364       EltNo -= NumElems/2;
3365     }
3366     NumElems >>= 1;
3367   }
3368
3369   // Perform the splat.
3370   int SplatMask[4] = { EltNo, EltNo, EltNo, EltNo };
3371   V1 = DAG.getNode(ISD::BIT_CONVERT, dl, PVT, V1);
3372   V1 = DAG.getVectorShuffle(PVT, dl, V1, DAG.getUNDEF(PVT), &SplatMask[0]);
3373   return DAG.getNode(ISD::BIT_CONVERT, dl, VT, V1);
3374 }
3375
3376 /// getShuffleVectorZeroOrUndef - Return a vector_shuffle of the specified
3377 /// vector of zero or undef vector.  This produces a shuffle where the low
3378 /// element of V2 is swizzled into the zero/undef vector, landing at element
3379 /// Idx.  This produces a shuffle mask like 4,1,2,3 (idx=0) or  0,1,2,4 (idx=3).
3380 static SDValue getShuffleVectorZeroOrUndef(SDValue V2, unsigned Idx,
3381                                              bool isZero, bool HasSSE2,
3382                                              SelectionDAG &DAG) {
3383   EVT VT = V2.getValueType();
3384   SDValue V1 = isZero
3385     ? getZeroVector(VT, HasSSE2, DAG, V2.getDebugLoc()) : DAG.getUNDEF(VT);
3386   unsigned NumElems = VT.getVectorNumElements();
3387   SmallVector<int, 16> MaskVec;
3388   for (unsigned i = 0; i != NumElems; ++i)
3389     // If this is the insertion idx, put the low elt of V2 here.
3390     MaskVec.push_back(i == Idx ? NumElems : i);
3391   return DAG.getVectorShuffle(VT, V2.getDebugLoc(), V1, V2, &MaskVec[0]);
3392 }
3393
3394 /// getNumOfConsecutiveZeros - Return the number of elements in a result of
3395 /// a shuffle that is zero.
3396 static
3397 unsigned getNumOfConsecutiveZeros(ShuffleVectorSDNode *SVOp, int NumElems,
3398                                   bool Low, SelectionDAG &DAG) {
3399   unsigned NumZeros = 0;
3400   for (int i = 0; i < NumElems; ++i) {
3401     unsigned Index = Low ? i : NumElems-i-1;
3402     int Idx = SVOp->getMaskElt(Index);
3403     if (Idx < 0) {
3404       ++NumZeros;
3405       continue;
3406     }
3407     SDValue Elt = DAG.getShuffleScalarElt(SVOp, Index);
3408     if (Elt.getNode() && X86::isZeroNode(Elt))
3409       ++NumZeros;
3410     else
3411       break;
3412   }
3413   return NumZeros;
3414 }
3415
3416 /// isVectorShift - Returns true if the shuffle can be implemented as a
3417 /// logical left or right shift of a vector.
3418 /// FIXME: split into pslldqi, psrldqi, palignr variants.
3419 static bool isVectorShift(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
3420                           bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
3421   int NumElems = SVOp->getValueType(0).getVectorNumElements();
3422
3423   isLeft = true;
3424   unsigned NumZeros = getNumOfConsecutiveZeros(SVOp, NumElems, true, DAG);
3425   if (!NumZeros) {
3426     isLeft = false;
3427     NumZeros = getNumOfConsecutiveZeros(SVOp, NumElems, false, DAG);
3428     if (!NumZeros)
3429       return false;
3430   }
3431   bool SeenV1 = false;
3432   bool SeenV2 = false;
3433   for (int i = NumZeros; i < NumElems; ++i) {
3434     int Val = isLeft ? (i - NumZeros) : i;
3435     int Idx = SVOp->getMaskElt(isLeft ? i : (i - NumZeros));
3436     if (Idx < 0)
3437       continue;
3438     if (Idx < NumElems)
3439       SeenV1 = true;
3440     else {
3441       Idx -= NumElems;
3442       SeenV2 = true;
3443     }
3444     if (Idx != Val)
3445       return false;
3446   }
3447   if (SeenV1 && SeenV2)
3448     return false;
3449
3450   ShVal = SeenV1 ? SVOp->getOperand(0) : SVOp->getOperand(1);
3451   ShAmt = NumZeros;
3452   return true;
3453 }
3454
3455
3456 /// LowerBuildVectorv16i8 - Custom lower build_vector of v16i8.
3457 ///
3458 static SDValue LowerBuildVectorv16i8(SDValue Op, unsigned NonZeros,
3459                                        unsigned NumNonZero, unsigned NumZero,
3460                                        SelectionDAG &DAG, TargetLowering &TLI) {
3461   if (NumNonZero > 8)
3462     return SDValue();
3463
3464   DebugLoc dl = Op.getDebugLoc();
3465   SDValue V(0, 0);
3466   bool First = true;
3467   for (unsigned i = 0; i < 16; ++i) {
3468     bool ThisIsNonZero = (NonZeros & (1 << i)) != 0;
3469     if (ThisIsNonZero && First) {
3470       if (NumZero)
3471         V = getZeroVector(MVT::v8i16, true, DAG, dl);
3472       else
3473         V = DAG.getUNDEF(MVT::v8i16);
3474       First = false;
3475     }
3476
3477     if ((i & 1) != 0) {
3478       SDValue ThisElt(0, 0), LastElt(0, 0);
3479       bool LastIsNonZero = (NonZeros & (1 << (i-1))) != 0;
3480       if (LastIsNonZero) {
3481         LastElt = DAG.getNode(ISD::ZERO_EXTEND, dl,
3482                               MVT::i16, Op.getOperand(i-1));
3483       }
3484       if (ThisIsNonZero) {
3485         ThisElt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i16, Op.getOperand(i));
3486         ThisElt = DAG.getNode(ISD::SHL, dl, MVT::i16,
3487                               ThisElt, DAG.getConstant(8, MVT::i8));
3488         if (LastIsNonZero)
3489           ThisElt = DAG.getNode(ISD::OR, dl, MVT::i16, ThisElt, LastElt);
3490       } else
3491         ThisElt = LastElt;
3492
3493       if (ThisElt.getNode())
3494         V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, V, ThisElt,
3495                         DAG.getIntPtrConstant(i/2));
3496     }
3497   }
3498
3499   return DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v16i8, V);
3500 }
3501
3502 /// LowerBuildVectorv8i16 - Custom lower build_vector of v8i16.
3503 ///
3504 static SDValue LowerBuildVectorv8i16(SDValue Op, unsigned NonZeros,
3505                                        unsigned NumNonZero, unsigned NumZero,
3506                                        SelectionDAG &DAG, TargetLowering &TLI) {
3507   if (NumNonZero > 4)
3508     return SDValue();
3509
3510   DebugLoc dl = Op.getDebugLoc();
3511   SDValue V(0, 0);
3512   bool First = true;
3513   for (unsigned i = 0; i < 8; ++i) {
3514     bool isNonZero = (NonZeros & (1 << i)) != 0;
3515     if (isNonZero) {
3516       if (First) {
3517         if (NumZero)
3518           V = getZeroVector(MVT::v8i16, true, DAG, dl);
3519         else
3520           V = DAG.getUNDEF(MVT::v8i16);
3521         First = false;
3522       }
3523       V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl,
3524                       MVT::v8i16, V, Op.getOperand(i),
3525                       DAG.getIntPtrConstant(i));
3526     }
3527   }
3528
3529   return V;
3530 }
3531
3532 /// getVShift - Return a vector logical shift node.
3533 ///
3534 static SDValue getVShift(bool isLeft, EVT VT, SDValue SrcOp,
3535                          unsigned NumBits, SelectionDAG &DAG,
3536                          const TargetLowering &TLI, DebugLoc dl) {
3537   bool isMMX = VT.getSizeInBits() == 64;
3538   EVT ShVT = isMMX ? MVT::v1i64 : MVT::v2i64;
3539   unsigned Opc = isLeft ? X86ISD::VSHL : X86ISD::VSRL;
3540   SrcOp = DAG.getNode(ISD::BIT_CONVERT, dl, ShVT, SrcOp);
3541   return DAG.getNode(ISD::BIT_CONVERT, dl, VT,
3542                      DAG.getNode(Opc, dl, ShVT, SrcOp,
3543                              DAG.getConstant(NumBits, TLI.getShiftAmountTy())));
3544 }
3545
3546 SDValue
3547 X86TargetLowering::LowerAsSplatVectorLoad(SDValue SrcOp, EVT VT, DebugLoc dl,
3548                                           SelectionDAG &DAG) {
3549   
3550   // Check if the scalar load can be widened into a vector load. And if
3551   // the address is "base + cst" see if the cst can be "absorbed" into
3552   // the shuffle mask.
3553   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(SrcOp)) {
3554     SDValue Ptr = LD->getBasePtr();
3555     if (!ISD::isNormalLoad(LD) || LD->isVolatile())
3556       return SDValue();
3557     EVT PVT = LD->getValueType(0);
3558     if (PVT != MVT::i32 && PVT != MVT::f32)
3559       return SDValue();
3560
3561     int FI = -1;
3562     int64_t Offset = 0;
3563     if (FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr)) {
3564       FI = FINode->getIndex();
3565       Offset = 0;
3566     } else if (Ptr.getOpcode() == ISD::ADD &&
3567                isa<ConstantSDNode>(Ptr.getOperand(1)) &&
3568                isa<FrameIndexSDNode>(Ptr.getOperand(0))) {
3569       FI = cast<FrameIndexSDNode>(Ptr.getOperand(0))->getIndex();
3570       Offset = Ptr.getConstantOperandVal(1);
3571       Ptr = Ptr.getOperand(0);
3572     } else {
3573       return SDValue();
3574     }
3575
3576     SDValue Chain = LD->getChain();
3577     // Make sure the stack object alignment is at least 16.
3578     MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
3579     if (DAG.InferPtrAlignment(Ptr) < 16) {
3580       if (MFI->isFixedObjectIndex(FI)) {
3581         // Can't change the alignment. FIXME: It's possible to compute
3582         // the exact stack offset and reference FI + adjust offset instead.
3583         // If someone *really* cares about this. That's the way to implement it.
3584         return SDValue();
3585       } else {
3586         MFI->setObjectAlignment(FI, 16);
3587       }
3588     }
3589
3590     // (Offset % 16) must be multiple of 4. Then address is then
3591     // Ptr + (Offset & ~15).
3592     if (Offset < 0)
3593       return SDValue();
3594     if ((Offset % 16) & 3)
3595       return SDValue();
3596     int64_t StartOffset = Offset & ~15;
3597     if (StartOffset)
3598       Ptr = DAG.getNode(ISD::ADD, Ptr.getDebugLoc(), Ptr.getValueType(),
3599                         Ptr,DAG.getConstant(StartOffset, Ptr.getValueType()));
3600
3601     int EltNo = (Offset - StartOffset) >> 2;
3602     int Mask[4] = { EltNo, EltNo, EltNo, EltNo };
3603     EVT VT = (PVT == MVT::i32) ? MVT::v4i32 : MVT::v4f32;
3604     SDValue V1 = DAG.getLoad(VT, dl, Chain, Ptr,LD->getSrcValue(),0,
3605                              false, false, 0);
3606     // Canonicalize it to a v4i32 shuffle.
3607     V1 = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v4i32, V1);
3608     return DAG.getNode(ISD::BIT_CONVERT, dl, VT,
3609                        DAG.getVectorShuffle(MVT::v4i32, dl, V1,
3610                                             DAG.getUNDEF(MVT::v4i32), &Mask[0]));
3611   }
3612
3613   return SDValue();
3614 }
3615
3616 static SDValue EltsFromConsecutiveLoads(EVT VT, SmallVectorImpl<SDValue> &Elts,
3617                                         DebugLoc &dl, SelectionDAG &DAG) {
3618   EVT EltVT = VT.getVectorElementType();
3619   unsigned NumElems = Elts.size();
3620   
3621   // FIXME: check for zeroes
3622   LoadSDNode *LDBase = NULL;
3623   unsigned LastLoadedElt = -1U;
3624   for (unsigned i = 0; i < NumElems; ++i) {
3625     SDValue Elt = Elts[i];
3626     
3627     if (!Elt.getNode() ||
3628         (Elt.getOpcode() != ISD::UNDEF && !ISD::isNON_EXTLoad(Elt.getNode())))
3629       return SDValue();
3630     if (!LDBase) {
3631       if (Elt.getNode()->getOpcode() == ISD::UNDEF)
3632         return SDValue();
3633       LDBase = cast<LoadSDNode>(Elt.getNode());
3634       LastLoadedElt = i;
3635       continue;
3636     }
3637     if (Elt.getOpcode() == ISD::UNDEF)
3638       continue;
3639
3640     LoadSDNode *LD = cast<LoadSDNode>(Elt);
3641     if (!DAG.isConsecutiveLoad(LD, LDBase, EltVT.getSizeInBits()/8, i))
3642       return SDValue();
3643     LastLoadedElt = i;
3644   }
3645                                        
3646   if (LastLoadedElt == NumElems - 1) {
3647     if (DAG.InferPtrAlignment(LDBase->getBasePtr()) >= 16)
3648       return DAG.getLoad(VT, dl, LDBase->getChain(), LDBase->getBasePtr(),
3649                          LDBase->getSrcValue(), LDBase->getSrcValueOffset(),
3650                          LDBase->isVolatile(), LDBase->isNonTemporal(), 0);
3651     return DAG.getLoad(VT, dl, LDBase->getChain(), LDBase->getBasePtr(),
3652                        LDBase->getSrcValue(), LDBase->getSrcValueOffset(),
3653                        LDBase->isVolatile(), LDBase->isNonTemporal(),
3654                        LDBase->getAlignment());
3655   } else if (NumElems == 4 && LastLoadedElt == 1) {
3656     SDVTList Tys = DAG.getVTList(MVT::v2i64, MVT::Other);
3657     SDValue Ops[] = { LDBase->getChain(), LDBase->getBasePtr() };
3658     SDValue ResNode = DAG.getNode(X86ISD::VZEXT_LOAD, dl, Tys, Ops, 2);
3659     return DAG.getNode(ISD::BIT_CONVERT, dl, VT, ResNode);
3660   }
3661   return SDValue();
3662 }
3663
3664 SDValue
3665 X86TargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG) {
3666   DebugLoc dl = Op.getDebugLoc();
3667   // All zero's are handled with pxor, all one's are handled with pcmpeqd.
3668   if (ISD::isBuildVectorAllZeros(Op.getNode())
3669       || ISD::isBuildVectorAllOnes(Op.getNode())) {
3670     // Canonicalize this to either <4 x i32> or <2 x i32> (SSE vs MMX) to
3671     // 1) ensure the zero vectors are CSE'd, and 2) ensure that i64 scalars are
3672     // eliminated on x86-32 hosts.
3673     if (Op.getValueType() == MVT::v4i32 || Op.getValueType() == MVT::v2i32)
3674       return Op;
3675
3676     if (ISD::isBuildVectorAllOnes(Op.getNode()))
3677       return getOnesVector(Op.getValueType(), DAG, dl);
3678     return getZeroVector(Op.getValueType(), Subtarget->hasSSE2(), DAG, dl);
3679   }
3680
3681   EVT VT = Op.getValueType();
3682   EVT ExtVT = VT.getVectorElementType();
3683   unsigned EVTBits = ExtVT.getSizeInBits();
3684
3685   unsigned NumElems = Op.getNumOperands();
3686   unsigned NumZero  = 0;
3687   unsigned NumNonZero = 0;
3688   unsigned NonZeros = 0;
3689   bool IsAllConstants = true;
3690   SmallSet<SDValue, 8> Values;
3691   for (unsigned i = 0; i < NumElems; ++i) {
3692     SDValue Elt = Op.getOperand(i);
3693     if (Elt.getOpcode() == ISD::UNDEF)
3694       continue;
3695     Values.insert(Elt);
3696     if (Elt.getOpcode() != ISD::Constant &&
3697         Elt.getOpcode() != ISD::ConstantFP)
3698       IsAllConstants = false;
3699     if (X86::isZeroNode(Elt))
3700       NumZero++;
3701     else {
3702       NonZeros |= (1 << i);
3703       NumNonZero++;
3704     }
3705   }
3706
3707   if (NumNonZero == 0) {
3708     // All undef vector. Return an UNDEF.  All zero vectors were handled above.
3709     return DAG.getUNDEF(VT);
3710   }
3711
3712   // Special case for single non-zero, non-undef, element.
3713   if (NumNonZero == 1) {
3714     unsigned Idx = CountTrailingZeros_32(NonZeros);
3715     SDValue Item = Op.getOperand(Idx);
3716
3717     // If this is an insertion of an i64 value on x86-32, and if the top bits of
3718     // the value are obviously zero, truncate the value to i32 and do the
3719     // insertion that way.  Only do this if the value is non-constant or if the
3720     // value is a constant being inserted into element 0.  It is cheaper to do
3721     // a constant pool load than it is to do a movd + shuffle.
3722     if (ExtVT == MVT::i64 && !Subtarget->is64Bit() &&
3723         (!IsAllConstants || Idx == 0)) {
3724       if (DAG.MaskedValueIsZero(Item, APInt::getBitsSet(64, 32, 64))) {
3725         // Handle MMX and SSE both.
3726         EVT VecVT = VT == MVT::v2i64 ? MVT::v4i32 : MVT::v2i32;
3727         unsigned VecElts = VT == MVT::v2i64 ? 4 : 2;
3728
3729         // Truncate the value (which may itself be a constant) to i32, and
3730         // convert it to a vector with movd (S2V+shuffle to zero extend).
3731         Item = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Item);
3732         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VecVT, Item);
3733         Item = getShuffleVectorZeroOrUndef(Item, 0, true,
3734                                            Subtarget->hasSSE2(), DAG);
3735
3736         // Now we have our 32-bit value zero extended in the low element of
3737         // a vector.  If Idx != 0, swizzle it into place.
3738         if (Idx != 0) {
3739           SmallVector<int, 4> Mask;
3740           Mask.push_back(Idx);
3741           for (unsigned i = 1; i != VecElts; ++i)
3742             Mask.push_back(i);
3743           Item = DAG.getVectorShuffle(VecVT, dl, Item,
3744                                       DAG.getUNDEF(Item.getValueType()),
3745                                       &Mask[0]);
3746         }
3747         return DAG.getNode(ISD::BIT_CONVERT, dl, Op.getValueType(), Item);
3748       }
3749     }
3750
3751     // If we have a constant or non-constant insertion into the low element of
3752     // a vector, we can do this with SCALAR_TO_VECTOR + shuffle of zero into
3753     // the rest of the elements.  This will be matched as movd/movq/movss/movsd
3754     // depending on what the source datatype is.
3755     if (Idx == 0) {
3756       if (NumZero == 0) {
3757         return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
3758       } else if (ExtVT == MVT::i32 || ExtVT == MVT::f32 || ExtVT == MVT::f64 ||
3759           (ExtVT == MVT::i64 && Subtarget->is64Bit())) {
3760         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
3761         // Turn it into a MOVL (i.e. movss, movsd, or movd) to a zero vector.
3762         return getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget->hasSSE2(),
3763                                            DAG);
3764       } else if (ExtVT == MVT::i16 || ExtVT == MVT::i8) {
3765         Item = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, Item);
3766         EVT MiddleVT = VT.getSizeInBits() == 64 ? MVT::v2i32 : MVT::v4i32;
3767         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MiddleVT, Item);
3768         Item = getShuffleVectorZeroOrUndef(Item, 0, true,
3769                                            Subtarget->hasSSE2(), DAG);
3770         return DAG.getNode(ISD::BIT_CONVERT, dl, VT, Item);
3771       }
3772     }
3773
3774     // Is it a vector logical left shift?
3775     if (NumElems == 2 && Idx == 1 &&
3776         X86::isZeroNode(Op.getOperand(0)) &&
3777         !X86::isZeroNode(Op.getOperand(1))) {
3778       unsigned NumBits = VT.getSizeInBits();
3779       return getVShift(true, VT,
3780                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
3781                                    VT, Op.getOperand(1)),
3782                        NumBits/2, DAG, *this, dl);
3783     }
3784
3785     if (IsAllConstants) // Otherwise, it's better to do a constpool load.
3786       return SDValue();
3787
3788     // Otherwise, if this is a vector with i32 or f32 elements, and the element
3789     // is a non-constant being inserted into an element other than the low one,
3790     // we can't use a constant pool load.  Instead, use SCALAR_TO_VECTOR (aka
3791     // movd/movss) to move this into the low element, then shuffle it into
3792     // place.
3793     if (EVTBits == 32) {
3794       Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
3795
3796       // Turn it into a shuffle of zero and zero-extended scalar to vector.
3797       Item = getShuffleVectorZeroOrUndef(Item, 0, NumZero > 0,
3798                                          Subtarget->hasSSE2(), DAG);
3799       SmallVector<int, 8> MaskVec;
3800       for (unsigned i = 0; i < NumElems; i++)
3801         MaskVec.push_back(i == Idx ? 0 : 1);
3802       return DAG.getVectorShuffle(VT, dl, Item, DAG.getUNDEF(VT), &MaskVec[0]);
3803     }
3804   }
3805
3806   // Splat is obviously ok. Let legalizer expand it to a shuffle.
3807   if (Values.size() == 1) {
3808     if (EVTBits == 32) {
3809       // Instead of a shuffle like this:
3810       // shuffle (scalar_to_vector (load (ptr + 4))), undef, <0, 0, 0, 0>
3811       // Check if it's possible to issue this instead.
3812       // shuffle (vload ptr)), undef, <1, 1, 1, 1>
3813       unsigned Idx = CountTrailingZeros_32(NonZeros);
3814       SDValue Item = Op.getOperand(Idx);
3815       if (Op.getNode()->isOnlyUserOf(Item.getNode()))
3816         return LowerAsSplatVectorLoad(Item, VT, dl, DAG);
3817     }
3818     return SDValue();
3819   }
3820
3821   // A vector full of immediates; various special cases are already
3822   // handled, so this is best done with a single constant-pool load.
3823   if (IsAllConstants)
3824     return SDValue();
3825
3826   // Let legalizer expand 2-wide build_vectors.
3827   if (EVTBits == 64) {
3828     if (NumNonZero == 1) {
3829       // One half is zero or undef.
3830       unsigned Idx = CountTrailingZeros_32(NonZeros);
3831       SDValue V2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT,
3832                                  Op.getOperand(Idx));
3833       return getShuffleVectorZeroOrUndef(V2, Idx, true,
3834                                          Subtarget->hasSSE2(), DAG);
3835     }
3836     return SDValue();
3837   }
3838
3839   // If element VT is < 32 bits, convert it to inserts into a zero vector.
3840   if (EVTBits == 8 && NumElems == 16) {
3841     SDValue V = LowerBuildVectorv16i8(Op, NonZeros,NumNonZero,NumZero, DAG,
3842                                         *this);
3843     if (V.getNode()) return V;
3844   }
3845
3846   if (EVTBits == 16 && NumElems == 8) {
3847     SDValue V = LowerBuildVectorv8i16(Op, NonZeros,NumNonZero,NumZero, DAG,
3848                                         *this);
3849     if (V.getNode()) return V;
3850   }
3851
3852   // If element VT is == 32 bits, turn it into a number of shuffles.
3853   SmallVector<SDValue, 8> V;
3854   V.resize(NumElems);
3855   if (NumElems == 4 && NumZero > 0) {
3856     for (unsigned i = 0; i < 4; ++i) {
3857       bool isZero = !(NonZeros & (1 << i));
3858       if (isZero)
3859         V[i] = getZeroVector(VT, Subtarget->hasSSE2(), DAG, dl);
3860       else
3861         V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
3862     }
3863
3864     for (unsigned i = 0; i < 2; ++i) {
3865       switch ((NonZeros & (0x3 << i*2)) >> (i*2)) {
3866         default: break;
3867         case 0:
3868           V[i] = V[i*2];  // Must be a zero vector.
3869           break;
3870         case 1:
3871           V[i] = getMOVL(DAG, dl, VT, V[i*2+1], V[i*2]);
3872           break;
3873         case 2:
3874           V[i] = getMOVL(DAG, dl, VT, V[i*2], V[i*2+1]);
3875           break;
3876         case 3:
3877           V[i] = getUnpackl(DAG, dl, VT, V[i*2], V[i*2+1]);
3878           break;
3879       }
3880     }
3881
3882     SmallVector<int, 8> MaskVec;
3883     bool Reverse = (NonZeros & 0x3) == 2;
3884     for (unsigned i = 0; i < 2; ++i)
3885       MaskVec.push_back(Reverse ? 1-i : i);
3886     Reverse = ((NonZeros & (0x3 << 2)) >> 2) == 2;
3887     for (unsigned i = 0; i < 2; ++i)
3888       MaskVec.push_back(Reverse ? 1-i+NumElems : i+NumElems);
3889     return DAG.getVectorShuffle(VT, dl, V[0], V[1], &MaskVec[0]);
3890   }
3891
3892   if (Values.size() > 1 && VT.getSizeInBits() == 128) {
3893     // Check for a build vector of consecutive loads.
3894     for (unsigned i = 0; i < NumElems; ++i)
3895       V[i] = Op.getOperand(i);
3896     
3897     // Check for elements which are consecutive loads.
3898     SDValue LD = EltsFromConsecutiveLoads(VT, V, dl, DAG);
3899     if (LD.getNode())
3900       return LD;
3901     
3902     // For SSE 4.1, use inserts into undef.  
3903     if (getSubtarget()->hasSSE41()) {
3904       V[0] = DAG.getUNDEF(VT);
3905       for (unsigned i = 0; i < NumElems; ++i)
3906         if (Op.getOperand(i).getOpcode() != ISD::UNDEF)
3907           V[0] = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, V[0],
3908                              Op.getOperand(i), DAG.getIntPtrConstant(i));
3909       return V[0];
3910     }
3911     
3912     // Otherwise, expand into a number of unpckl*
3913     // e.g. for v4f32
3914     //   Step 1: unpcklps 0, 2 ==> X: <?, ?, 2, 0>
3915     //         : unpcklps 1, 3 ==> Y: <?, ?, 3, 1>
3916     //   Step 2: unpcklps X, Y ==>    <3, 2, 1, 0>
3917     for (unsigned i = 0; i < NumElems; ++i)
3918       V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
3919     NumElems >>= 1;
3920     while (NumElems != 0) {
3921       for (unsigned i = 0; i < NumElems; ++i)
3922         V[i] = getUnpackl(DAG, dl, VT, V[i], V[i + NumElems]);
3923       NumElems >>= 1;
3924     }
3925     return V[0];
3926   }
3927   return SDValue();
3928 }
3929
3930 SDValue
3931 X86TargetLowering::LowerCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
3932   // We support concatenate two MMX registers and place them in a MMX
3933   // register.  This is better than doing a stack convert.
3934   DebugLoc dl = Op.getDebugLoc();
3935   EVT ResVT = Op.getValueType();
3936   assert(Op.getNumOperands() == 2);
3937   assert(ResVT == MVT::v2i64 || ResVT == MVT::v4i32 ||
3938          ResVT == MVT::v8i16 || ResVT == MVT::v16i8);
3939   int Mask[2];
3940   SDValue InVec = DAG.getNode(ISD::BIT_CONVERT,dl, MVT::v1i64, Op.getOperand(0));
3941   SDValue VecOp = DAG.getNode(X86ISD::MOVQ2DQ, dl, MVT::v2i64, InVec);
3942   InVec = Op.getOperand(1);
3943   if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR) {
3944     unsigned NumElts = ResVT.getVectorNumElements();
3945     VecOp = DAG.getNode(ISD::BIT_CONVERT, dl, ResVT, VecOp);
3946     VecOp = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, ResVT, VecOp,
3947                        InVec.getOperand(0), DAG.getIntPtrConstant(NumElts/2+1));
3948   } else {
3949     InVec = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v1i64, InVec);
3950     SDValue VecOp2 = DAG.getNode(X86ISD::MOVQ2DQ, dl, MVT::v2i64, InVec);
3951     Mask[0] = 0; Mask[1] = 2;
3952     VecOp = DAG.getVectorShuffle(MVT::v2i64, dl, VecOp, VecOp2, Mask);
3953   }
3954   return DAG.getNode(ISD::BIT_CONVERT, dl, ResVT, VecOp);
3955 }
3956
3957 // v8i16 shuffles - Prefer shuffles in the following order:
3958 // 1. [all]   pshuflw, pshufhw, optional move
3959 // 2. [ssse3] 1 x pshufb
3960 // 3. [ssse3] 2 x pshufb + 1 x por
3961 // 4. [all]   mov + pshuflw + pshufhw + N x (pextrw + pinsrw)
3962 static
3963 SDValue LowerVECTOR_SHUFFLEv8i16(ShuffleVectorSDNode *SVOp,
3964                                  SelectionDAG &DAG, X86TargetLowering &TLI) {
3965   SDValue V1 = SVOp->getOperand(0);
3966   SDValue V2 = SVOp->getOperand(1);
3967   DebugLoc dl = SVOp->getDebugLoc();
3968   SmallVector<int, 8> MaskVals;
3969
3970   // Determine if more than 1 of the words in each of the low and high quadwords
3971   // of the result come from the same quadword of one of the two inputs.  Undef
3972   // mask values count as coming from any quadword, for better codegen.
3973   SmallVector<unsigned, 4> LoQuad(4);
3974   SmallVector<unsigned, 4> HiQuad(4);
3975   BitVector InputQuads(4);
3976   for (unsigned i = 0; i < 8; ++i) {
3977     SmallVectorImpl<unsigned> &Quad = i < 4 ? LoQuad : HiQuad;
3978     int EltIdx = SVOp->getMaskElt(i);
3979     MaskVals.push_back(EltIdx);
3980     if (EltIdx < 0) {
3981       ++Quad[0];
3982       ++Quad[1];
3983       ++Quad[2];
3984       ++Quad[3];
3985       continue;
3986     }
3987     ++Quad[EltIdx / 4];
3988     InputQuads.set(EltIdx / 4);
3989   }
3990
3991   int BestLoQuad = -1;
3992   unsigned MaxQuad = 1;
3993   for (unsigned i = 0; i < 4; ++i) {
3994     if (LoQuad[i] > MaxQuad) {
3995       BestLoQuad = i;
3996       MaxQuad = LoQuad[i];
3997     }
3998   }
3999
4000   int BestHiQuad = -1;
4001   MaxQuad = 1;
4002   for (unsigned i = 0; i < 4; ++i) {
4003     if (HiQuad[i] > MaxQuad) {
4004       BestHiQuad = i;
4005       MaxQuad = HiQuad[i];
4006     }
4007   }
4008
4009   // For SSSE3, If all 8 words of the result come from only 1 quadword of each
4010   // of the two input vectors, shuffle them into one input vector so only a
4011   // single pshufb instruction is necessary. If There are more than 2 input
4012   // quads, disable the next transformation since it does not help SSSE3.
4013   bool V1Used = InputQuads[0] || InputQuads[1];
4014   bool V2Used = InputQuads[2] || InputQuads[3];
4015   if (TLI.getSubtarget()->hasSSSE3()) {
4016     if (InputQuads.count() == 2 && V1Used && V2Used) {
4017       BestLoQuad = InputQuads.find_first();
4018       BestHiQuad = InputQuads.find_next(BestLoQuad);
4019     }
4020     if (InputQuads.count() > 2) {
4021       BestLoQuad = -1;
4022       BestHiQuad = -1;
4023     }
4024   }
4025
4026   // If BestLoQuad or BestHiQuad are set, shuffle the quads together and update
4027   // the shuffle mask.  If a quad is scored as -1, that means that it contains
4028   // words from all 4 input quadwords.
4029   SDValue NewV;
4030   if (BestLoQuad >= 0 || BestHiQuad >= 0) {
4031     SmallVector<int, 8> MaskV;
4032     MaskV.push_back(BestLoQuad < 0 ? 0 : BestLoQuad);
4033     MaskV.push_back(BestHiQuad < 0 ? 1 : BestHiQuad);
4034     NewV = DAG.getVectorShuffle(MVT::v2i64, dl,
4035                   DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v2i64, V1),
4036                   DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v2i64, V2), &MaskV[0]);
4037     NewV = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v8i16, NewV);
4038
4039     // Rewrite the MaskVals and assign NewV to V1 if NewV now contains all the
4040     // source words for the shuffle, to aid later transformations.
4041     bool AllWordsInNewV = true;
4042     bool InOrder[2] = { true, true };
4043     for (unsigned i = 0; i != 8; ++i) {
4044       int idx = MaskVals[i];
4045       if (idx != (int)i)
4046         InOrder[i/4] = false;
4047       if (idx < 0 || (idx/4) == BestLoQuad || (idx/4) == BestHiQuad)
4048         continue;
4049       AllWordsInNewV = false;
4050       break;
4051     }
4052
4053     bool pshuflw = AllWordsInNewV, pshufhw = AllWordsInNewV;
4054     if (AllWordsInNewV) {
4055       for (int i = 0; i != 8; ++i) {
4056         int idx = MaskVals[i];
4057         if (idx < 0)
4058           continue;
4059         idx = MaskVals[i] = (idx / 4) == BestLoQuad ? (idx & 3) : (idx & 3) + 4;
4060         if ((idx != i) && idx < 4)
4061           pshufhw = false;
4062         if ((idx != i) && idx > 3)
4063           pshuflw = false;
4064       }
4065       V1 = NewV;
4066       V2Used = false;
4067       BestLoQuad = 0;
4068       BestHiQuad = 1;
4069     }
4070
4071     // If we've eliminated the use of V2, and the new mask is a pshuflw or
4072     // pshufhw, that's as cheap as it gets.  Return the new shuffle.
4073     if ((pshufhw && InOrder[0]) || (pshuflw && InOrder[1])) {
4074       return DAG.getVectorShuffle(MVT::v8i16, dl, NewV,
4075                                   DAG.getUNDEF(MVT::v8i16), &MaskVals[0]);
4076     }
4077   }
4078
4079   // If we have SSSE3, and all words of the result are from 1 input vector,
4080   // case 2 is generated, otherwise case 3 is generated.  If no SSSE3
4081   // is present, fall back to case 4.
4082   if (TLI.getSubtarget()->hasSSSE3()) {
4083     SmallVector<SDValue,16> pshufbMask;
4084
4085     // If we have elements from both input vectors, set the high bit of the
4086     // shuffle mask element to zero out elements that come from V2 in the V1
4087     // mask, and elements that come from V1 in the V2 mask, so that the two
4088     // results can be OR'd together.
4089     bool TwoInputs = V1Used && V2Used;
4090     for (unsigned i = 0; i != 8; ++i) {
4091       int EltIdx = MaskVals[i] * 2;
4092       if (TwoInputs && (EltIdx >= 16)) {
4093         pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
4094         pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
4095         continue;
4096       }
4097       pshufbMask.push_back(DAG.getConstant(EltIdx,   MVT::i8));
4098       pshufbMask.push_back(DAG.getConstant(EltIdx+1, MVT::i8));
4099     }
4100     V1 = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v16i8, V1);
4101     V1 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V1,
4102                      DAG.getNode(ISD::BUILD_VECTOR, dl,
4103                                  MVT::v16i8, &pshufbMask[0], 16));
4104     if (!TwoInputs)
4105       return DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v8i16, V1);
4106
4107     // Calculate the shuffle mask for the second input, shuffle it, and
4108     // OR it with the first shuffled input.
4109     pshufbMask.clear();
4110     for (unsigned i = 0; i != 8; ++i) {
4111       int EltIdx = MaskVals[i] * 2;
4112       if (EltIdx < 16) {
4113         pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
4114         pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
4115         continue;
4116       }
4117       pshufbMask.push_back(DAG.getConstant(EltIdx - 16, MVT::i8));
4118       pshufbMask.push_back(DAG.getConstant(EltIdx - 15, MVT::i8));
4119     }
4120     V2 = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v16i8, V2);
4121     V2 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V2,
4122                      DAG.getNode(ISD::BUILD_VECTOR, dl,
4123                                  MVT::v16i8, &pshufbMask[0], 16));
4124     V1 = DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2);
4125     return DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v8i16, V1);
4126   }
4127
4128   // If BestLoQuad >= 0, generate a pshuflw to put the low elements in order,
4129   // and update MaskVals with new element order.
4130   BitVector InOrder(8);
4131   if (BestLoQuad >= 0) {
4132     SmallVector<int, 8> MaskV;
4133     for (int i = 0; i != 4; ++i) {
4134       int idx = MaskVals[i];
4135       if (idx < 0) {
4136         MaskV.push_back(-1);
4137         InOrder.set(i);
4138       } else if ((idx / 4) == BestLoQuad) {
4139         MaskV.push_back(idx & 3);
4140         InOrder.set(i);
4141       } else {
4142         MaskV.push_back(-1);
4143       }
4144     }
4145     for (unsigned i = 4; i != 8; ++i)
4146       MaskV.push_back(i);
4147     NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::v8i16),
4148                                 &MaskV[0]);
4149   }
4150
4151   // If BestHi >= 0, generate a pshufhw to put the high elements in order,
4152   // and update MaskVals with the new element order.
4153   if (BestHiQuad >= 0) {
4154     SmallVector<int, 8> MaskV;
4155     for (unsigned i = 0; i != 4; ++i)
4156       MaskV.push_back(i);
4157     for (unsigned i = 4; i != 8; ++i) {
4158       int idx = MaskVals[i];
4159       if (idx < 0) {
4160         MaskV.push_back(-1);
4161         InOrder.set(i);
4162       } else if ((idx / 4) == BestHiQuad) {
4163         MaskV.push_back((idx & 3) + 4);
4164         InOrder.set(i);
4165       } else {
4166         MaskV.push_back(-1);
4167       }
4168     }
4169     NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::v8i16),
4170                                 &MaskV[0]);
4171   }
4172
4173   // In case BestHi & BestLo were both -1, which means each quadword has a word
4174   // from each of the four input quadwords, calculate the InOrder bitvector now
4175   // before falling through to the insert/extract cleanup.
4176   if (BestLoQuad == -1 && BestHiQuad == -1) {
4177     NewV = V1;
4178     for (int i = 0; i != 8; ++i)
4179       if (MaskVals[i] < 0 || MaskVals[i] == i)
4180         InOrder.set(i);
4181   }
4182
4183   // The other elements are put in the right place using pextrw and pinsrw.
4184   for (unsigned i = 0; i != 8; ++i) {
4185     if (InOrder[i])
4186       continue;
4187     int EltIdx = MaskVals[i];
4188     if (EltIdx < 0)
4189       continue;
4190     SDValue ExtOp = (EltIdx < 8)
4191     ? DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V1,
4192                   DAG.getIntPtrConstant(EltIdx))
4193     : DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V2,
4194                   DAG.getIntPtrConstant(EltIdx - 8));
4195     NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, ExtOp,
4196                        DAG.getIntPtrConstant(i));
4197   }
4198   return NewV;
4199 }
4200
4201 // v16i8 shuffles - Prefer shuffles in the following order:
4202 // 1. [ssse3] 1 x pshufb
4203 // 2. [ssse3] 2 x pshufb + 1 x por
4204 // 3. [all]   v8i16 shuffle + N x pextrw + rotate + pinsrw
4205 static
4206 SDValue LowerVECTOR_SHUFFLEv16i8(ShuffleVectorSDNode *SVOp,
4207                                  SelectionDAG &DAG, X86TargetLowering &TLI) {
4208   SDValue V1 = SVOp->getOperand(0);
4209   SDValue V2 = SVOp->getOperand(1);
4210   DebugLoc dl = SVOp->getDebugLoc();
4211   SmallVector<int, 16> MaskVals;
4212   SVOp->getMask(MaskVals);
4213
4214   // If we have SSSE3, case 1 is generated when all result bytes come from
4215   // one of  the inputs.  Otherwise, case 2 is generated.  If no SSSE3 is
4216   // present, fall back to case 3.
4217   // FIXME: kill V2Only once shuffles are canonizalized by getNode.
4218   bool V1Only = true;
4219   bool V2Only = true;
4220   for (unsigned i = 0; i < 16; ++i) {
4221     int EltIdx = MaskVals[i];
4222     if (EltIdx < 0)
4223       continue;
4224     if (EltIdx < 16)
4225       V2Only = false;
4226     else
4227       V1Only = false;
4228   }
4229
4230   // If SSSE3, use 1 pshufb instruction per vector with elements in the result.
4231   if (TLI.getSubtarget()->hasSSSE3()) {
4232     SmallVector<SDValue,16> pshufbMask;
4233
4234     // If all result elements are from one input vector, then only translate
4235     // undef mask values to 0x80 (zero out result) in the pshufb mask.
4236     //
4237     // Otherwise, we have elements from both input vectors, and must zero out
4238     // elements that come from V2 in the first mask, and V1 in the second mask
4239     // so that we can OR them together.
4240     bool TwoInputs = !(V1Only || V2Only);
4241     for (unsigned i = 0; i != 16; ++i) {
4242       int EltIdx = MaskVals[i];
4243       if (EltIdx < 0 || (TwoInputs && EltIdx >= 16)) {
4244         pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
4245         continue;
4246       }
4247       pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8));
4248     }
4249     // If all the elements are from V2, assign it to V1 and return after
4250     // building the first pshufb.
4251     if (V2Only)
4252       V1 = V2;
4253     V1 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V1,
4254                      DAG.getNode(ISD::BUILD_VECTOR, dl,
4255                                  MVT::v16i8, &pshufbMask[0], 16));
4256     if (!TwoInputs)
4257       return V1;
4258
4259     // Calculate the shuffle mask for the second input, shuffle it, and
4260     // OR it with the first shuffled input.
4261     pshufbMask.clear();
4262     for (unsigned i = 0; i != 16; ++i) {
4263       int EltIdx = MaskVals[i];
4264       if (EltIdx < 16) {
4265         pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
4266         continue;
4267       }
4268       pshufbMask.push_back(DAG.getConstant(EltIdx - 16, MVT::i8));
4269     }
4270     V2 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V2,
4271                      DAG.getNode(ISD::BUILD_VECTOR, dl,
4272                                  MVT::v16i8, &pshufbMask[0], 16));
4273     return DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2);
4274   }
4275
4276   // No SSSE3 - Calculate in place words and then fix all out of place words
4277   // With 0-16 extracts & inserts.  Worst case is 16 bytes out of order from
4278   // the 16 different words that comprise the two doublequadword input vectors.
4279   V1 = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v8i16, V1);
4280   V2 = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v8i16, V2);
4281   SDValue NewV = V2Only ? V2 : V1;
4282   for (int i = 0; i != 8; ++i) {
4283     int Elt0 = MaskVals[i*2];
4284     int Elt1 = MaskVals[i*2+1];
4285
4286     // This word of the result is all undef, skip it.
4287     if (Elt0 < 0 && Elt1 < 0)
4288       continue;
4289
4290     // This word of the result is already in the correct place, skip it.
4291     if (V1Only && (Elt0 == i*2) && (Elt1 == i*2+1))
4292       continue;
4293     if (V2Only && (Elt0 == i*2+16) && (Elt1 == i*2+17))
4294       continue;
4295
4296     SDValue Elt0Src = Elt0 < 16 ? V1 : V2;
4297     SDValue Elt1Src = Elt1 < 16 ? V1 : V2;
4298     SDValue InsElt;
4299
4300     // If Elt0 and Elt1 are defined, are consecutive, and can be load
4301     // using a single extract together, load it and store it.
4302     if ((Elt0 >= 0) && ((Elt0 + 1) == Elt1) && ((Elt0 & 1) == 0)) {
4303       InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src,
4304                            DAG.getIntPtrConstant(Elt1 / 2));
4305       NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt,
4306                         DAG.getIntPtrConstant(i));
4307       continue;
4308     }
4309
4310     // If Elt1 is defined, extract it from the appropriate source.  If the
4311     // source byte is not also odd, shift the extracted word left 8 bits
4312     // otherwise clear the bottom 8 bits if we need to do an or.
4313     if (Elt1 >= 0) {
4314       InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src,
4315                            DAG.getIntPtrConstant(Elt1 / 2));
4316       if ((Elt1 & 1) == 0)
4317         InsElt = DAG.getNode(ISD::SHL, dl, MVT::i16, InsElt,
4318                              DAG.getConstant(8, TLI.getShiftAmountTy()));
4319       else if (Elt0 >= 0)
4320         InsElt = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt,
4321                              DAG.getConstant(0xFF00, MVT::i16));
4322     }
4323     // If Elt0 is defined, extract it from the appropriate source.  If the
4324     // source byte is not also even, shift the extracted word right 8 bits. If
4325     // Elt1 was also defined, OR the extracted values together before
4326     // inserting them in the result.
4327     if (Elt0 >= 0) {
4328       SDValue InsElt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16,
4329                                     Elt0Src, DAG.getIntPtrConstant(Elt0 / 2));
4330       if ((Elt0 & 1) != 0)
4331         InsElt0 = DAG.getNode(ISD::SRL, dl, MVT::i16, InsElt0,
4332                               DAG.getConstant(8, TLI.getShiftAmountTy()));
4333       else if (Elt1 >= 0)
4334         InsElt0 = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt0,
4335                              DAG.getConstant(0x00FF, MVT::i16));
4336       InsElt = Elt1 >= 0 ? DAG.getNode(ISD::OR, dl, MVT::i16, InsElt, InsElt0)
4337                          : InsElt0;
4338     }
4339     NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt,
4340                        DAG.getIntPtrConstant(i));
4341   }
4342   return DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v16i8, NewV);
4343 }
4344
4345 /// RewriteAsNarrowerShuffle - Try rewriting v8i16 and v16i8 shuffles as 4 wide
4346 /// ones, or rewriting v4i32 / v2f32 as 2 wide ones if possible. This can be
4347 /// done when every pair / quad of shuffle mask elements point to elements in
4348 /// the right sequence. e.g.
4349 /// vector_shuffle <>, <>, < 3, 4, | 10, 11, | 0, 1, | 14, 15>
4350 static
4351 SDValue RewriteAsNarrowerShuffle(ShuffleVectorSDNode *SVOp,
4352                                  SelectionDAG &DAG,
4353                                  TargetLowering &TLI, DebugLoc dl) {
4354   EVT VT = SVOp->getValueType(0);
4355   SDValue V1 = SVOp->getOperand(0);
4356   SDValue V2 = SVOp->getOperand(1);
4357   unsigned NumElems = VT.getVectorNumElements();
4358   unsigned NewWidth = (NumElems == 4) ? 2 : 4;
4359   EVT MaskVT = MVT::getIntVectorWithNumElements(NewWidth);
4360   EVT MaskEltVT = MaskVT.getVectorElementType();
4361   EVT NewVT = MaskVT;
4362   switch (VT.getSimpleVT().SimpleTy) {
4363   default: assert(false && "Unexpected!");
4364   case MVT::v4f32: NewVT = MVT::v2f64; break;
4365   case MVT::v4i32: NewVT = MVT::v2i64; break;
4366   case MVT::v8i16: NewVT = MVT::v4i32; break;
4367   case MVT::v16i8: NewVT = MVT::v4i32; break;
4368   }
4369
4370   if (NewWidth == 2) {
4371     if (VT.isInteger())
4372       NewVT = MVT::v2i64;
4373     else
4374       NewVT = MVT::v2f64;
4375   }
4376   int Scale = NumElems / NewWidth;
4377   SmallVector<int, 8> MaskVec;
4378   for (unsigned i = 0; i < NumElems; i += Scale) {
4379     int StartIdx = -1;
4380     for (int j = 0; j < Scale; ++j) {
4381       int EltIdx = SVOp->getMaskElt(i+j);
4382       if (EltIdx < 0)
4383         continue;
4384       if (StartIdx == -1)
4385         StartIdx = EltIdx - (EltIdx % Scale);
4386       if (EltIdx != StartIdx + j)
4387         return SDValue();
4388     }
4389     if (StartIdx == -1)
4390       MaskVec.push_back(-1);
4391     else
4392       MaskVec.push_back(StartIdx / Scale);
4393   }
4394
4395   V1 = DAG.getNode(ISD::BIT_CONVERT, dl, NewVT, V1);
4396   V2 = DAG.getNode(ISD::BIT_CONVERT, dl, NewVT, V2);
4397   return DAG.getVectorShuffle(NewVT, dl, V1, V2, &MaskVec[0]);
4398 }
4399
4400 /// getVZextMovL - Return a zero-extending vector move low node.
4401 ///
4402 static SDValue getVZextMovL(EVT VT, EVT OpVT,
4403                             SDValue SrcOp, SelectionDAG &DAG,
4404                             const X86Subtarget *Subtarget, DebugLoc dl) {
4405   if (VT == MVT::v2f64 || VT == MVT::v4f32) {
4406     LoadSDNode *LD = NULL;
4407     if (!isScalarLoadToVector(SrcOp.getNode(), &LD))
4408       LD = dyn_cast<LoadSDNode>(SrcOp);
4409     if (!LD) {
4410       // movssrr and movsdrr do not clear top bits. Try to use movd, movq
4411       // instead.
4412       MVT ExtVT = (OpVT == MVT::v2f64) ? MVT::i64 : MVT::i32;
4413       if ((ExtVT.SimpleTy != MVT::i64 || Subtarget->is64Bit()) &&
4414           SrcOp.getOpcode() == ISD::SCALAR_TO_VECTOR &&
4415           SrcOp.getOperand(0).getOpcode() == ISD::BIT_CONVERT &&
4416           SrcOp.getOperand(0).getOperand(0).getValueType() == ExtVT) {
4417         // PR2108
4418         OpVT = (OpVT == MVT::v2f64) ? MVT::v2i64 : MVT::v4i32;
4419         return DAG.getNode(ISD::BIT_CONVERT, dl, VT,
4420                            DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT,
4421                                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
4422                                                    OpVT,
4423                                                    SrcOp.getOperand(0)
4424                                                           .getOperand(0))));
4425       }
4426     }
4427   }
4428
4429   return DAG.getNode(ISD::BIT_CONVERT, dl, VT,
4430                      DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT,
4431                                  DAG.getNode(ISD::BIT_CONVERT, dl,
4432                                              OpVT, SrcOp)));
4433 }
4434
4435 /// LowerVECTOR_SHUFFLE_4wide - Handle all 4 wide cases with a number of
4436 /// shuffles.
4437 static SDValue
4438 LowerVECTOR_SHUFFLE_4wide(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
4439   SDValue V1 = SVOp->getOperand(0);
4440   SDValue V2 = SVOp->getOperand(1);
4441   DebugLoc dl = SVOp->getDebugLoc();
4442   EVT VT = SVOp->getValueType(0);
4443
4444   SmallVector<std::pair<int, int>, 8> Locs;
4445   Locs.resize(4);
4446   SmallVector<int, 8> Mask1(4U, -1);
4447   SmallVector<int, 8> PermMask;
4448   SVOp->getMask(PermMask);
4449
4450   unsigned NumHi = 0;
4451   unsigned NumLo = 0;
4452   for (unsigned i = 0; i != 4; ++i) {
4453     int Idx = PermMask[i];
4454     if (Idx < 0) {
4455       Locs[i] = std::make_pair(-1, -1);
4456     } else {
4457       assert(Idx < 8 && "Invalid VECTOR_SHUFFLE index!");
4458       if (Idx < 4) {
4459         Locs[i] = std::make_pair(0, NumLo);
4460         Mask1[NumLo] = Idx;
4461         NumLo++;
4462       } else {
4463         Locs[i] = std::make_pair(1, NumHi);
4464         if (2+NumHi < 4)
4465           Mask1[2+NumHi] = Idx;
4466         NumHi++;
4467       }
4468     }
4469   }
4470
4471   if (NumLo <= 2 && NumHi <= 2) {
4472     // If no more than two elements come from either vector. This can be
4473     // implemented with two shuffles. First shuffle gather the elements.
4474     // The second shuffle, which takes the first shuffle as both of its
4475     // vector operands, put the elements into the right order.
4476     V1 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
4477
4478     SmallVector<int, 8> Mask2(4U, -1);
4479
4480     for (unsigned i = 0; i != 4; ++i) {
4481       if (Locs[i].first == -1)
4482         continue;
4483       else {
4484         unsigned Idx = (i < 2) ? 0 : 4;
4485         Idx += Locs[i].first * 2 + Locs[i].second;
4486         Mask2[i] = Idx;
4487       }
4488     }
4489
4490     return DAG.getVectorShuffle(VT, dl, V1, V1, &Mask2[0]);
4491   } else if (NumLo == 3 || NumHi == 3) {
4492     // Otherwise, we must have three elements from one vector, call it X, and
4493     // one element from the other, call it Y.  First, use a shufps to build an
4494     // intermediate vector with the one element from Y and the element from X
4495     // that will be in the same half in the final destination (the indexes don't
4496     // matter). Then, use a shufps to build the final vector, taking the half
4497     // containing the element from Y from the intermediate, and the other half
4498     // from X.
4499     if (NumHi == 3) {
4500       // Normalize it so the 3 elements come from V1.
4501       CommuteVectorShuffleMask(PermMask, VT);
4502       std::swap(V1, V2);
4503     }
4504
4505     // Find the element from V2.
4506     unsigned HiIndex;
4507     for (HiIndex = 0; HiIndex < 3; ++HiIndex) {
4508       int Val = PermMask[HiIndex];
4509       if (Val < 0)
4510         continue;
4511       if (Val >= 4)
4512         break;
4513     }
4514
4515     Mask1[0] = PermMask[HiIndex];
4516     Mask1[1] = -1;
4517     Mask1[2] = PermMask[HiIndex^1];
4518     Mask1[3] = -1;
4519     V2 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
4520
4521     if (HiIndex >= 2) {
4522       Mask1[0] = PermMask[0];
4523       Mask1[1] = PermMask[1];
4524       Mask1[2] = HiIndex & 1 ? 6 : 4;
4525       Mask1[3] = HiIndex & 1 ? 4 : 6;
4526       return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
4527     } else {
4528       Mask1[0] = HiIndex & 1 ? 2 : 0;
4529       Mask1[1] = HiIndex & 1 ? 0 : 2;
4530       Mask1[2] = PermMask[2];
4531       Mask1[3] = PermMask[3];
4532       if (Mask1[2] >= 0)
4533         Mask1[2] += 4;
4534       if (Mask1[3] >= 0)
4535         Mask1[3] += 4;
4536       return DAG.getVectorShuffle(VT, dl, V2, V1, &Mask1[0]);
4537     }
4538   }
4539
4540   // Break it into (shuffle shuffle_hi, shuffle_lo).
4541   Locs.clear();
4542   SmallVector<int,8> LoMask(4U, -1);
4543   SmallVector<int,8> HiMask(4U, -1);
4544
4545   SmallVector<int,8> *MaskPtr = &LoMask;
4546   unsigned MaskIdx = 0;
4547   unsigned LoIdx = 0;
4548   unsigned HiIdx = 2;
4549   for (unsigned i = 0; i != 4; ++i) {
4550     if (i == 2) {
4551       MaskPtr = &HiMask;
4552       MaskIdx = 1;
4553       LoIdx = 0;
4554       HiIdx = 2;
4555     }
4556     int Idx = PermMask[i];
4557     if (Idx < 0) {
4558       Locs[i] = std::make_pair(-1, -1);
4559     } else if (Idx < 4) {
4560       Locs[i] = std::make_pair(MaskIdx, LoIdx);
4561       (*MaskPtr)[LoIdx] = Idx;
4562       LoIdx++;
4563     } else {
4564       Locs[i] = std::make_pair(MaskIdx, HiIdx);
4565       (*MaskPtr)[HiIdx] = Idx;
4566       HiIdx++;
4567     }
4568   }
4569
4570   SDValue LoShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &LoMask[0]);
4571   SDValue HiShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &HiMask[0]);
4572   SmallVector<int, 8> MaskOps;
4573   for (unsigned i = 0; i != 4; ++i) {
4574     if (Locs[i].first == -1) {
4575       MaskOps.push_back(-1);
4576     } else {
4577       unsigned Idx = Locs[i].first * 4 + Locs[i].second;
4578       MaskOps.push_back(Idx);
4579     }
4580   }
4581   return DAG.getVectorShuffle(VT, dl, LoShuffle, HiShuffle, &MaskOps[0]);
4582 }
4583
4584 SDValue
4585 X86TargetLowering::LowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG) {
4586   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
4587   SDValue V1 = Op.getOperand(0);
4588   SDValue V2 = Op.getOperand(1);
4589   EVT VT = Op.getValueType();
4590   DebugLoc dl = Op.getDebugLoc();
4591   unsigned NumElems = VT.getVectorNumElements();
4592   bool isMMX = VT.getSizeInBits() == 64;
4593   bool V1IsUndef = V1.getOpcode() == ISD::UNDEF;
4594   bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
4595   bool V1IsSplat = false;
4596   bool V2IsSplat = false;
4597
4598   if (isZeroShuffle(SVOp))
4599     return getZeroVector(VT, Subtarget->hasSSE2(), DAG, dl);
4600
4601   // Promote splats to v4f32.
4602   if (SVOp->isSplat()) {
4603     if (isMMX || NumElems < 4)
4604       return Op;
4605     return PromoteSplat(SVOp, DAG, Subtarget->hasSSE2());
4606   }
4607
4608   // If the shuffle can be profitably rewritten as a narrower shuffle, then
4609   // do it!
4610   if (VT == MVT::v8i16 || VT == MVT::v16i8) {
4611     SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG, *this, dl);
4612     if (NewOp.getNode())
4613       return DAG.getNode(ISD::BIT_CONVERT, dl, VT,
4614                          LowerVECTOR_SHUFFLE(NewOp, DAG));
4615   } else if ((VT == MVT::v4i32 || (VT == MVT::v4f32 && Subtarget->hasSSE2()))) {
4616     // FIXME: Figure out a cleaner way to do this.
4617     // Try to make use of movq to zero out the top part.
4618     if (ISD::isBuildVectorAllZeros(V2.getNode())) {
4619       SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG, *this, dl);
4620       if (NewOp.getNode()) {
4621         if (isCommutedMOVL(cast<ShuffleVectorSDNode>(NewOp), true, false))
4622           return getVZextMovL(VT, NewOp.getValueType(), NewOp.getOperand(0),
4623                               DAG, Subtarget, dl);
4624       }
4625     } else if (ISD::isBuildVectorAllZeros(V1.getNode())) {
4626       SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG, *this, dl);
4627       if (NewOp.getNode() && X86::isMOVLMask(cast<ShuffleVectorSDNode>(NewOp)))
4628         return getVZextMovL(VT, NewOp.getValueType(), NewOp.getOperand(1),
4629                             DAG, Subtarget, dl);
4630     }
4631   }
4632
4633   if (X86::isPSHUFDMask(SVOp))
4634     return Op;
4635
4636   // Check if this can be converted into a logical shift.
4637   bool isLeft = false;
4638   unsigned ShAmt = 0;
4639   SDValue ShVal;
4640   bool isShift = getSubtarget()->hasSSE2() &&
4641     isVectorShift(SVOp, DAG, isLeft, ShVal, ShAmt);
4642   if (isShift && ShVal.hasOneUse()) {
4643     // If the shifted value has multiple uses, it may be cheaper to use
4644     // v_set0 + movlhps or movhlps, etc.
4645     EVT EltVT = VT.getVectorElementType();
4646     ShAmt *= EltVT.getSizeInBits();
4647     return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
4648   }
4649
4650   if (X86::isMOVLMask(SVOp)) {
4651     if (V1IsUndef)
4652       return V2;
4653     if (ISD::isBuildVectorAllZeros(V1.getNode()))
4654       return getVZextMovL(VT, VT, V2, DAG, Subtarget, dl);
4655     if (!isMMX)
4656       return Op;
4657   }
4658
4659   // FIXME: fold these into legal mask.
4660   if (!isMMX && (X86::isMOVSHDUPMask(SVOp) ||
4661                  X86::isMOVSLDUPMask(SVOp) ||
4662                  X86::isMOVHLPSMask(SVOp) ||
4663                  X86::isMOVLHPSMask(SVOp) ||
4664                  X86::isMOVLPMask(SVOp)))
4665     return Op;
4666
4667   if (ShouldXformToMOVHLPS(SVOp) ||
4668       ShouldXformToMOVLP(V1.getNode(), V2.getNode(), SVOp))
4669     return CommuteVectorShuffle(SVOp, DAG);
4670
4671   if (isShift) {
4672     // No better options. Use a vshl / vsrl.
4673     EVT EltVT = VT.getVectorElementType();
4674     ShAmt *= EltVT.getSizeInBits();
4675     return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
4676   }
4677
4678   bool Commuted = false;
4679   // FIXME: This should also accept a bitcast of a splat?  Be careful, not
4680   // 1,1,1,1 -> v8i16 though.
4681   V1IsSplat = isSplatVector(V1.getNode());
4682   V2IsSplat = isSplatVector(V2.getNode());
4683
4684   // Canonicalize the splat or undef, if present, to be on the RHS.
4685   if ((V1IsSplat || V1IsUndef) && !(V2IsSplat || V2IsUndef)) {
4686     Op = CommuteVectorShuffle(SVOp, DAG);
4687     SVOp = cast<ShuffleVectorSDNode>(Op);
4688     V1 = SVOp->getOperand(0);
4689     V2 = SVOp->getOperand(1);
4690     std::swap(V1IsSplat, V2IsSplat);
4691     std::swap(V1IsUndef, V2IsUndef);
4692     Commuted = true;
4693   }
4694
4695   if (isCommutedMOVL(SVOp, V2IsSplat, V2IsUndef)) {
4696     // Shuffling low element of v1 into undef, just return v1.
4697     if (V2IsUndef)
4698       return V1;
4699     // If V2 is a splat, the mask may be malformed such as <4,3,3,3>, which
4700     // the instruction selector will not match, so get a canonical MOVL with
4701     // swapped operands to undo the commute.
4702     return getMOVL(DAG, dl, VT, V2, V1);
4703   }
4704
4705   if (X86::isUNPCKL_v_undef_Mask(SVOp) ||
4706       X86::isUNPCKH_v_undef_Mask(SVOp) ||
4707       X86::isUNPCKLMask(SVOp) ||
4708       X86::isUNPCKHMask(SVOp))
4709     return Op;
4710
4711   if (V2IsSplat) {
4712     // Normalize mask so all entries that point to V2 points to its first
4713     // element then try to match unpck{h|l} again. If match, return a
4714     // new vector_shuffle with the corrected mask.
4715     SDValue NewMask = NormalizeMask(SVOp, DAG);
4716     ShuffleVectorSDNode *NSVOp = cast<ShuffleVectorSDNode>(NewMask);
4717     if (NSVOp != SVOp) {
4718       if (X86::isUNPCKLMask(NSVOp, true)) {
4719         return NewMask;
4720       } else if (X86::isUNPCKHMask(NSVOp, true)) {
4721         return NewMask;
4722       }
4723     }
4724   }
4725
4726   if (Commuted) {
4727     // Commute is back and try unpck* again.
4728     // FIXME: this seems wrong.
4729     SDValue NewOp = CommuteVectorShuffle(SVOp, DAG);
4730     ShuffleVectorSDNode *NewSVOp = cast<ShuffleVectorSDNode>(NewOp);
4731     if (X86::isUNPCKL_v_undef_Mask(NewSVOp) ||
4732         X86::isUNPCKH_v_undef_Mask(NewSVOp) ||
4733         X86::isUNPCKLMask(NewSVOp) ||
4734         X86::isUNPCKHMask(NewSVOp))
4735       return NewOp;
4736   }
4737
4738   // FIXME: for mmx, bitcast v2i32 to v4i16 for shuffle.
4739
4740   // Normalize the node to match x86 shuffle ops if needed
4741   if (!isMMX && V2.getOpcode() != ISD::UNDEF && isCommutedSHUFP(SVOp))
4742     return CommuteVectorShuffle(SVOp, DAG);
4743
4744   // Check for legal shuffle and return?
4745   SmallVector<int, 16> PermMask;
4746   SVOp->getMask(PermMask);
4747   if (isShuffleMaskLegal(PermMask, VT))
4748     return Op;
4749
4750   // Handle v8i16 specifically since SSE can do byte extraction and insertion.
4751   if (VT == MVT::v8i16) {
4752     SDValue NewOp = LowerVECTOR_SHUFFLEv8i16(SVOp, DAG, *this);
4753     if (NewOp.getNode())
4754       return NewOp;
4755   }
4756
4757   if (VT == MVT::v16i8) {
4758     SDValue NewOp = LowerVECTOR_SHUFFLEv16i8(SVOp, DAG, *this);
4759     if (NewOp.getNode())
4760       return NewOp;
4761   }
4762
4763   // Handle all 4 wide cases with a number of shuffles except for MMX.
4764   if (NumElems == 4 && !isMMX)
4765     return LowerVECTOR_SHUFFLE_4wide(SVOp, DAG);
4766
4767   return SDValue();
4768 }
4769
4770 SDValue
4771 X86TargetLowering::LowerEXTRACT_VECTOR_ELT_SSE4(SDValue Op,
4772                                                 SelectionDAG &DAG) {
4773   EVT VT = Op.getValueType();
4774   DebugLoc dl = Op.getDebugLoc();
4775   if (VT.getSizeInBits() == 8) {
4776     SDValue Extract = DAG.getNode(X86ISD::PEXTRB, dl, MVT::i32,
4777                                     Op.getOperand(0), Op.getOperand(1));
4778     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
4779                                     DAG.getValueType(VT));
4780     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
4781   } else if (VT.getSizeInBits() == 16) {
4782     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
4783     // If Idx is 0, it's cheaper to do a move instead of a pextrw.
4784     if (Idx == 0)
4785       return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
4786                          DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
4787                                      DAG.getNode(ISD::BIT_CONVERT, dl,
4788                                                  MVT::v4i32,
4789                                                  Op.getOperand(0)),
4790                                      Op.getOperand(1)));
4791     SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, MVT::i32,
4792                                     Op.getOperand(0), Op.getOperand(1));
4793     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
4794                                     DAG.getValueType(VT));
4795     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
4796   } else if (VT == MVT::f32) {
4797     // EXTRACTPS outputs to a GPR32 register which will require a movd to copy
4798     // the result back to FR32 register. It's only worth matching if the
4799     // result has a single use which is a store or a bitcast to i32.  And in
4800     // the case of a store, it's not worth it if the index is a constant 0,
4801     // because a MOVSSmr can be used instead, which is smaller and faster.
4802     if (!Op.hasOneUse())
4803       return SDValue();
4804     SDNode *User = *Op.getNode()->use_begin();
4805     if ((User->getOpcode() != ISD::STORE ||
4806          (isa<ConstantSDNode>(Op.getOperand(1)) &&
4807           cast<ConstantSDNode>(Op.getOperand(1))->isNullValue())) &&
4808         (User->getOpcode() != ISD::BIT_CONVERT ||
4809          User->getValueType(0) != MVT::i32))
4810       return SDValue();
4811     SDValue Extract = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
4812                                   DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v4i32,
4813                                               Op.getOperand(0)),
4814                                               Op.getOperand(1));
4815     return DAG.getNode(ISD::BIT_CONVERT, dl, MVT::f32, Extract);
4816   } else if (VT == MVT::i32) {
4817     // ExtractPS works with constant index.
4818     if (isa<ConstantSDNode>(Op.getOperand(1)))
4819       return Op;
4820   }
4821   return SDValue();
4822 }
4823
4824
4825 SDValue
4826 X86TargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) {
4827   if (!isa<ConstantSDNode>(Op.getOperand(1)))
4828     return SDValue();
4829
4830   if (Subtarget->hasSSE41()) {
4831     SDValue Res = LowerEXTRACT_VECTOR_ELT_SSE4(Op, DAG);
4832     if (Res.getNode())
4833       return Res;
4834   }
4835
4836   EVT VT = Op.getValueType();
4837   DebugLoc dl = Op.getDebugLoc();
4838   // TODO: handle v16i8.
4839   if (VT.getSizeInBits() == 16) {
4840     SDValue Vec = Op.getOperand(0);
4841     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
4842     if (Idx == 0)
4843       return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
4844                          DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
4845                                      DAG.getNode(ISD::BIT_CONVERT, dl,
4846                                                  MVT::v4i32, Vec),
4847                                      Op.getOperand(1)));
4848     // Transform it so it match pextrw which produces a 32-bit result.
4849     EVT EltVT = MVT::i32;
4850     SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, EltVT,
4851                                     Op.getOperand(0), Op.getOperand(1));
4852     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, EltVT, Extract,
4853                                     DAG.getValueType(VT));
4854     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
4855   } else if (VT.getSizeInBits() == 32) {
4856     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
4857     if (Idx == 0)
4858       return Op;
4859
4860     // SHUFPS the element to the lowest double word, then movss.
4861     int Mask[4] = { Idx, -1, -1, -1 };
4862     EVT VVT = Op.getOperand(0).getValueType();
4863     SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
4864                                        DAG.getUNDEF(VVT), Mask);
4865     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
4866                        DAG.getIntPtrConstant(0));
4867   } else if (VT.getSizeInBits() == 64) {
4868     // FIXME: .td only matches this for <2 x f64>, not <2 x i64> on 32b
4869     // FIXME: seems like this should be unnecessary if mov{h,l}pd were taught
4870     //        to match extract_elt for f64.
4871     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
4872     if (Idx == 0)
4873       return Op;
4874
4875     // UNPCKHPD the element to the lowest double word, then movsd.
4876     // Note if the lower 64 bits of the result of the UNPCKHPD is then stored
4877     // to a f64mem, the whole operation is folded into a single MOVHPDmr.
4878     int Mask[2] = { 1, -1 };
4879     EVT VVT = Op.getOperand(0).getValueType();
4880     SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
4881                                        DAG.getUNDEF(VVT), Mask);
4882     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
4883                        DAG.getIntPtrConstant(0));
4884   }
4885
4886   return SDValue();
4887 }
4888
4889 SDValue
4890 X86TargetLowering::LowerINSERT_VECTOR_ELT_SSE4(SDValue Op, SelectionDAG &DAG){
4891   EVT VT = Op.getValueType();
4892   EVT EltVT = VT.getVectorElementType();
4893   DebugLoc dl = Op.getDebugLoc();
4894
4895   SDValue N0 = Op.getOperand(0);
4896   SDValue N1 = Op.getOperand(1);
4897   SDValue N2 = Op.getOperand(2);
4898
4899   if ((EltVT.getSizeInBits() == 8 || EltVT.getSizeInBits() == 16) &&
4900       isa<ConstantSDNode>(N2)) {
4901     unsigned Opc;
4902     if (VT == MVT::v8i16)
4903       Opc = X86ISD::PINSRW;
4904     else if (VT == MVT::v4i16)
4905       Opc = X86ISD::MMX_PINSRW;
4906     else if (VT == MVT::v16i8)
4907       Opc = X86ISD::PINSRB;
4908     else
4909       Opc = X86ISD::PINSRB;
4910
4911     // Transform it so it match pinsr{b,w} which expects a GR32 as its second
4912     // argument.
4913     if (N1.getValueType() != MVT::i32)
4914       N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
4915     if (N2.getValueType() != MVT::i32)
4916       N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue());
4917     return DAG.getNode(Opc, dl, VT, N0, N1, N2);
4918   } else if (EltVT == MVT::f32 && isa<ConstantSDNode>(N2)) {
4919     // Bits [7:6] of the constant are the source select.  This will always be
4920     //  zero here.  The DAG Combiner may combine an extract_elt index into these
4921     //  bits.  For example (insert (extract, 3), 2) could be matched by putting
4922     //  the '3' into bits [7:6] of X86ISD::INSERTPS.
4923     // Bits [5:4] of the constant are the destination select.  This is the
4924     //  value of the incoming immediate.
4925     // Bits [3:0] of the constant are the zero mask.  The DAG Combiner may
4926     //   combine either bitwise AND or insert of float 0.0 to set these bits.
4927     N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue() << 4);
4928     // Create this as a scalar to vector..
4929     N1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4f32, N1);
4930     return DAG.getNode(X86ISD::INSERTPS, dl, VT, N0, N1, N2);
4931   } else if (EltVT == MVT::i32 && isa<ConstantSDNode>(N2)) {
4932     // PINSR* works with constant index.
4933     return Op;
4934   }
4935   return SDValue();
4936 }
4937
4938 SDValue
4939 X86TargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) {
4940   EVT VT = Op.getValueType();
4941   EVT EltVT = VT.getVectorElementType();
4942
4943   if (Subtarget->hasSSE41())
4944     return LowerINSERT_VECTOR_ELT_SSE4(Op, DAG);
4945
4946   if (EltVT == MVT::i8)
4947     return SDValue();
4948
4949   DebugLoc dl = Op.getDebugLoc();
4950   SDValue N0 = Op.getOperand(0);
4951   SDValue N1 = Op.getOperand(1);
4952   SDValue N2 = Op.getOperand(2);
4953
4954   if (EltVT.getSizeInBits() == 16 && isa<ConstantSDNode>(N2)) {
4955     // Transform it so it match pinsrw which expects a 16-bit value in a GR32
4956     // as its second argument.
4957     if (N1.getValueType() != MVT::i32)
4958       N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
4959     if (N2.getValueType() != MVT::i32)
4960       N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue());
4961     return DAG.getNode(VT == MVT::v8i16 ? X86ISD::PINSRW : X86ISD::MMX_PINSRW,
4962                        dl, VT, N0, N1, N2);
4963   }
4964   return SDValue();
4965 }
4966
4967 SDValue
4968 X86TargetLowering::LowerSCALAR_TO_VECTOR(SDValue Op, SelectionDAG &DAG) {
4969   DebugLoc dl = Op.getDebugLoc();
4970   if (Op.getValueType() == MVT::v2f32)
4971     return DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v2f32,
4972                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i32,
4973                                    DAG.getNode(ISD::BIT_CONVERT, dl, MVT::i32,
4974                                                Op.getOperand(0))));
4975
4976   if (Op.getValueType() == MVT::v1i64 && Op.getOperand(0).getValueType() == MVT::i64)
4977     return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v1i64, Op.getOperand(0));
4978
4979   SDValue AnyExt = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, Op.getOperand(0));
4980   EVT VT = MVT::v2i32;
4981   switch (Op.getValueType().getSimpleVT().SimpleTy) {
4982   default: break;
4983   case MVT::v16i8:
4984   case MVT::v8i16:
4985     VT = MVT::v4i32;
4986     break;
4987   }
4988   return DAG.getNode(ISD::BIT_CONVERT, dl, Op.getValueType(),
4989                      DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, AnyExt));
4990 }
4991
4992 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
4993 // their target countpart wrapped in the X86ISD::Wrapper node. Suppose N is
4994 // one of the above mentioned nodes. It has to be wrapped because otherwise
4995 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
4996 // be used to form addressing mode. These wrapped nodes will be selected
4997 // into MOV32ri.
4998 SDValue
4999 X86TargetLowering::LowerConstantPool(SDValue Op, SelectionDAG &DAG) {
5000   ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
5001
5002   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
5003   // global base reg.
5004   unsigned char OpFlag = 0;
5005   unsigned WrapperKind = X86ISD::Wrapper;
5006   CodeModel::Model M = getTargetMachine().getCodeModel();
5007
5008   if (Subtarget->isPICStyleRIPRel() &&
5009       (M == CodeModel::Small || M == CodeModel::Kernel))
5010     WrapperKind = X86ISD::WrapperRIP;
5011   else if (Subtarget->isPICStyleGOT())
5012     OpFlag = X86II::MO_GOTOFF;
5013   else if (Subtarget->isPICStyleStubPIC())
5014     OpFlag = X86II::MO_PIC_BASE_OFFSET;
5015
5016   SDValue Result = DAG.getTargetConstantPool(CP->getConstVal(), getPointerTy(),
5017                                              CP->getAlignment(),
5018                                              CP->getOffset(), OpFlag);
5019   DebugLoc DL = CP->getDebugLoc();
5020   Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
5021   // With PIC, the address is actually $g + Offset.
5022   if (OpFlag) {
5023     Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
5024                          DAG.getNode(X86ISD::GlobalBaseReg,
5025                                      DebugLoc::getUnknownLoc(), getPointerTy()),
5026                          Result);
5027   }
5028
5029   return Result;
5030 }
5031
5032 SDValue X86TargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) {
5033   JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
5034
5035   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
5036   // global base reg.
5037   unsigned char OpFlag = 0;
5038   unsigned WrapperKind = X86ISD::Wrapper;
5039   CodeModel::Model M = getTargetMachine().getCodeModel();
5040
5041   if (Subtarget->isPICStyleRIPRel() &&
5042       (M == CodeModel::Small || M == CodeModel::Kernel))
5043     WrapperKind = X86ISD::WrapperRIP;
5044   else if (Subtarget->isPICStyleGOT())
5045     OpFlag = X86II::MO_GOTOFF;
5046   else if (Subtarget->isPICStyleStubPIC())
5047     OpFlag = X86II::MO_PIC_BASE_OFFSET;
5048
5049   SDValue Result = DAG.getTargetJumpTable(JT->getIndex(), getPointerTy(),
5050                                           OpFlag);
5051   DebugLoc DL = JT->getDebugLoc();
5052   Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
5053
5054   // With PIC, the address is actually $g + Offset.
5055   if (OpFlag) {
5056     Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
5057                          DAG.getNode(X86ISD::GlobalBaseReg,
5058                                      DebugLoc::getUnknownLoc(), getPointerTy()),
5059                          Result);
5060   }
5061
5062   return Result;
5063 }
5064
5065 SDValue
5066 X86TargetLowering::LowerExternalSymbol(SDValue Op, SelectionDAG &DAG) {
5067   const char *Sym = cast<ExternalSymbolSDNode>(Op)->getSymbol();
5068
5069   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
5070   // global base reg.
5071   unsigned char OpFlag = 0;
5072   unsigned WrapperKind = X86ISD::Wrapper;
5073   CodeModel::Model M = getTargetMachine().getCodeModel();
5074
5075   if (Subtarget->isPICStyleRIPRel() &&
5076       (M == CodeModel::Small || M == CodeModel::Kernel))
5077     WrapperKind = X86ISD::WrapperRIP;
5078   else if (Subtarget->isPICStyleGOT())
5079     OpFlag = X86II::MO_GOTOFF;
5080   else if (Subtarget->isPICStyleStubPIC())
5081     OpFlag = X86II::MO_PIC_BASE_OFFSET;
5082
5083   SDValue Result = DAG.getTargetExternalSymbol(Sym, getPointerTy(), OpFlag);
5084
5085   DebugLoc DL = Op.getDebugLoc();
5086   Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
5087
5088
5089   // With PIC, the address is actually $g + Offset.
5090   if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
5091       !Subtarget->is64Bit()) {
5092     Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
5093                          DAG.getNode(X86ISD::GlobalBaseReg,
5094                                      DebugLoc::getUnknownLoc(),
5095                                      getPointerTy()),
5096                          Result);
5097   }
5098
5099   return Result;
5100 }
5101
5102 SDValue
5103 X86TargetLowering::LowerBlockAddress(SDValue Op, SelectionDAG &DAG) {
5104   // Create the TargetBlockAddressAddress node.
5105   unsigned char OpFlags =
5106     Subtarget->ClassifyBlockAddressReference();
5107   CodeModel::Model M = getTargetMachine().getCodeModel();
5108   BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
5109   DebugLoc dl = Op.getDebugLoc();
5110   SDValue Result = DAG.getBlockAddress(BA, getPointerTy(),
5111                                        /*isTarget=*/true, OpFlags);
5112
5113   if (Subtarget->isPICStyleRIPRel() &&
5114       (M == CodeModel::Small || M == CodeModel::Kernel))
5115     Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
5116   else
5117     Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
5118
5119   // With PIC, the address is actually $g + Offset.
5120   if (isGlobalRelativeToPICBase(OpFlags)) {
5121     Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
5122                          DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
5123                          Result);
5124   }
5125
5126   return Result;
5127 }
5128
5129 SDValue
5130 X86TargetLowering::LowerGlobalAddress(const GlobalValue *GV, DebugLoc dl,
5131                                       int64_t Offset,
5132                                       SelectionDAG &DAG) const {
5133   // Create the TargetGlobalAddress node, folding in the constant
5134   // offset if it is legal.
5135   unsigned char OpFlags =
5136     Subtarget->ClassifyGlobalReference(GV, getTargetMachine());
5137   CodeModel::Model M = getTargetMachine().getCodeModel();
5138   SDValue Result;
5139   if (OpFlags == X86II::MO_NO_FLAG &&
5140       X86::isOffsetSuitableForCodeModel(Offset, M)) {
5141     // A direct static reference to a global.
5142     Result = DAG.getTargetGlobalAddress(GV, getPointerTy(), Offset);
5143     Offset = 0;
5144   } else {
5145     Result = DAG.getTargetGlobalAddress(GV, getPointerTy(), 0, OpFlags);
5146   }
5147
5148   if (Subtarget->isPICStyleRIPRel() &&
5149       (M == CodeModel::Small || M == CodeModel::Kernel))
5150     Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
5151   else
5152     Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
5153
5154   // With PIC, the address is actually $g + Offset.
5155   if (isGlobalRelativeToPICBase(OpFlags)) {
5156     Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
5157                          DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
5158                          Result);
5159   }
5160
5161   // For globals that require a load from a stub to get the address, emit the
5162   // load.
5163   if (isGlobalStubReference(OpFlags))
5164     Result = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Result,
5165                          PseudoSourceValue::getGOT(), 0, false, false, 0);
5166
5167   // If there was a non-zero offset that we didn't fold, create an explicit
5168   // addition for it.
5169   if (Offset != 0)
5170     Result = DAG.getNode(ISD::ADD, dl, getPointerTy(), Result,
5171                          DAG.getConstant(Offset, getPointerTy()));
5172
5173   return Result;
5174 }
5175
5176 SDValue
5177 X86TargetLowering::LowerGlobalAddress(SDValue Op, SelectionDAG &DAG) {
5178   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
5179   int64_t Offset = cast<GlobalAddressSDNode>(Op)->getOffset();
5180   return LowerGlobalAddress(GV, Op.getDebugLoc(), Offset, DAG);
5181 }
5182
5183 static SDValue
5184 GetTLSADDR(SelectionDAG &DAG, SDValue Chain, GlobalAddressSDNode *GA,
5185            SDValue *InFlag, const EVT PtrVT, unsigned ReturnReg,
5186            unsigned char OperandFlags) {
5187   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
5188   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Flag);
5189   DebugLoc dl = GA->getDebugLoc();
5190   SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(),
5191                                            GA->getValueType(0),
5192                                            GA->getOffset(),
5193                                            OperandFlags);
5194   if (InFlag) {
5195     SDValue Ops[] = { Chain,  TGA, *InFlag };
5196     Chain = DAG.getNode(X86ISD::TLSADDR, dl, NodeTys, Ops, 3);
5197   } else {
5198     SDValue Ops[]  = { Chain, TGA };
5199     Chain = DAG.getNode(X86ISD::TLSADDR, dl, NodeTys, Ops, 2);
5200   }
5201
5202   // TLSADDR will be codegen'ed as call. Inform MFI that function has calls.
5203   MFI->setHasCalls(true);
5204
5205   SDValue Flag = Chain.getValue(1);
5206   return DAG.getCopyFromReg(Chain, dl, ReturnReg, PtrVT, Flag);
5207 }
5208
5209 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 32 bit
5210 static SDValue
5211 LowerToTLSGeneralDynamicModel32(GlobalAddressSDNode *GA, SelectionDAG &DAG,
5212                                 const EVT PtrVT) {
5213   SDValue InFlag;
5214   DebugLoc dl = GA->getDebugLoc();  // ? function entry point might be better
5215   SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
5216                                      DAG.getNode(X86ISD::GlobalBaseReg,
5217                                                  DebugLoc::getUnknownLoc(),
5218                                                  PtrVT), InFlag);
5219   InFlag = Chain.getValue(1);
5220
5221   return GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX, X86II::MO_TLSGD);
5222 }
5223
5224 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 64 bit
5225 static SDValue
5226 LowerToTLSGeneralDynamicModel64(GlobalAddressSDNode *GA, SelectionDAG &DAG,
5227                                 const EVT PtrVT) {
5228   return GetTLSADDR(DAG, DAG.getEntryNode(), GA, NULL, PtrVT,
5229                     X86::RAX, X86II::MO_TLSGD);
5230 }
5231
5232 // Lower ISD::GlobalTLSAddress using the "initial exec" (for no-pic) or
5233 // "local exec" model.
5234 static SDValue LowerToTLSExecModel(GlobalAddressSDNode *GA, SelectionDAG &DAG,
5235                                    const EVT PtrVT, TLSModel::Model model,
5236                                    bool is64Bit) {
5237   DebugLoc dl = GA->getDebugLoc();
5238   // Get the Thread Pointer
5239   SDValue Base = DAG.getNode(X86ISD::SegmentBaseAddress,
5240                              DebugLoc::getUnknownLoc(), PtrVT,
5241                              DAG.getRegister(is64Bit? X86::FS : X86::GS,
5242                                              MVT::i32));
5243
5244   SDValue ThreadPointer = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Base,
5245                                       NULL, 0, false, false, 0);
5246
5247   unsigned char OperandFlags = 0;
5248   // Most TLS accesses are not RIP relative, even on x86-64.  One exception is
5249   // initialexec.
5250   unsigned WrapperKind = X86ISD::Wrapper;
5251   if (model == TLSModel::LocalExec) {
5252     OperandFlags = is64Bit ? X86II::MO_TPOFF : X86II::MO_NTPOFF;
5253   } else if (is64Bit) {
5254     assert(model == TLSModel::InitialExec);
5255     OperandFlags = X86II::MO_GOTTPOFF;
5256     WrapperKind = X86ISD::WrapperRIP;
5257   } else {
5258     assert(model == TLSModel::InitialExec);
5259     OperandFlags = X86II::MO_INDNTPOFF;
5260   }
5261
5262   // emit "addl x@ntpoff,%eax" (local exec) or "addl x@indntpoff,%eax" (initial
5263   // exec)
5264   SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), GA->getValueType(0),
5265                                            GA->getOffset(), OperandFlags);
5266   SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
5267
5268   if (model == TLSModel::InitialExec)
5269     Offset = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Offset,
5270                          PseudoSourceValue::getGOT(), 0, false, false, 0);
5271
5272   // The address of the thread local variable is the add of the thread
5273   // pointer with the offset of the variable.
5274   return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
5275 }
5276
5277 SDValue
5278 X86TargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) {
5279   // TODO: implement the "local dynamic" model
5280   // TODO: implement the "initial exec"model for pic executables
5281   assert(Subtarget->isTargetELF() &&
5282          "TLS not implemented for non-ELF targets");
5283   GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
5284   const GlobalValue *GV = GA->getGlobal();
5285
5286   // If GV is an alias then use the aliasee for determining
5287   // thread-localness.
5288   if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(GV))
5289     GV = GA->resolveAliasedGlobal(false);
5290
5291   TLSModel::Model model = getTLSModel(GV,
5292                                       getTargetMachine().getRelocationModel());
5293
5294   switch (model) {
5295   case TLSModel::GeneralDynamic:
5296   case TLSModel::LocalDynamic: // not implemented
5297     if (Subtarget->is64Bit())
5298       return LowerToTLSGeneralDynamicModel64(GA, DAG, getPointerTy());
5299     return LowerToTLSGeneralDynamicModel32(GA, DAG, getPointerTy());
5300
5301   case TLSModel::InitialExec:
5302   case TLSModel::LocalExec:
5303     return LowerToTLSExecModel(GA, DAG, getPointerTy(), model,
5304                                Subtarget->is64Bit());
5305   }
5306
5307   llvm_unreachable("Unreachable");
5308   return SDValue();
5309 }
5310
5311
5312 /// LowerShift - Lower SRA_PARTS and friends, which return two i32 values and
5313 /// take a 2 x i32 value to shift plus a shift amount.
5314 SDValue X86TargetLowering::LowerShift(SDValue Op, SelectionDAG &DAG) {
5315   assert(Op.getNumOperands() == 3 && "Not a double-shift!");
5316   EVT VT = Op.getValueType();
5317   unsigned VTBits = VT.getSizeInBits();
5318   DebugLoc dl = Op.getDebugLoc();
5319   bool isSRA = Op.getOpcode() == ISD::SRA_PARTS;
5320   SDValue ShOpLo = Op.getOperand(0);
5321   SDValue ShOpHi = Op.getOperand(1);
5322   SDValue ShAmt  = Op.getOperand(2);
5323   SDValue Tmp1 = isSRA ? DAG.getNode(ISD::SRA, dl, VT, ShOpHi,
5324                                      DAG.getConstant(VTBits - 1, MVT::i8))
5325                        : DAG.getConstant(0, VT);
5326
5327   SDValue Tmp2, Tmp3;
5328   if (Op.getOpcode() == ISD::SHL_PARTS) {
5329     Tmp2 = DAG.getNode(X86ISD::SHLD, dl, VT, ShOpHi, ShOpLo, ShAmt);
5330     Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ShAmt);
5331   } else {
5332     Tmp2 = DAG.getNode(X86ISD::SHRD, dl, VT, ShOpLo, ShOpHi, ShAmt);
5333     Tmp3 = DAG.getNode(isSRA ? ISD::SRA : ISD::SRL, dl, VT, ShOpHi, ShAmt);
5334   }
5335
5336   SDValue AndNode = DAG.getNode(ISD::AND, dl, MVT::i8, ShAmt,
5337                                 DAG.getConstant(VTBits, MVT::i8));
5338   SDValue Cond = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
5339                              AndNode, DAG.getConstant(0, MVT::i8));
5340
5341   SDValue Hi, Lo;
5342   SDValue CC = DAG.getConstant(X86::COND_NE, MVT::i8);
5343   SDValue Ops0[4] = { Tmp2, Tmp3, CC, Cond };
5344   SDValue Ops1[4] = { Tmp3, Tmp1, CC, Cond };
5345
5346   if (Op.getOpcode() == ISD::SHL_PARTS) {
5347     Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0, 4);
5348     Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1, 4);
5349   } else {
5350     Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0, 4);
5351     Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1, 4);
5352   }
5353
5354   SDValue Ops[2] = { Lo, Hi };
5355   return DAG.getMergeValues(Ops, 2, dl);
5356 }
5357
5358 SDValue X86TargetLowering::LowerSINT_TO_FP(SDValue Op, SelectionDAG &DAG) {
5359   EVT SrcVT = Op.getOperand(0).getValueType();
5360
5361   if (SrcVT.isVector()) {
5362     if (SrcVT == MVT::v2i32 && Op.getValueType() == MVT::v2f64) {
5363       return Op;
5364     }
5365     return SDValue();
5366   }
5367
5368   assert(SrcVT.getSimpleVT() <= MVT::i64 && SrcVT.getSimpleVT() >= MVT::i16 &&
5369          "Unknown SINT_TO_FP to lower!");
5370
5371   // These are really Legal; return the operand so the caller accepts it as
5372   // Legal.
5373   if (SrcVT == MVT::i32 && isScalarFPTypeInSSEReg(Op.getValueType()))
5374     return Op;
5375   if (SrcVT == MVT::i64 && isScalarFPTypeInSSEReg(Op.getValueType()) &&
5376       Subtarget->is64Bit()) {
5377     return Op;
5378   }
5379
5380   DebugLoc dl = Op.getDebugLoc();
5381   unsigned Size = SrcVT.getSizeInBits()/8;
5382   MachineFunction &MF = DAG.getMachineFunction();
5383   int SSFI = MF.getFrameInfo()->CreateStackObject(Size, Size, false);
5384   SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
5385   SDValue Chain = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
5386                                StackSlot,
5387                                PseudoSourceValue::getFixedStack(SSFI), 0,
5388                                false, false, 0);
5389   return BuildFILD(Op, SrcVT, Chain, StackSlot, DAG);
5390 }
5391
5392 SDValue X86TargetLowering::BuildFILD(SDValue Op, EVT SrcVT, SDValue Chain,
5393                                      SDValue StackSlot,
5394                                      SelectionDAG &DAG) {
5395   // Build the FILD
5396   DebugLoc dl = Op.getDebugLoc();
5397   SDVTList Tys;
5398   bool useSSE = isScalarFPTypeInSSEReg(Op.getValueType());
5399   if (useSSE)
5400     Tys = DAG.getVTList(MVT::f64, MVT::Other, MVT::Flag);
5401   else
5402     Tys = DAG.getVTList(Op.getValueType(), MVT::Other);
5403   SDValue Ops[] = { Chain, StackSlot, DAG.getValueType(SrcVT) };
5404   SDValue Result = DAG.getNode(useSSE ? X86ISD::FILD_FLAG : X86ISD::FILD, dl,
5405                                Tys, Ops, array_lengthof(Ops));
5406
5407   if (useSSE) {
5408     Chain = Result.getValue(1);
5409     SDValue InFlag = Result.getValue(2);
5410
5411     // FIXME: Currently the FST is flagged to the FILD_FLAG. This
5412     // shouldn't be necessary except that RFP cannot be live across
5413     // multiple blocks. When stackifier is fixed, they can be uncoupled.
5414     MachineFunction &MF = DAG.getMachineFunction();
5415     int SSFI = MF.getFrameInfo()->CreateStackObject(8, 8, false);
5416     SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
5417     Tys = DAG.getVTList(MVT::Other);
5418     SDValue Ops[] = {
5419       Chain, Result, StackSlot, DAG.getValueType(Op.getValueType()), InFlag
5420     };
5421     Chain = DAG.getNode(X86ISD::FST, dl, Tys, Ops, array_lengthof(Ops));
5422     Result = DAG.getLoad(Op.getValueType(), dl, Chain, StackSlot,
5423                          PseudoSourceValue::getFixedStack(SSFI), 0,
5424                          false, false, 0);
5425   }
5426
5427   return Result;
5428 }
5429
5430 // LowerUINT_TO_FP_i64 - 64-bit unsigned integer to double expansion.
5431 SDValue X86TargetLowering::LowerUINT_TO_FP_i64(SDValue Op, SelectionDAG &DAG) {
5432   // This algorithm is not obvious. Here it is in C code, more or less:
5433   /*
5434     double uint64_to_double( uint32_t hi, uint32_t lo ) {
5435       static const __m128i exp = { 0x4330000045300000ULL, 0 };
5436       static const __m128d bias = { 0x1.0p84, 0x1.0p52 };
5437
5438       // Copy ints to xmm registers.
5439       __m128i xh = _mm_cvtsi32_si128( hi );
5440       __m128i xl = _mm_cvtsi32_si128( lo );
5441
5442       // Combine into low half of a single xmm register.
5443       __m128i x = _mm_unpacklo_epi32( xh, xl );
5444       __m128d d;
5445       double sd;
5446
5447       // Merge in appropriate exponents to give the integer bits the right
5448       // magnitude.
5449       x = _mm_unpacklo_epi32( x, exp );
5450
5451       // Subtract away the biases to deal with the IEEE-754 double precision
5452       // implicit 1.
5453       d = _mm_sub_pd( (__m128d) x, bias );
5454
5455       // All conversions up to here are exact. The correctly rounded result is
5456       // calculated using the current rounding mode using the following
5457       // horizontal add.
5458       d = _mm_add_sd( d, _mm_unpackhi_pd( d, d ) );
5459       _mm_store_sd( &sd, d );   // Because we are returning doubles in XMM, this
5460                                 // store doesn't really need to be here (except
5461                                 // maybe to zero the other double)
5462       return sd;
5463     }
5464   */
5465
5466   DebugLoc dl = Op.getDebugLoc();
5467   LLVMContext *Context = DAG.getContext();
5468
5469   // Build some magic constants.
5470   std::vector<Constant*> CV0;
5471   CV0.push_back(ConstantInt::get(*Context, APInt(32, 0x45300000)));
5472   CV0.push_back(ConstantInt::get(*Context, APInt(32, 0x43300000)));
5473   CV0.push_back(ConstantInt::get(*Context, APInt(32, 0)));
5474   CV0.push_back(ConstantInt::get(*Context, APInt(32, 0)));
5475   Constant *C0 = ConstantVector::get(CV0);
5476   SDValue CPIdx0 = DAG.getConstantPool(C0, getPointerTy(), 16);
5477
5478   std::vector<Constant*> CV1;
5479   CV1.push_back(
5480     ConstantFP::get(*Context, APFloat(APInt(64, 0x4530000000000000ULL))));
5481   CV1.push_back(
5482     ConstantFP::get(*Context, APFloat(APInt(64, 0x4330000000000000ULL))));
5483   Constant *C1 = ConstantVector::get(CV1);
5484   SDValue CPIdx1 = DAG.getConstantPool(C1, getPointerTy(), 16);
5485
5486   SDValue XR1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
5487                             DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
5488                                         Op.getOperand(0),
5489                                         DAG.getIntPtrConstant(1)));
5490   SDValue XR2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
5491                             DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
5492                                         Op.getOperand(0),
5493                                         DAG.getIntPtrConstant(0)));
5494   SDValue Unpck1 = getUnpackl(DAG, dl, MVT::v4i32, XR1, XR2);
5495   SDValue CLod0 = DAG.getLoad(MVT::v4i32, dl, DAG.getEntryNode(), CPIdx0,
5496                               PseudoSourceValue::getConstantPool(), 0,
5497                               false, false, 16);
5498   SDValue Unpck2 = getUnpackl(DAG, dl, MVT::v4i32, Unpck1, CLod0);
5499   SDValue XR2F = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v2f64, Unpck2);
5500   SDValue CLod1 = DAG.getLoad(MVT::v2f64, dl, CLod0.getValue(1), CPIdx1,
5501                               PseudoSourceValue::getConstantPool(), 0,
5502                               false, false, 16);
5503   SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, XR2F, CLod1);
5504
5505   // Add the halves; easiest way is to swap them into another reg first.
5506   int ShufMask[2] = { 1, -1 };
5507   SDValue Shuf = DAG.getVectorShuffle(MVT::v2f64, dl, Sub,
5508                                       DAG.getUNDEF(MVT::v2f64), ShufMask);
5509   SDValue Add = DAG.getNode(ISD::FADD, dl, MVT::v2f64, Shuf, Sub);
5510   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Add,
5511                      DAG.getIntPtrConstant(0));
5512 }
5513
5514 // LowerUINT_TO_FP_i32 - 32-bit unsigned integer to float expansion.
5515 SDValue X86TargetLowering::LowerUINT_TO_FP_i32(SDValue Op, SelectionDAG &DAG) {
5516   DebugLoc dl = Op.getDebugLoc();
5517   // FP constant to bias correct the final result.
5518   SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL),
5519                                    MVT::f64);
5520
5521   // Load the 32-bit value into an XMM register.
5522   SDValue Load = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
5523                              DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
5524                                          Op.getOperand(0),
5525                                          DAG.getIntPtrConstant(0)));
5526
5527   Load = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
5528                      DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v2f64, Load),
5529                      DAG.getIntPtrConstant(0));
5530
5531   // Or the load with the bias.
5532   SDValue Or = DAG.getNode(ISD::OR, dl, MVT::v2i64,
5533                            DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v2i64,
5534                                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
5535                                                    MVT::v2f64, Load)),
5536                            DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v2i64,
5537                                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
5538                                                    MVT::v2f64, Bias)));
5539   Or = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
5540                    DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v2f64, Or),
5541                    DAG.getIntPtrConstant(0));
5542
5543   // Subtract the bias.
5544   SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::f64, Or, Bias);
5545
5546   // Handle final rounding.
5547   EVT DestVT = Op.getValueType();
5548
5549   if (DestVT.bitsLT(MVT::f64)) {
5550     return DAG.getNode(ISD::FP_ROUND, dl, DestVT, Sub,
5551                        DAG.getIntPtrConstant(0));
5552   } else if (DestVT.bitsGT(MVT::f64)) {
5553     return DAG.getNode(ISD::FP_EXTEND, dl, DestVT, Sub);
5554   }
5555
5556   // Handle final rounding.
5557   return Sub;
5558 }
5559
5560 SDValue X86TargetLowering::LowerUINT_TO_FP(SDValue Op, SelectionDAG &DAG) {
5561   SDValue N0 = Op.getOperand(0);
5562   DebugLoc dl = Op.getDebugLoc();
5563
5564   // Now not UINT_TO_FP is legal (it's marked custom), dag combiner won't
5565   // optimize it to a SINT_TO_FP when the sign bit is known zero. Perform
5566   // the optimization here.
5567   if (DAG.SignBitIsZero(N0))
5568     return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(), N0);
5569
5570   EVT SrcVT = N0.getValueType();
5571   if (SrcVT == MVT::i64) {
5572     // We only handle SSE2 f64 target here; caller can expand the rest.
5573     if (Op.getValueType() != MVT::f64 || !X86ScalarSSEf64)
5574       return SDValue();
5575
5576     return LowerUINT_TO_FP_i64(Op, DAG);
5577   } else if (SrcVT == MVT::i32 && X86ScalarSSEf64) {
5578     return LowerUINT_TO_FP_i32(Op, DAG);
5579   }
5580
5581   assert(SrcVT == MVT::i32 && "Unknown UINT_TO_FP to lower!");
5582
5583   // Make a 64-bit buffer, and use it to build an FILD.
5584   SDValue StackSlot = DAG.CreateStackTemporary(MVT::i64);
5585   SDValue WordOff = DAG.getConstant(4, getPointerTy());
5586   SDValue OffsetSlot = DAG.getNode(ISD::ADD, dl,
5587                                    getPointerTy(), StackSlot, WordOff);
5588   SDValue Store1 = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
5589                                 StackSlot, NULL, 0, false, false, 0);
5590   SDValue Store2 = DAG.getStore(Store1, dl, DAG.getConstant(0, MVT::i32),
5591                                 OffsetSlot, NULL, 0, false, false, 0);
5592   return BuildFILD(Op, MVT::i64, Store2, StackSlot, DAG);
5593 }
5594
5595 std::pair<SDValue,SDValue> X86TargetLowering::
5596 FP_TO_INTHelper(SDValue Op, SelectionDAG &DAG, bool IsSigned) {
5597   DebugLoc dl = Op.getDebugLoc();
5598
5599   EVT DstTy = Op.getValueType();
5600
5601   if (!IsSigned) {
5602     assert(DstTy == MVT::i32 && "Unexpected FP_TO_UINT");
5603     DstTy = MVT::i64;
5604   }
5605
5606   assert(DstTy.getSimpleVT() <= MVT::i64 &&
5607          DstTy.getSimpleVT() >= MVT::i16 &&
5608          "Unknown FP_TO_SINT to lower!");
5609
5610   // These are really Legal.
5611   if (DstTy == MVT::i32 &&
5612       isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
5613     return std::make_pair(SDValue(), SDValue());
5614   if (Subtarget->is64Bit() &&
5615       DstTy == MVT::i64 &&
5616       isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
5617     return std::make_pair(SDValue(), SDValue());
5618
5619   // We lower FP->sint64 into FISTP64, followed by a load, all to a temporary
5620   // stack slot.
5621   MachineFunction &MF = DAG.getMachineFunction();
5622   unsigned MemSize = DstTy.getSizeInBits()/8;
5623   int SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
5624   SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
5625
5626   unsigned Opc;
5627   switch (DstTy.getSimpleVT().SimpleTy) {
5628   default: llvm_unreachable("Invalid FP_TO_SINT to lower!");
5629   case MVT::i16: Opc = X86ISD::FP_TO_INT16_IN_MEM; break;
5630   case MVT::i32: Opc = X86ISD::FP_TO_INT32_IN_MEM; break;
5631   case MVT::i64: Opc = X86ISD::FP_TO_INT64_IN_MEM; break;
5632   }
5633
5634   SDValue Chain = DAG.getEntryNode();
5635   SDValue Value = Op.getOperand(0);
5636   if (isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType())) {
5637     assert(DstTy == MVT::i64 && "Invalid FP_TO_SINT to lower!");
5638     Chain = DAG.getStore(Chain, dl, Value, StackSlot,
5639                          PseudoSourceValue::getFixedStack(SSFI), 0,
5640                          false, false, 0);
5641     SDVTList Tys = DAG.getVTList(Op.getOperand(0).getValueType(), MVT::Other);
5642     SDValue Ops[] = {
5643       Chain, StackSlot, DAG.getValueType(Op.getOperand(0).getValueType())
5644     };
5645     Value = DAG.getNode(X86ISD::FLD, dl, Tys, Ops, 3);
5646     Chain = Value.getValue(1);
5647     SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
5648     StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
5649   }
5650
5651   // Build the FP_TO_INT*_IN_MEM
5652   SDValue Ops[] = { Chain, Value, StackSlot };
5653   SDValue FIST = DAG.getNode(Opc, dl, MVT::Other, Ops, 3);
5654
5655   return std::make_pair(FIST, StackSlot);
5656 }
5657
5658 SDValue X86TargetLowering::LowerFP_TO_SINT(SDValue Op, SelectionDAG &DAG) {
5659   if (Op.getValueType().isVector()) {
5660     if (Op.getValueType() == MVT::v2i32 &&
5661         Op.getOperand(0).getValueType() == MVT::v2f64) {
5662       return Op;
5663     }
5664     return SDValue();
5665   }
5666
5667   std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG, true);
5668   SDValue FIST = Vals.first, StackSlot = Vals.second;
5669   // If FP_TO_INTHelper failed, the node is actually supposed to be Legal.
5670   if (FIST.getNode() == 0) return Op;
5671
5672   // Load the result.
5673   return DAG.getLoad(Op.getValueType(), Op.getDebugLoc(),
5674                      FIST, StackSlot, NULL, 0, false, false, 0);
5675 }
5676
5677 SDValue X86TargetLowering::LowerFP_TO_UINT(SDValue Op, SelectionDAG &DAG) {
5678   std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG, false);
5679   SDValue FIST = Vals.first, StackSlot = Vals.second;
5680   assert(FIST.getNode() && "Unexpected failure");
5681
5682   // Load the result.
5683   return DAG.getLoad(Op.getValueType(), Op.getDebugLoc(),
5684                      FIST, StackSlot, NULL, 0, false, false, 0);
5685 }
5686
5687 SDValue X86TargetLowering::LowerFABS(SDValue Op, SelectionDAG &DAG) {
5688   LLVMContext *Context = DAG.getContext();
5689   DebugLoc dl = Op.getDebugLoc();
5690   EVT VT = Op.getValueType();
5691   EVT EltVT = VT;
5692   if (VT.isVector())
5693     EltVT = VT.getVectorElementType();
5694   std::vector<Constant*> CV;
5695   if (EltVT == MVT::f64) {
5696     Constant *C = ConstantFP::get(*Context, APFloat(APInt(64, ~(1ULL << 63))));
5697     CV.push_back(C);
5698     CV.push_back(C);
5699   } else {
5700     Constant *C = ConstantFP::get(*Context, APFloat(APInt(32, ~(1U << 31))));
5701     CV.push_back(C);
5702     CV.push_back(C);
5703     CV.push_back(C);
5704     CV.push_back(C);
5705   }
5706   Constant *C = ConstantVector::get(CV);
5707   SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
5708   SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
5709                              PseudoSourceValue::getConstantPool(), 0,
5710                              false, false, 16);
5711   return DAG.getNode(X86ISD::FAND, dl, VT, Op.getOperand(0), Mask);
5712 }
5713
5714 SDValue X86TargetLowering::LowerFNEG(SDValue Op, SelectionDAG &DAG) {
5715   LLVMContext *Context = DAG.getContext();
5716   DebugLoc dl = Op.getDebugLoc();
5717   EVT VT = Op.getValueType();
5718   EVT EltVT = VT;
5719   if (VT.isVector())
5720     EltVT = VT.getVectorElementType();
5721   std::vector<Constant*> CV;
5722   if (EltVT == MVT::f64) {
5723     Constant *C = ConstantFP::get(*Context, APFloat(APInt(64, 1ULL << 63)));
5724     CV.push_back(C);
5725     CV.push_back(C);
5726   } else {
5727     Constant *C = ConstantFP::get(*Context, APFloat(APInt(32, 1U << 31)));
5728     CV.push_back(C);
5729     CV.push_back(C);
5730     CV.push_back(C);
5731     CV.push_back(C);
5732   }
5733   Constant *C = ConstantVector::get(CV);
5734   SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
5735   SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
5736                              PseudoSourceValue::getConstantPool(), 0,
5737                              false, false, 16);
5738   if (VT.isVector()) {
5739     return DAG.getNode(ISD::BIT_CONVERT, dl, VT,
5740                        DAG.getNode(ISD::XOR, dl, MVT::v2i64,
5741                     DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v2i64,
5742                                 Op.getOperand(0)),
5743                     DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v2i64, Mask)));
5744   } else {
5745     return DAG.getNode(X86ISD::FXOR, dl, VT, Op.getOperand(0), Mask);
5746   }
5747 }
5748
5749 SDValue X86TargetLowering::LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) {
5750   LLVMContext *Context = DAG.getContext();
5751   SDValue Op0 = Op.getOperand(0);
5752   SDValue Op1 = Op.getOperand(1);
5753   DebugLoc dl = Op.getDebugLoc();
5754   EVT VT = Op.getValueType();
5755   EVT SrcVT = Op1.getValueType();
5756
5757   // If second operand is smaller, extend it first.
5758   if (SrcVT.bitsLT(VT)) {
5759     Op1 = DAG.getNode(ISD::FP_EXTEND, dl, VT, Op1);
5760     SrcVT = VT;
5761   }
5762   // And if it is bigger, shrink it first.
5763   if (SrcVT.bitsGT(VT)) {
5764     Op1 = DAG.getNode(ISD::FP_ROUND, dl, VT, Op1, DAG.getIntPtrConstant(1));
5765     SrcVT = VT;
5766   }
5767
5768   // At this point the operands and the result should have the same
5769   // type, and that won't be f80 since that is not custom lowered.
5770
5771   // First get the sign bit of second operand.
5772   std::vector<Constant*> CV;
5773   if (SrcVT == MVT::f64) {
5774     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, 1ULL << 63))));
5775     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, 0))));
5776   } else {
5777     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 1U << 31))));
5778     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
5779     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
5780     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
5781   }
5782   Constant *C = ConstantVector::get(CV);
5783   SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
5784   SDValue Mask1 = DAG.getLoad(SrcVT, dl, DAG.getEntryNode(), CPIdx,
5785                               PseudoSourceValue::getConstantPool(), 0,
5786                               false, false, 16);
5787   SDValue SignBit = DAG.getNode(X86ISD::FAND, dl, SrcVT, Op1, Mask1);
5788
5789   // Shift sign bit right or left if the two operands have different types.
5790   if (SrcVT.bitsGT(VT)) {
5791     // Op0 is MVT::f32, Op1 is MVT::f64.
5792     SignBit = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f64, SignBit);
5793     SignBit = DAG.getNode(X86ISD::FSRL, dl, MVT::v2f64, SignBit,
5794                           DAG.getConstant(32, MVT::i32));
5795     SignBit = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v4f32, SignBit);
5796     SignBit = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f32, SignBit,
5797                           DAG.getIntPtrConstant(0));
5798   }
5799
5800   // Clear first operand sign bit.
5801   CV.clear();
5802   if (VT == MVT::f64) {
5803     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, ~(1ULL << 63)))));
5804     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, 0))));
5805   } else {
5806     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, ~(1U << 31)))));
5807     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
5808     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
5809     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
5810   }
5811   C = ConstantVector::get(CV);
5812   CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
5813   SDValue Mask2 = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
5814                               PseudoSourceValue::getConstantPool(), 0,
5815                               false, false, 16);
5816   SDValue Val = DAG.getNode(X86ISD::FAND, dl, VT, Op0, Mask2);
5817
5818   // Or the value with the sign bit.
5819   return DAG.getNode(X86ISD::FOR, dl, VT, Val, SignBit);
5820 }
5821
5822 /// Emit nodes that will be selected as "test Op0,Op0", or something
5823 /// equivalent.
5824 SDValue X86TargetLowering::EmitTest(SDValue Op, unsigned X86CC,
5825                                     SelectionDAG &DAG) {
5826   DebugLoc dl = Op.getDebugLoc();
5827
5828   // CF and OF aren't always set the way we want. Determine which
5829   // of these we need.
5830   bool NeedCF = false;
5831   bool NeedOF = false;
5832   switch (X86CC) {
5833   case X86::COND_A: case X86::COND_AE:
5834   case X86::COND_B: case X86::COND_BE:
5835     NeedCF = true;
5836     break;
5837   case X86::COND_G: case X86::COND_GE:
5838   case X86::COND_L: case X86::COND_LE:
5839   case X86::COND_O: case X86::COND_NO:
5840     NeedOF = true;
5841     break;
5842   default: break;
5843   }
5844
5845   // See if we can use the EFLAGS value from the operand instead of
5846   // doing a separate TEST. TEST always sets OF and CF to 0, so unless
5847   // we prove that the arithmetic won't overflow, we can't use OF or CF.
5848   if (Op.getResNo() == 0 && !NeedOF && !NeedCF) {
5849     unsigned Opcode = 0;
5850     unsigned NumOperands = 0;
5851     switch (Op.getNode()->getOpcode()) {
5852     case ISD::ADD:
5853       // Due to an isel shortcoming, be conservative if this add is likely to
5854       // be selected as part of a load-modify-store instruction. When the root
5855       // node in a match is a store, isel doesn't know how to remap non-chain
5856       // non-flag uses of other nodes in the match, such as the ADD in this
5857       // case. This leads to the ADD being left around and reselected, with
5858       // the result being two adds in the output.
5859       for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
5860            UE = Op.getNode()->use_end(); UI != UE; ++UI)
5861         if (UI->getOpcode() == ISD::STORE)
5862           goto default_case;
5863       if (ConstantSDNode *C =
5864             dyn_cast<ConstantSDNode>(Op.getNode()->getOperand(1))) {
5865         // An add of one will be selected as an INC.
5866         if (C->getAPIntValue() == 1) {
5867           Opcode = X86ISD::INC;
5868           NumOperands = 1;
5869           break;
5870         }
5871         // An add of negative one (subtract of one) will be selected as a DEC.
5872         if (C->getAPIntValue().isAllOnesValue()) {
5873           Opcode = X86ISD::DEC;
5874           NumOperands = 1;
5875           break;
5876         }
5877       }
5878       // Otherwise use a regular EFLAGS-setting add.
5879       Opcode = X86ISD::ADD;
5880       NumOperands = 2;
5881       break;
5882     case ISD::AND: {
5883       // If the primary and result isn't used, don't bother using X86ISD::AND,
5884       // because a TEST instruction will be better.
5885       bool NonFlagUse = false;
5886       for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
5887              UE = Op.getNode()->use_end(); UI != UE; ++UI) {
5888         SDNode *User = *UI;
5889         unsigned UOpNo = UI.getOperandNo();
5890         if (User->getOpcode() == ISD::TRUNCATE && User->hasOneUse()) {
5891           // Look pass truncate.
5892           UOpNo = User->use_begin().getOperandNo();
5893           User = *User->use_begin();
5894         }
5895         if (User->getOpcode() != ISD::BRCOND &&
5896             User->getOpcode() != ISD::SETCC &&
5897             (User->getOpcode() != ISD::SELECT || UOpNo != 0)) {
5898           NonFlagUse = true;
5899           break;
5900         }
5901       }
5902       if (!NonFlagUse)
5903         break;
5904     }
5905     // FALL THROUGH
5906     case ISD::SUB:
5907     case ISD::OR:
5908     case ISD::XOR:
5909       // Due to the ISEL shortcoming noted above, be conservative if this op is
5910       // likely to be selected as part of a load-modify-store instruction.
5911       for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
5912            UE = Op.getNode()->use_end(); UI != UE; ++UI)
5913         if (UI->getOpcode() == ISD::STORE)
5914           goto default_case;
5915       // Otherwise use a regular EFLAGS-setting instruction.
5916       switch (Op.getNode()->getOpcode()) {
5917       case ISD::SUB: Opcode = X86ISD::SUB; break;
5918       case ISD::OR:  Opcode = X86ISD::OR;  break;
5919       case ISD::XOR: Opcode = X86ISD::XOR; break;
5920       case ISD::AND: Opcode = X86ISD::AND; break;
5921       default: llvm_unreachable("unexpected operator!");
5922       }
5923       NumOperands = 2;
5924       break;
5925     case X86ISD::ADD:
5926     case X86ISD::SUB:
5927     case X86ISD::INC:
5928     case X86ISD::DEC:
5929     case X86ISD::OR:
5930     case X86ISD::XOR:
5931     case X86ISD::AND:
5932       return SDValue(Op.getNode(), 1);
5933     default:
5934     default_case:
5935       break;
5936     }
5937     if (Opcode != 0) {
5938       SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
5939       SmallVector<SDValue, 4> Ops;
5940       for (unsigned i = 0; i != NumOperands; ++i)
5941         Ops.push_back(Op.getOperand(i));
5942       SDValue New = DAG.getNode(Opcode, dl, VTs, &Ops[0], NumOperands);
5943       DAG.ReplaceAllUsesWith(Op, New);
5944       return SDValue(New.getNode(), 1);
5945     }
5946   }
5947
5948   // Otherwise just emit a CMP with 0, which is the TEST pattern.
5949   return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
5950                      DAG.getConstant(0, Op.getValueType()));
5951 }
5952
5953 /// Emit nodes that will be selected as "cmp Op0,Op1", or something
5954 /// equivalent.
5955 SDValue X86TargetLowering::EmitCmp(SDValue Op0, SDValue Op1, unsigned X86CC,
5956                                    SelectionDAG &DAG) {
5957   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op1))
5958     if (C->getAPIntValue() == 0)
5959       return EmitTest(Op0, X86CC, DAG);
5960
5961   DebugLoc dl = Op0.getDebugLoc();
5962   return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op0, Op1);
5963 }
5964
5965 /// LowerToBT - Result of 'and' is compared against zero. Turn it into a BT node
5966 /// if it's possible.
5967 static SDValue LowerToBT(SDValue And, ISD::CondCode CC,
5968                          DebugLoc dl, SelectionDAG &DAG) {
5969   SDValue Op0 = And.getOperand(0);
5970   SDValue Op1 = And.getOperand(1);
5971   if (Op0.getOpcode() == ISD::TRUNCATE)
5972     Op0 = Op0.getOperand(0);
5973   if (Op1.getOpcode() == ISD::TRUNCATE)
5974     Op1 = Op1.getOperand(0);
5975
5976   SDValue LHS, RHS;
5977   if (Op1.getOpcode() == ISD::SHL) {
5978     if (ConstantSDNode *And10C = dyn_cast<ConstantSDNode>(Op1.getOperand(0)))
5979       if (And10C->getZExtValue() == 1) {
5980         LHS = Op0;
5981         RHS = Op1.getOperand(1);
5982       }
5983   } else if (Op0.getOpcode() == ISD::SHL) {
5984     if (ConstantSDNode *And00C = dyn_cast<ConstantSDNode>(Op0.getOperand(0)))
5985       if (And00C->getZExtValue() == 1) {
5986         LHS = Op1;
5987         RHS = Op0.getOperand(1);
5988       }
5989   } else if (Op1.getOpcode() == ISD::Constant) {
5990     ConstantSDNode *AndRHS = cast<ConstantSDNode>(Op1);
5991     SDValue AndLHS = Op0;
5992     if (AndRHS->getZExtValue() == 1 && AndLHS.getOpcode() == ISD::SRL) {
5993       LHS = AndLHS.getOperand(0);
5994       RHS = AndLHS.getOperand(1);
5995     }
5996   }
5997
5998   if (LHS.getNode()) {
5999     // If LHS is i8, promote it to i16 with any_extend.  There is no i8 BT
6000     // instruction.  Since the shift amount is in-range-or-undefined, we know
6001     // that doing a bittest on the i16 value is ok.  We extend to i32 because
6002     // the encoding for the i16 version is larger than the i32 version.
6003     if (LHS.getValueType() == MVT::i8)
6004       LHS = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, LHS);
6005
6006     // If the operand types disagree, extend the shift amount to match.  Since
6007     // BT ignores high bits (like shifts) we can use anyextend.
6008     if (LHS.getValueType() != RHS.getValueType())
6009       RHS = DAG.getNode(ISD::ANY_EXTEND, dl, LHS.getValueType(), RHS);
6010
6011     SDValue BT = DAG.getNode(X86ISD::BT, dl, MVT::i32, LHS, RHS);
6012     unsigned Cond = CC == ISD::SETEQ ? X86::COND_AE : X86::COND_B;
6013     return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
6014                        DAG.getConstant(Cond, MVT::i8), BT);
6015   }
6016
6017   return SDValue();
6018 }
6019
6020 SDValue X86TargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) {
6021   assert(Op.getValueType() == MVT::i8 && "SetCC type must be 8-bit integer");
6022   SDValue Op0 = Op.getOperand(0);
6023   SDValue Op1 = Op.getOperand(1);
6024   DebugLoc dl = Op.getDebugLoc();
6025   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
6026
6027   // Optimize to BT if possible.
6028   // Lower (X & (1 << N)) == 0 to BT(X, N).
6029   // Lower ((X >>u N) & 1) != 0 to BT(X, N).
6030   // Lower ((X >>s N) & 1) != 0 to BT(X, N).
6031   if (Op0.getOpcode() == ISD::AND &&
6032       Op0.hasOneUse() &&
6033       Op1.getOpcode() == ISD::Constant &&
6034       cast<ConstantSDNode>(Op1)->getZExtValue() == 0 &&
6035       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
6036     SDValue NewSetCC = LowerToBT(Op0, CC, dl, DAG);
6037     if (NewSetCC.getNode())
6038       return NewSetCC;
6039   }
6040
6041   // Look for "(setcc) == / != 1" to avoid unncessary setcc.
6042   if (Op0.getOpcode() == X86ISD::SETCC &&
6043       Op1.getOpcode() == ISD::Constant &&
6044       (cast<ConstantSDNode>(Op1)->getZExtValue() == 1 ||
6045        cast<ConstantSDNode>(Op1)->isNullValue()) &&
6046       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
6047     X86::CondCode CCode = (X86::CondCode)Op0.getConstantOperandVal(0);
6048     bool Invert = (CC == ISD::SETNE) ^
6049       cast<ConstantSDNode>(Op1)->isNullValue();
6050     if (Invert)
6051       CCode = X86::GetOppositeBranchCondition(CCode);
6052     return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
6053                        DAG.getConstant(CCode, MVT::i8), Op0.getOperand(1));
6054   }
6055
6056   bool isFP = Op.getOperand(1).getValueType().isFloatingPoint();
6057   unsigned X86CC = TranslateX86CC(CC, isFP, Op0, Op1, DAG);
6058   if (X86CC == X86::COND_INVALID)
6059     return SDValue();
6060
6061   SDValue Cond = EmitCmp(Op0, Op1, X86CC, DAG);
6062
6063   // Use sbb x, x to materialize carry bit into a GPR.
6064   if (X86CC == X86::COND_B)
6065     return DAG.getNode(ISD::AND, dl, MVT::i8,
6066                        DAG.getNode(X86ISD::SETCC_CARRY, dl, MVT::i8,
6067                                    DAG.getConstant(X86CC, MVT::i8), Cond),
6068                        DAG.getConstant(1, MVT::i8));
6069
6070   return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
6071                      DAG.getConstant(X86CC, MVT::i8), Cond);
6072 }
6073
6074 SDValue X86TargetLowering::LowerVSETCC(SDValue Op, SelectionDAG &DAG) {
6075   SDValue Cond;
6076   SDValue Op0 = Op.getOperand(0);
6077   SDValue Op1 = Op.getOperand(1);
6078   SDValue CC = Op.getOperand(2);
6079   EVT VT = Op.getValueType();
6080   ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
6081   bool isFP = Op.getOperand(1).getValueType().isFloatingPoint();
6082   DebugLoc dl = Op.getDebugLoc();
6083
6084   if (isFP) {
6085     unsigned SSECC = 8;
6086     EVT VT0 = Op0.getValueType();
6087     assert(VT0 == MVT::v4f32 || VT0 == MVT::v2f64);
6088     unsigned Opc = VT0 == MVT::v4f32 ? X86ISD::CMPPS : X86ISD::CMPPD;
6089     bool Swap = false;
6090
6091     switch (SetCCOpcode) {
6092     default: break;
6093     case ISD::SETOEQ:
6094     case ISD::SETEQ:  SSECC = 0; break;
6095     case ISD::SETOGT:
6096     case ISD::SETGT: Swap = true; // Fallthrough
6097     case ISD::SETLT:
6098     case ISD::SETOLT: SSECC = 1; break;
6099     case ISD::SETOGE:
6100     case ISD::SETGE: Swap = true; // Fallthrough
6101     case ISD::SETLE:
6102     case ISD::SETOLE: SSECC = 2; break;
6103     case ISD::SETUO:  SSECC = 3; break;
6104     case ISD::SETUNE:
6105     case ISD::SETNE:  SSECC = 4; break;
6106     case ISD::SETULE: Swap = true;
6107     case ISD::SETUGE: SSECC = 5; break;
6108     case ISD::SETULT: Swap = true;
6109     case ISD::SETUGT: SSECC = 6; break;
6110     case ISD::SETO:   SSECC = 7; break;
6111     }
6112     if (Swap)
6113       std::swap(Op0, Op1);
6114
6115     // In the two special cases we can't handle, emit two comparisons.
6116     if (SSECC == 8) {
6117       if (SetCCOpcode == ISD::SETUEQ) {
6118         SDValue UNORD, EQ;
6119         UNORD = DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(3, MVT::i8));
6120         EQ = DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(0, MVT::i8));
6121         return DAG.getNode(ISD::OR, dl, VT, UNORD, EQ);
6122       }
6123       else if (SetCCOpcode == ISD::SETONE) {
6124         SDValue ORD, NEQ;
6125         ORD = DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(7, MVT::i8));
6126         NEQ = DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(4, MVT::i8));
6127         return DAG.getNode(ISD::AND, dl, VT, ORD, NEQ);
6128       }
6129       llvm_unreachable("Illegal FP comparison");
6130     }
6131     // Handle all other FP comparisons here.
6132     return DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(SSECC, MVT::i8));
6133   }
6134
6135   // We are handling one of the integer comparisons here.  Since SSE only has
6136   // GT and EQ comparisons for integer, swapping operands and multiple
6137   // operations may be required for some comparisons.
6138   unsigned Opc = 0, EQOpc = 0, GTOpc = 0;
6139   bool Swap = false, Invert = false, FlipSigns = false;
6140
6141   switch (VT.getSimpleVT().SimpleTy) {
6142   default: break;
6143   case MVT::v8i8:
6144   case MVT::v16i8: EQOpc = X86ISD::PCMPEQB; GTOpc = X86ISD::PCMPGTB; break;
6145   case MVT::v4i16:
6146   case MVT::v8i16: EQOpc = X86ISD::PCMPEQW; GTOpc = X86ISD::PCMPGTW; break;
6147   case MVT::v2i32:
6148   case MVT::v4i32: EQOpc = X86ISD::PCMPEQD; GTOpc = X86ISD::PCMPGTD; break;
6149   case MVT::v2i64: EQOpc = X86ISD::PCMPEQQ; GTOpc = X86ISD::PCMPGTQ; break;
6150   }
6151
6152   switch (SetCCOpcode) {
6153   default: break;
6154   case ISD::SETNE:  Invert = true;
6155   case ISD::SETEQ:  Opc = EQOpc; break;
6156   case ISD::SETLT:  Swap = true;
6157   case ISD::SETGT:  Opc = GTOpc; break;
6158   case ISD::SETGE:  Swap = true;
6159   case ISD::SETLE:  Opc = GTOpc; Invert = true; break;
6160   case ISD::SETULT: Swap = true;
6161   case ISD::SETUGT: Opc = GTOpc; FlipSigns = true; break;
6162   case ISD::SETUGE: Swap = true;
6163   case ISD::SETULE: Opc = GTOpc; FlipSigns = true; Invert = true; break;
6164   }
6165   if (Swap)
6166     std::swap(Op0, Op1);
6167
6168   // Since SSE has no unsigned integer comparisons, we need to flip  the sign
6169   // bits of the inputs before performing those operations.
6170   if (FlipSigns) {
6171     EVT EltVT = VT.getVectorElementType();
6172     SDValue SignBit = DAG.getConstant(APInt::getSignBit(EltVT.getSizeInBits()),
6173                                       EltVT);
6174     std::vector<SDValue> SignBits(VT.getVectorNumElements(), SignBit);
6175     SDValue SignVec = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &SignBits[0],
6176                                     SignBits.size());
6177     Op0 = DAG.getNode(ISD::XOR, dl, VT, Op0, SignVec);
6178     Op1 = DAG.getNode(ISD::XOR, dl, VT, Op1, SignVec);
6179   }
6180
6181   SDValue Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
6182
6183   // If the logical-not of the result is required, perform that now.
6184   if (Invert)
6185     Result = DAG.getNOT(dl, Result, VT);
6186
6187   return Result;
6188 }
6189
6190 // isX86LogicalCmp - Return true if opcode is a X86 logical comparison.
6191 static bool isX86LogicalCmp(SDValue Op) {
6192   unsigned Opc = Op.getNode()->getOpcode();
6193   if (Opc == X86ISD::CMP || Opc == X86ISD::COMI || Opc == X86ISD::UCOMI)
6194     return true;
6195   if (Op.getResNo() == 1 &&
6196       (Opc == X86ISD::ADD ||
6197        Opc == X86ISD::SUB ||
6198        Opc == X86ISD::SMUL ||
6199        Opc == X86ISD::UMUL ||
6200        Opc == X86ISD::INC ||
6201        Opc == X86ISD::DEC ||
6202        Opc == X86ISD::OR ||
6203        Opc == X86ISD::XOR ||
6204        Opc == X86ISD::AND))
6205     return true;
6206
6207   return false;
6208 }
6209
6210 SDValue X86TargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) {
6211   bool addTest = true;
6212   SDValue Cond  = Op.getOperand(0);
6213   DebugLoc dl = Op.getDebugLoc();
6214   SDValue CC;
6215
6216   if (Cond.getOpcode() == ISD::SETCC) {
6217     SDValue NewCond = LowerSETCC(Cond, DAG);
6218     if (NewCond.getNode())
6219       Cond = NewCond;
6220   }
6221
6222   // (select (x == 0), -1, 0) -> (sign_bit (x - 1))
6223   SDValue Op1 = Op.getOperand(1);
6224   SDValue Op2 = Op.getOperand(2);
6225   if (Cond.getOpcode() == X86ISD::SETCC &&
6226       cast<ConstantSDNode>(Cond.getOperand(0))->getZExtValue() == X86::COND_E) {
6227     SDValue Cmp = Cond.getOperand(1);
6228     if (Cmp.getOpcode() == X86ISD::CMP) {
6229       ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(Op1);
6230       ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(Op2);
6231       ConstantSDNode *RHSC =
6232         dyn_cast<ConstantSDNode>(Cmp.getOperand(1).getNode());
6233       if (N1C && N1C->isAllOnesValue() &&
6234           N2C && N2C->isNullValue() &&
6235           RHSC && RHSC->isNullValue()) {
6236         SDValue CmpOp0 = Cmp.getOperand(0);
6237         Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
6238                           CmpOp0, DAG.getConstant(1, CmpOp0.getValueType()));
6239         return DAG.getNode(X86ISD::SETCC_CARRY, dl, Op.getValueType(),
6240                            DAG.getConstant(X86::COND_B, MVT::i8), Cmp);
6241       }
6242     }
6243   }
6244
6245   // Look pass (and (setcc_carry (cmp ...)), 1).
6246   if (Cond.getOpcode() == ISD::AND &&
6247       Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
6248     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
6249     if (C && C->getAPIntValue() == 1) 
6250       Cond = Cond.getOperand(0);
6251   }
6252
6253   // If condition flag is set by a X86ISD::CMP, then use it as the condition
6254   // setting operand in place of the X86ISD::SETCC.
6255   if (Cond.getOpcode() == X86ISD::SETCC ||
6256       Cond.getOpcode() == X86ISD::SETCC_CARRY) {
6257     CC = Cond.getOperand(0);
6258
6259     SDValue Cmp = Cond.getOperand(1);
6260     unsigned Opc = Cmp.getOpcode();
6261     EVT VT = Op.getValueType();
6262
6263     bool IllegalFPCMov = false;
6264     if (VT.isFloatingPoint() && !VT.isVector() &&
6265         !isScalarFPTypeInSSEReg(VT))  // FPStack?
6266       IllegalFPCMov = !hasFPCMov(cast<ConstantSDNode>(CC)->getSExtValue());
6267
6268     if ((isX86LogicalCmp(Cmp) && !IllegalFPCMov) ||
6269         Opc == X86ISD::BT) { // FIXME
6270       Cond = Cmp;
6271       addTest = false;
6272     }
6273   }
6274
6275   if (addTest) {
6276     // Look pass the truncate.
6277     if (Cond.getOpcode() == ISD::TRUNCATE)
6278       Cond = Cond.getOperand(0);
6279
6280     // We know the result of AND is compared against zero. Try to match
6281     // it to BT.
6282     if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) { 
6283       SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, dl, DAG);
6284       if (NewSetCC.getNode()) {
6285         CC = NewSetCC.getOperand(0);
6286         Cond = NewSetCC.getOperand(1);
6287         addTest = false;
6288       }
6289     }
6290   }
6291
6292   if (addTest) {
6293     CC = DAG.getConstant(X86::COND_NE, MVT::i8);
6294     Cond = EmitTest(Cond, X86::COND_NE, DAG);
6295   }
6296
6297   // X86ISD::CMOV means set the result (which is operand 1) to the RHS if
6298   // condition is true.
6299   SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::Flag);
6300   SDValue Ops[] = { Op2, Op1, CC, Cond };
6301   return DAG.getNode(X86ISD::CMOV, dl, VTs, Ops, array_lengthof(Ops));
6302 }
6303
6304 // isAndOrOfSingleUseSetCCs - Return true if node is an ISD::AND or
6305 // ISD::OR of two X86ISD::SETCC nodes each of which has no other use apart
6306 // from the AND / OR.
6307 static bool isAndOrOfSetCCs(SDValue Op, unsigned &Opc) {
6308   Opc = Op.getOpcode();
6309   if (Opc != ISD::OR && Opc != ISD::AND)
6310     return false;
6311   return (Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
6312           Op.getOperand(0).hasOneUse() &&
6313           Op.getOperand(1).getOpcode() == X86ISD::SETCC &&
6314           Op.getOperand(1).hasOneUse());
6315 }
6316
6317 // isXor1OfSetCC - Return true if node is an ISD::XOR of a X86ISD::SETCC and
6318 // 1 and that the SETCC node has a single use.
6319 static bool isXor1OfSetCC(SDValue Op) {
6320   if (Op.getOpcode() != ISD::XOR)
6321     return false;
6322   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
6323   if (N1C && N1C->getAPIntValue() == 1) {
6324     return Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
6325       Op.getOperand(0).hasOneUse();
6326   }
6327   return false;
6328 }
6329
6330 SDValue X86TargetLowering::LowerBRCOND(SDValue Op, SelectionDAG &DAG) {
6331   bool addTest = true;
6332   SDValue Chain = Op.getOperand(0);
6333   SDValue Cond  = Op.getOperand(1);
6334   SDValue Dest  = Op.getOperand(2);
6335   DebugLoc dl = Op.getDebugLoc();
6336   SDValue CC;
6337
6338   if (Cond.getOpcode() == ISD::SETCC) {
6339     SDValue NewCond = LowerSETCC(Cond, DAG);
6340     if (NewCond.getNode())
6341       Cond = NewCond;
6342   }
6343 #if 0
6344   // FIXME: LowerXALUO doesn't handle these!!
6345   else if (Cond.getOpcode() == X86ISD::ADD  ||
6346            Cond.getOpcode() == X86ISD::SUB  ||
6347            Cond.getOpcode() == X86ISD::SMUL ||
6348            Cond.getOpcode() == X86ISD::UMUL)
6349     Cond = LowerXALUO(Cond, DAG);
6350 #endif
6351
6352   // Look pass (and (setcc_carry (cmp ...)), 1).
6353   if (Cond.getOpcode() == ISD::AND &&
6354       Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
6355     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
6356     if (C && C->getAPIntValue() == 1) 
6357       Cond = Cond.getOperand(0);
6358   }
6359
6360   // If condition flag is set by a X86ISD::CMP, then use it as the condition
6361   // setting operand in place of the X86ISD::SETCC.
6362   if (Cond.getOpcode() == X86ISD::SETCC ||
6363       Cond.getOpcode() == X86ISD::SETCC_CARRY) {
6364     CC = Cond.getOperand(0);
6365
6366     SDValue Cmp = Cond.getOperand(1);
6367     unsigned Opc = Cmp.getOpcode();
6368     // FIXME: WHY THE SPECIAL CASING OF LogicalCmp??
6369     if (isX86LogicalCmp(Cmp) || Opc == X86ISD::BT) {
6370       Cond = Cmp;
6371       addTest = false;
6372     } else {
6373       switch (cast<ConstantSDNode>(CC)->getZExtValue()) {
6374       default: break;
6375       case X86::COND_O:
6376       case X86::COND_B:
6377         // These can only come from an arithmetic instruction with overflow,
6378         // e.g. SADDO, UADDO.
6379         Cond = Cond.getNode()->getOperand(1);
6380         addTest = false;
6381         break;
6382       }
6383     }
6384   } else {
6385     unsigned CondOpc;
6386     if (Cond.hasOneUse() && isAndOrOfSetCCs(Cond, CondOpc)) {
6387       SDValue Cmp = Cond.getOperand(0).getOperand(1);
6388       if (CondOpc == ISD::OR) {
6389         // Also, recognize the pattern generated by an FCMP_UNE. We can emit
6390         // two branches instead of an explicit OR instruction with a
6391         // separate test.
6392         if (Cmp == Cond.getOperand(1).getOperand(1) &&
6393             isX86LogicalCmp(Cmp)) {
6394           CC = Cond.getOperand(0).getOperand(0);
6395           Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
6396                               Chain, Dest, CC, Cmp);
6397           CC = Cond.getOperand(1).getOperand(0);
6398           Cond = Cmp;
6399           addTest = false;
6400         }
6401       } else { // ISD::AND
6402         // Also, recognize the pattern generated by an FCMP_OEQ. We can emit
6403         // two branches instead of an explicit AND instruction with a
6404         // separate test. However, we only do this if this block doesn't
6405         // have a fall-through edge, because this requires an explicit
6406         // jmp when the condition is false.
6407         if (Cmp == Cond.getOperand(1).getOperand(1) &&
6408             isX86LogicalCmp(Cmp) &&
6409             Op.getNode()->hasOneUse()) {
6410           X86::CondCode CCode =
6411             (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
6412           CCode = X86::GetOppositeBranchCondition(CCode);
6413           CC = DAG.getConstant(CCode, MVT::i8);
6414           SDValue User = SDValue(*Op.getNode()->use_begin(), 0);
6415           // Look for an unconditional branch following this conditional branch.
6416           // We need this because we need to reverse the successors in order
6417           // to implement FCMP_OEQ.
6418           if (User.getOpcode() == ISD::BR) {
6419             SDValue FalseBB = User.getOperand(1);
6420             SDValue NewBR =
6421               DAG.UpdateNodeOperands(User, User.getOperand(0), Dest);
6422             assert(NewBR == User);
6423             Dest = FalseBB;
6424
6425             Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
6426                                 Chain, Dest, CC, Cmp);
6427             X86::CondCode CCode =
6428               (X86::CondCode)Cond.getOperand(1).getConstantOperandVal(0);
6429             CCode = X86::GetOppositeBranchCondition(CCode);
6430             CC = DAG.getConstant(CCode, MVT::i8);
6431             Cond = Cmp;
6432             addTest = false;
6433           }
6434         }
6435       }
6436     } else if (Cond.hasOneUse() && isXor1OfSetCC(Cond)) {
6437       // Recognize for xorb (setcc), 1 patterns. The xor inverts the condition.
6438       // It should be transformed during dag combiner except when the condition
6439       // is set by a arithmetics with overflow node.
6440       X86::CondCode CCode =
6441         (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
6442       CCode = X86::GetOppositeBranchCondition(CCode);
6443       CC = DAG.getConstant(CCode, MVT::i8);
6444       Cond = Cond.getOperand(0).getOperand(1);
6445       addTest = false;
6446     }
6447   }
6448
6449   if (addTest) {
6450     // Look pass the truncate.
6451     if (Cond.getOpcode() == ISD::TRUNCATE)
6452       Cond = Cond.getOperand(0);
6453
6454     // We know the result of AND is compared against zero. Try to match
6455     // it to BT.
6456     if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) { 
6457       SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, dl, DAG);
6458       if (NewSetCC.getNode()) {
6459         CC = NewSetCC.getOperand(0);
6460         Cond = NewSetCC.getOperand(1);
6461         addTest = false;
6462       }
6463     }
6464   }
6465
6466   if (addTest) {
6467     CC = DAG.getConstant(X86::COND_NE, MVT::i8);
6468     Cond = EmitTest(Cond, X86::COND_NE, DAG);
6469   }
6470   return DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
6471                      Chain, Dest, CC, Cond);
6472 }
6473
6474
6475 // Lower dynamic stack allocation to _alloca call for Cygwin/Mingw targets.
6476 // Calls to _alloca is needed to probe the stack when allocating more than 4k
6477 // bytes in one go. Touching the stack at 4K increments is necessary to ensure
6478 // that the guard pages used by the OS virtual memory manager are allocated in
6479 // correct sequence.
6480 SDValue
6481 X86TargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
6482                                            SelectionDAG &DAG) {
6483   assert(Subtarget->isTargetCygMing() &&
6484          "This should be used only on Cygwin/Mingw targets");
6485   DebugLoc dl = Op.getDebugLoc();
6486
6487   // Get the inputs.
6488   SDValue Chain = Op.getOperand(0);
6489   SDValue Size  = Op.getOperand(1);
6490   // FIXME: Ensure alignment here
6491
6492   SDValue Flag;
6493
6494   EVT IntPtr = getPointerTy();
6495   EVT SPTy = Subtarget->is64Bit() ? MVT::i64 : MVT::i32;
6496
6497   Chain = DAG.getCopyToReg(Chain, dl, X86::EAX, Size, Flag);
6498   Flag = Chain.getValue(1);
6499
6500   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Flag);
6501
6502   Chain = DAG.getNode(X86ISD::MINGW_ALLOCA, dl, NodeTys, Chain, Flag);
6503   Flag = Chain.getValue(1);
6504
6505   Chain = DAG.getCopyFromReg(Chain, dl, X86StackPtr, SPTy).getValue(1);
6506
6507   SDValue Ops1[2] = { Chain.getValue(0), Chain };
6508   return DAG.getMergeValues(Ops1, 2, dl);
6509 }
6510
6511 SDValue
6512 X86TargetLowering::EmitTargetCodeForMemset(SelectionDAG &DAG, DebugLoc dl,
6513                                            SDValue Chain,
6514                                            SDValue Dst, SDValue Src,
6515                                            SDValue Size, unsigned Align,
6516                                            const Value *DstSV,
6517                                            uint64_t DstSVOff) {
6518   ConstantSDNode *ConstantSize = dyn_cast<ConstantSDNode>(Size);
6519
6520   // If not DWORD aligned or size is more than the threshold, call the library.
6521   // The libc version is likely to be faster for these cases. It can use the
6522   // address value and run time information about the CPU.
6523   if ((Align & 3) != 0 ||
6524       !ConstantSize ||
6525       ConstantSize->getZExtValue() >
6526         getSubtarget()->getMaxInlineSizeThreshold()) {
6527     SDValue InFlag(0, 0);
6528
6529     // Check to see if there is a specialized entry-point for memory zeroing.
6530     ConstantSDNode *V = dyn_cast<ConstantSDNode>(Src);
6531
6532     if (const char *bzeroEntry =  V &&
6533         V->isNullValue() ? Subtarget->getBZeroEntry() : 0) {
6534       EVT IntPtr = getPointerTy();
6535       const Type *IntPtrTy = TD->getIntPtrType(*DAG.getContext());
6536       TargetLowering::ArgListTy Args;
6537       TargetLowering::ArgListEntry Entry;
6538       Entry.Node = Dst;
6539       Entry.Ty = IntPtrTy;
6540       Args.push_back(Entry);
6541       Entry.Node = Size;
6542       Args.push_back(Entry);
6543       std::pair<SDValue,SDValue> CallResult =
6544         LowerCallTo(Chain, Type::getVoidTy(*DAG.getContext()),
6545                     false, false, false, false,
6546                     0, CallingConv::C, false, /*isReturnValueUsed=*/false,
6547                     DAG.getExternalSymbol(bzeroEntry, IntPtr), Args, DAG, dl);
6548       return CallResult.second;
6549     }
6550
6551     // Otherwise have the target-independent code call memset.
6552     return SDValue();
6553   }
6554
6555   uint64_t SizeVal = ConstantSize->getZExtValue();
6556   SDValue InFlag(0, 0);
6557   EVT AVT;
6558   SDValue Count;
6559   ConstantSDNode *ValC = dyn_cast<ConstantSDNode>(Src);
6560   unsigned BytesLeft = 0;
6561   bool TwoRepStos = false;
6562   if (ValC) {
6563     unsigned ValReg;
6564     uint64_t Val = ValC->getZExtValue() & 255;
6565
6566     // If the value is a constant, then we can potentially use larger sets.
6567     switch (Align & 3) {
6568     case 2:   // WORD aligned
6569       AVT = MVT::i16;
6570       ValReg = X86::AX;
6571       Val = (Val << 8) | Val;
6572       break;
6573     case 0:  // DWORD aligned
6574       AVT = MVT::i32;
6575       ValReg = X86::EAX;
6576       Val = (Val << 8)  | Val;
6577       Val = (Val << 16) | Val;
6578       if (Subtarget->is64Bit() && ((Align & 0x7) == 0)) {  // QWORD aligned
6579         AVT = MVT::i64;
6580         ValReg = X86::RAX;
6581         Val = (Val << 32) | Val;
6582       }
6583       break;
6584     default:  // Byte aligned
6585       AVT = MVT::i8;
6586       ValReg = X86::AL;
6587       Count = DAG.getIntPtrConstant(SizeVal);
6588       break;
6589     }
6590
6591     if (AVT.bitsGT(MVT::i8)) {
6592       unsigned UBytes = AVT.getSizeInBits() / 8;
6593       Count = DAG.getIntPtrConstant(SizeVal / UBytes);
6594       BytesLeft = SizeVal % UBytes;
6595     }
6596
6597     Chain  = DAG.getCopyToReg(Chain, dl, ValReg, DAG.getConstant(Val, AVT),
6598                               InFlag);
6599     InFlag = Chain.getValue(1);
6600   } else {
6601     AVT = MVT::i8;
6602     Count  = DAG.getIntPtrConstant(SizeVal);
6603     Chain  = DAG.getCopyToReg(Chain, dl, X86::AL, Src, InFlag);
6604     InFlag = Chain.getValue(1);
6605   }
6606
6607   Chain  = DAG.getCopyToReg(Chain, dl, Subtarget->is64Bit() ? X86::RCX :
6608                                                               X86::ECX,
6609                             Count, InFlag);
6610   InFlag = Chain.getValue(1);
6611   Chain  = DAG.getCopyToReg(Chain, dl, Subtarget->is64Bit() ? X86::RDI :
6612                                                               X86::EDI,
6613                             Dst, InFlag);
6614   InFlag = Chain.getValue(1);
6615
6616   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Flag);
6617   SDValue Ops[] = { Chain, DAG.getValueType(AVT), InFlag };
6618   Chain = DAG.getNode(X86ISD::REP_STOS, dl, Tys, Ops, array_lengthof(Ops));
6619
6620   if (TwoRepStos) {
6621     InFlag = Chain.getValue(1);
6622     Count  = Size;
6623     EVT CVT = Count.getValueType();
6624     SDValue Left = DAG.getNode(ISD::AND, dl, CVT, Count,
6625                                DAG.getConstant((AVT == MVT::i64) ? 7 : 3, CVT));
6626     Chain  = DAG.getCopyToReg(Chain, dl, (CVT == MVT::i64) ? X86::RCX :
6627                                                              X86::ECX,
6628                               Left, InFlag);
6629     InFlag = Chain.getValue(1);
6630     Tys = DAG.getVTList(MVT::Other, MVT::Flag);
6631     SDValue Ops[] = { Chain, DAG.getValueType(MVT::i8), InFlag };
6632     Chain = DAG.getNode(X86ISD::REP_STOS, dl, Tys, Ops, array_lengthof(Ops));
6633   } else if (BytesLeft) {
6634     // Handle the last 1 - 7 bytes.
6635     unsigned Offset = SizeVal - BytesLeft;
6636     EVT AddrVT = Dst.getValueType();
6637     EVT SizeVT = Size.getValueType();
6638
6639     Chain = DAG.getMemset(Chain, dl,
6640                           DAG.getNode(ISD::ADD, dl, AddrVT, Dst,
6641                                       DAG.getConstant(Offset, AddrVT)),
6642                           Src,
6643                           DAG.getConstant(BytesLeft, SizeVT),
6644                           Align, DstSV, DstSVOff + Offset);
6645   }
6646
6647   // TODO: Use a Tokenfactor, as in memcpy, instead of a single chain.
6648   return Chain;
6649 }
6650
6651 SDValue
6652 X86TargetLowering::EmitTargetCodeForMemcpy(SelectionDAG &DAG, DebugLoc dl,
6653                                       SDValue Chain, SDValue Dst, SDValue Src,
6654                                       SDValue Size, unsigned Align,
6655                                       bool AlwaysInline,
6656                                       const Value *DstSV, uint64_t DstSVOff,
6657                                       const Value *SrcSV, uint64_t SrcSVOff) {
6658   // This requires the copy size to be a constant, preferrably
6659   // within a subtarget-specific limit.
6660   ConstantSDNode *ConstantSize = dyn_cast<ConstantSDNode>(Size);
6661   if (!ConstantSize)
6662     return SDValue();
6663   uint64_t SizeVal = ConstantSize->getZExtValue();
6664   if (!AlwaysInline && SizeVal > getSubtarget()->getMaxInlineSizeThreshold())
6665     return SDValue();
6666
6667   /// If not DWORD aligned, call the library.
6668   if ((Align & 3) != 0)
6669     return SDValue();
6670
6671   // DWORD aligned
6672   EVT AVT = MVT::i32;
6673   if (Subtarget->is64Bit() && ((Align & 0x7) == 0))  // QWORD aligned
6674     AVT = MVT::i64;
6675
6676   unsigned UBytes = AVT.getSizeInBits() / 8;
6677   unsigned CountVal = SizeVal / UBytes;
6678   SDValue Count = DAG.getIntPtrConstant(CountVal);
6679   unsigned BytesLeft = SizeVal % UBytes;
6680
6681   SDValue InFlag(0, 0);
6682   Chain  = DAG.getCopyToReg(Chain, dl, Subtarget->is64Bit() ? X86::RCX :
6683                                                               X86::ECX,
6684                             Count, InFlag);
6685   InFlag = Chain.getValue(1);
6686   Chain  = DAG.getCopyToReg(Chain, dl, Subtarget->is64Bit() ? X86::RDI :
6687                                                              X86::EDI,
6688                             Dst, InFlag);
6689   InFlag = Chain.getValue(1);
6690   Chain  = DAG.getCopyToReg(Chain, dl, Subtarget->is64Bit() ? X86::RSI :
6691                                                               X86::ESI,
6692                             Src, InFlag);
6693   InFlag = Chain.getValue(1);
6694
6695   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Flag);
6696   SDValue Ops[] = { Chain, DAG.getValueType(AVT), InFlag };
6697   SDValue RepMovs = DAG.getNode(X86ISD::REP_MOVS, dl, Tys, Ops,
6698                                 array_lengthof(Ops));
6699
6700   SmallVector<SDValue, 4> Results;
6701   Results.push_back(RepMovs);
6702   if (BytesLeft) {
6703     // Handle the last 1 - 7 bytes.
6704     unsigned Offset = SizeVal - BytesLeft;
6705     EVT DstVT = Dst.getValueType();
6706     EVT SrcVT = Src.getValueType();
6707     EVT SizeVT = Size.getValueType();
6708     Results.push_back(DAG.getMemcpy(Chain, dl,
6709                                     DAG.getNode(ISD::ADD, dl, DstVT, Dst,
6710                                                 DAG.getConstant(Offset, DstVT)),
6711                                     DAG.getNode(ISD::ADD, dl, SrcVT, Src,
6712                                                 DAG.getConstant(Offset, SrcVT)),
6713                                     DAG.getConstant(BytesLeft, SizeVT),
6714                                     Align, AlwaysInline,
6715                                     DstSV, DstSVOff + Offset,
6716                                     SrcSV, SrcSVOff + Offset));
6717   }
6718
6719   return DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
6720                      &Results[0], Results.size());
6721 }
6722
6723 SDValue X86TargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) {
6724   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
6725   DebugLoc dl = Op.getDebugLoc();
6726
6727   if (!Subtarget->is64Bit()) {
6728     // vastart just stores the address of the VarArgsFrameIndex slot into the
6729     // memory location argument.
6730     SDValue FR = DAG.getFrameIndex(VarArgsFrameIndex, getPointerTy());
6731     return DAG.getStore(Op.getOperand(0), dl, FR, Op.getOperand(1), SV, 0,
6732                         false, false, 0);
6733   }
6734
6735   // __va_list_tag:
6736   //   gp_offset         (0 - 6 * 8)
6737   //   fp_offset         (48 - 48 + 8 * 16)
6738   //   overflow_arg_area (point to parameters coming in memory).
6739   //   reg_save_area
6740   SmallVector<SDValue, 8> MemOps;
6741   SDValue FIN = Op.getOperand(1);
6742   // Store gp_offset
6743   SDValue Store = DAG.getStore(Op.getOperand(0), dl,
6744                                DAG.getConstant(VarArgsGPOffset, MVT::i32),
6745                                FIN, SV, 0, false, false, 0);
6746   MemOps.push_back(Store);
6747
6748   // Store fp_offset
6749   FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(),
6750                     FIN, DAG.getIntPtrConstant(4));
6751   Store = DAG.getStore(Op.getOperand(0), dl,
6752                        DAG.getConstant(VarArgsFPOffset, MVT::i32),
6753                        FIN, SV, 0, false, false, 0);
6754   MemOps.push_back(Store);
6755
6756   // Store ptr to overflow_arg_area
6757   FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(),
6758                     FIN, DAG.getIntPtrConstant(4));
6759   SDValue OVFIN = DAG.getFrameIndex(VarArgsFrameIndex, getPointerTy());
6760   Store = DAG.getStore(Op.getOperand(0), dl, OVFIN, FIN, SV, 0,
6761                        false, false, 0);
6762   MemOps.push_back(Store);
6763
6764   // Store ptr to reg_save_area.
6765   FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(),
6766                     FIN, DAG.getIntPtrConstant(8));
6767   SDValue RSFIN = DAG.getFrameIndex(RegSaveFrameIndex, getPointerTy());
6768   Store = DAG.getStore(Op.getOperand(0), dl, RSFIN, FIN, SV, 0,
6769                        false, false, 0);
6770   MemOps.push_back(Store);
6771   return DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
6772                      &MemOps[0], MemOps.size());
6773 }
6774
6775 SDValue X86TargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) {
6776   // X86-64 va_list is a struct { i32, i32, i8*, i8* }.
6777   assert(Subtarget->is64Bit() && "This code only handles 64-bit va_arg!");
6778   SDValue Chain = Op.getOperand(0);
6779   SDValue SrcPtr = Op.getOperand(1);
6780   SDValue SrcSV = Op.getOperand(2);
6781
6782   llvm_report_error("VAArgInst is not yet implemented for x86-64!");
6783   return SDValue();
6784 }
6785
6786 SDValue X86TargetLowering::LowerVACOPY(SDValue Op, SelectionDAG &DAG) {
6787   // X86-64 va_list is a struct { i32, i32, i8*, i8* }.
6788   assert(Subtarget->is64Bit() && "This code only handles 64-bit va_copy!");
6789   SDValue Chain = Op.getOperand(0);
6790   SDValue DstPtr = Op.getOperand(1);
6791   SDValue SrcPtr = Op.getOperand(2);
6792   const Value *DstSV = cast<SrcValueSDNode>(Op.getOperand(3))->getValue();
6793   const Value *SrcSV = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
6794   DebugLoc dl = Op.getDebugLoc();
6795
6796   return DAG.getMemcpy(Chain, dl, DstPtr, SrcPtr,
6797                        DAG.getIntPtrConstant(24), 8, false,
6798                        DstSV, 0, SrcSV, 0);
6799 }
6800
6801 SDValue
6802 X86TargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op, SelectionDAG &DAG) {
6803   DebugLoc dl = Op.getDebugLoc();
6804   unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
6805   switch (IntNo) {
6806   default: return SDValue();    // Don't custom lower most intrinsics.
6807   // Comparison intrinsics.
6808   case Intrinsic::x86_sse_comieq_ss:
6809   case Intrinsic::x86_sse_comilt_ss:
6810   case Intrinsic::x86_sse_comile_ss:
6811   case Intrinsic::x86_sse_comigt_ss:
6812   case Intrinsic::x86_sse_comige_ss:
6813   case Intrinsic::x86_sse_comineq_ss:
6814   case Intrinsic::x86_sse_ucomieq_ss:
6815   case Intrinsic::x86_sse_ucomilt_ss:
6816   case Intrinsic::x86_sse_ucomile_ss:
6817   case Intrinsic::x86_sse_ucomigt_ss:
6818   case Intrinsic::x86_sse_ucomige_ss:
6819   case Intrinsic::x86_sse_ucomineq_ss:
6820   case Intrinsic::x86_sse2_comieq_sd:
6821   case Intrinsic::x86_sse2_comilt_sd:
6822   case Intrinsic::x86_sse2_comile_sd:
6823   case Intrinsic::x86_sse2_comigt_sd:
6824   case Intrinsic::x86_sse2_comige_sd:
6825   case Intrinsic::x86_sse2_comineq_sd:
6826   case Intrinsic::x86_sse2_ucomieq_sd:
6827   case Intrinsic::x86_sse2_ucomilt_sd:
6828   case Intrinsic::x86_sse2_ucomile_sd:
6829   case Intrinsic::x86_sse2_ucomigt_sd:
6830   case Intrinsic::x86_sse2_ucomige_sd:
6831   case Intrinsic::x86_sse2_ucomineq_sd: {
6832     unsigned Opc = 0;
6833     ISD::CondCode CC = ISD::SETCC_INVALID;
6834     switch (IntNo) {
6835     default: break;
6836     case Intrinsic::x86_sse_comieq_ss:
6837     case Intrinsic::x86_sse2_comieq_sd:
6838       Opc = X86ISD::COMI;
6839       CC = ISD::SETEQ;
6840       break;
6841     case Intrinsic::x86_sse_comilt_ss:
6842     case Intrinsic::x86_sse2_comilt_sd:
6843       Opc = X86ISD::COMI;
6844       CC = ISD::SETLT;
6845       break;
6846     case Intrinsic::x86_sse_comile_ss:
6847     case Intrinsic::x86_sse2_comile_sd:
6848       Opc = X86ISD::COMI;
6849       CC = ISD::SETLE;
6850       break;
6851     case Intrinsic::x86_sse_comigt_ss:
6852     case Intrinsic::x86_sse2_comigt_sd:
6853       Opc = X86ISD::COMI;
6854       CC = ISD::SETGT;
6855       break;
6856     case Intrinsic::x86_sse_comige_ss:
6857     case Intrinsic::x86_sse2_comige_sd:
6858       Opc = X86ISD::COMI;
6859       CC = ISD::SETGE;
6860       break;
6861     case Intrinsic::x86_sse_comineq_ss:
6862     case Intrinsic::x86_sse2_comineq_sd:
6863       Opc = X86ISD::COMI;
6864       CC = ISD::SETNE;
6865       break;
6866     case Intrinsic::x86_sse_ucomieq_ss:
6867     case Intrinsic::x86_sse2_ucomieq_sd:
6868       Opc = X86ISD::UCOMI;
6869       CC = ISD::SETEQ;
6870       break;
6871     case Intrinsic::x86_sse_ucomilt_ss:
6872     case Intrinsic::x86_sse2_ucomilt_sd:
6873       Opc = X86ISD::UCOMI;
6874       CC = ISD::SETLT;
6875       break;
6876     case Intrinsic::x86_sse_ucomile_ss:
6877     case Intrinsic::x86_sse2_ucomile_sd:
6878       Opc = X86ISD::UCOMI;
6879       CC = ISD::SETLE;
6880       break;
6881     case Intrinsic::x86_sse_ucomigt_ss:
6882     case Intrinsic::x86_sse2_ucomigt_sd:
6883       Opc = X86ISD::UCOMI;
6884       CC = ISD::SETGT;
6885       break;
6886     case Intrinsic::x86_sse_ucomige_ss:
6887     case Intrinsic::x86_sse2_ucomige_sd:
6888       Opc = X86ISD::UCOMI;
6889       CC = ISD::SETGE;
6890       break;
6891     case Intrinsic::x86_sse_ucomineq_ss:
6892     case Intrinsic::x86_sse2_ucomineq_sd:
6893       Opc = X86ISD::UCOMI;
6894       CC = ISD::SETNE;
6895       break;
6896     }
6897
6898     SDValue LHS = Op.getOperand(1);
6899     SDValue RHS = Op.getOperand(2);
6900     unsigned X86CC = TranslateX86CC(CC, true, LHS, RHS, DAG);
6901     assert(X86CC != X86::COND_INVALID && "Unexpected illegal condition!");
6902     SDValue Cond = DAG.getNode(Opc, dl, MVT::i32, LHS, RHS);
6903     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
6904                                 DAG.getConstant(X86CC, MVT::i8), Cond);
6905     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
6906   }
6907   // ptest intrinsics. The intrinsic these come from are designed to return
6908   // an integer value, not just an instruction so lower it to the ptest
6909   // pattern and a setcc for the result.
6910   case Intrinsic::x86_sse41_ptestz:
6911   case Intrinsic::x86_sse41_ptestc:
6912   case Intrinsic::x86_sse41_ptestnzc:{
6913     unsigned X86CC = 0;
6914     switch (IntNo) {
6915     default: llvm_unreachable("Bad fallthrough in Intrinsic lowering.");
6916     case Intrinsic::x86_sse41_ptestz:
6917       // ZF = 1
6918       X86CC = X86::COND_E;
6919       break;
6920     case Intrinsic::x86_sse41_ptestc:
6921       // CF = 1
6922       X86CC = X86::COND_B;
6923       break;
6924     case Intrinsic::x86_sse41_ptestnzc:
6925       // ZF and CF = 0
6926       X86CC = X86::COND_A;
6927       break;
6928     }
6929
6930     SDValue LHS = Op.getOperand(1);
6931     SDValue RHS = Op.getOperand(2);
6932     SDValue Test = DAG.getNode(X86ISD::PTEST, dl, MVT::i32, LHS, RHS);
6933     SDValue CC = DAG.getConstant(X86CC, MVT::i8);
6934     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8, CC, Test);
6935     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
6936   }
6937
6938   // Fix vector shift instructions where the last operand is a non-immediate
6939   // i32 value.
6940   case Intrinsic::x86_sse2_pslli_w:
6941   case Intrinsic::x86_sse2_pslli_d:
6942   case Intrinsic::x86_sse2_pslli_q:
6943   case Intrinsic::x86_sse2_psrli_w:
6944   case Intrinsic::x86_sse2_psrli_d:
6945   case Intrinsic::x86_sse2_psrli_q:
6946   case Intrinsic::x86_sse2_psrai_w:
6947   case Intrinsic::x86_sse2_psrai_d:
6948   case Intrinsic::x86_mmx_pslli_w:
6949   case Intrinsic::x86_mmx_pslli_d:
6950   case Intrinsic::x86_mmx_pslli_q:
6951   case Intrinsic::x86_mmx_psrli_w:
6952   case Intrinsic::x86_mmx_psrli_d:
6953   case Intrinsic::x86_mmx_psrli_q:
6954   case Intrinsic::x86_mmx_psrai_w:
6955   case Intrinsic::x86_mmx_psrai_d: {
6956     SDValue ShAmt = Op.getOperand(2);
6957     if (isa<ConstantSDNode>(ShAmt))
6958       return SDValue();
6959
6960     unsigned NewIntNo = 0;
6961     EVT ShAmtVT = MVT::v4i32;
6962     switch (IntNo) {
6963     case Intrinsic::x86_sse2_pslli_w:
6964       NewIntNo = Intrinsic::x86_sse2_psll_w;
6965       break;
6966     case Intrinsic::x86_sse2_pslli_d:
6967       NewIntNo = Intrinsic::x86_sse2_psll_d;
6968       break;
6969     case Intrinsic::x86_sse2_pslli_q:
6970       NewIntNo = Intrinsic::x86_sse2_psll_q;
6971       break;
6972     case Intrinsic::x86_sse2_psrli_w:
6973       NewIntNo = Intrinsic::x86_sse2_psrl_w;
6974       break;
6975     case Intrinsic::x86_sse2_psrli_d:
6976       NewIntNo = Intrinsic::x86_sse2_psrl_d;
6977       break;
6978     case Intrinsic::x86_sse2_psrli_q:
6979       NewIntNo = Intrinsic::x86_sse2_psrl_q;
6980       break;
6981     case Intrinsic::x86_sse2_psrai_w:
6982       NewIntNo = Intrinsic::x86_sse2_psra_w;
6983       break;
6984     case Intrinsic::x86_sse2_psrai_d:
6985       NewIntNo = Intrinsic::x86_sse2_psra_d;
6986       break;
6987     default: {
6988       ShAmtVT = MVT::v2i32;
6989       switch (IntNo) {
6990       case Intrinsic::x86_mmx_pslli_w:
6991         NewIntNo = Intrinsic::x86_mmx_psll_w;
6992         break;
6993       case Intrinsic::x86_mmx_pslli_d:
6994         NewIntNo = Intrinsic::x86_mmx_psll_d;
6995         break;
6996       case Intrinsic::x86_mmx_pslli_q:
6997         NewIntNo = Intrinsic::x86_mmx_psll_q;
6998         break;
6999       case Intrinsic::x86_mmx_psrli_w:
7000         NewIntNo = Intrinsic::x86_mmx_psrl_w;
7001         break;
7002       case Intrinsic::x86_mmx_psrli_d:
7003         NewIntNo = Intrinsic::x86_mmx_psrl_d;
7004         break;
7005       case Intrinsic::x86_mmx_psrli_q:
7006         NewIntNo = Intrinsic::x86_mmx_psrl_q;
7007         break;
7008       case Intrinsic::x86_mmx_psrai_w:
7009         NewIntNo = Intrinsic::x86_mmx_psra_w;
7010         break;
7011       case Intrinsic::x86_mmx_psrai_d:
7012         NewIntNo = Intrinsic::x86_mmx_psra_d;
7013         break;
7014       default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
7015       }
7016       break;
7017     }
7018     }
7019
7020     // The vector shift intrinsics with scalars uses 32b shift amounts but
7021     // the sse2/mmx shift instructions reads 64 bits. Set the upper 32 bits
7022     // to be zero.
7023     SDValue ShOps[4];
7024     ShOps[0] = ShAmt;
7025     ShOps[1] = DAG.getConstant(0, MVT::i32);
7026     if (ShAmtVT == MVT::v4i32) {
7027       ShOps[2] = DAG.getUNDEF(MVT::i32);
7028       ShOps[3] = DAG.getUNDEF(MVT::i32);
7029       ShAmt =  DAG.getNode(ISD::BUILD_VECTOR, dl, ShAmtVT, &ShOps[0], 4);
7030     } else {
7031       ShAmt =  DAG.getNode(ISD::BUILD_VECTOR, dl, ShAmtVT, &ShOps[0], 2);
7032     }
7033
7034     EVT VT = Op.getValueType();
7035     ShAmt = DAG.getNode(ISD::BIT_CONVERT, dl, VT, ShAmt);
7036     return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
7037                        DAG.getConstant(NewIntNo, MVT::i32),
7038                        Op.getOperand(1), ShAmt);
7039   }
7040   }
7041 }
7042
7043 SDValue X86TargetLowering::LowerRETURNADDR(SDValue Op, SelectionDAG &DAG) {
7044   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
7045   DebugLoc dl = Op.getDebugLoc();
7046
7047   if (Depth > 0) {
7048     SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
7049     SDValue Offset =
7050       DAG.getConstant(TD->getPointerSize(),
7051                       Subtarget->is64Bit() ? MVT::i64 : MVT::i32);
7052     return DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(),
7053                        DAG.getNode(ISD::ADD, dl, getPointerTy(),
7054                                    FrameAddr, Offset),
7055                        NULL, 0, false, false, 0);
7056   }
7057
7058   // Just load the return address.
7059   SDValue RetAddrFI = getReturnAddressFrameIndex(DAG);
7060   return DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(),
7061                      RetAddrFI, NULL, 0, false, false, 0);
7062 }
7063
7064 SDValue X86TargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) {
7065   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
7066   MFI->setFrameAddressIsTaken(true);
7067   EVT VT = Op.getValueType();
7068   DebugLoc dl = Op.getDebugLoc();  // FIXME probably not meaningful
7069   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
7070   unsigned FrameReg = Subtarget->is64Bit() ? X86::RBP : X86::EBP;
7071   SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
7072   while (Depth--)
7073     FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr, NULL, 0,
7074                             false, false, 0);
7075   return FrameAddr;
7076 }
7077
7078 SDValue X86TargetLowering::LowerFRAME_TO_ARGS_OFFSET(SDValue Op,
7079                                                      SelectionDAG &DAG) {
7080   return DAG.getIntPtrConstant(2*TD->getPointerSize());
7081 }
7082
7083 SDValue X86TargetLowering::LowerEH_RETURN(SDValue Op, SelectionDAG &DAG)
7084 {
7085   MachineFunction &MF = DAG.getMachineFunction();
7086   SDValue Chain     = Op.getOperand(0);
7087   SDValue Offset    = Op.getOperand(1);
7088   SDValue Handler   = Op.getOperand(2);
7089   DebugLoc dl       = Op.getDebugLoc();
7090
7091   SDValue Frame = DAG.getRegister(Subtarget->is64Bit() ? X86::RBP : X86::EBP,
7092                                   getPointerTy());
7093   unsigned StoreAddrReg = (Subtarget->is64Bit() ? X86::RCX : X86::ECX);
7094
7095   SDValue StoreAddr = DAG.getNode(ISD::SUB, dl, getPointerTy(), Frame,
7096                                   DAG.getIntPtrConstant(-TD->getPointerSize()));
7097   StoreAddr = DAG.getNode(ISD::ADD, dl, getPointerTy(), StoreAddr, Offset);
7098   Chain = DAG.getStore(Chain, dl, Handler, StoreAddr, NULL, 0, false, false, 0);
7099   Chain = DAG.getCopyToReg(Chain, dl, StoreAddrReg, StoreAddr);
7100   MF.getRegInfo().addLiveOut(StoreAddrReg);
7101
7102   return DAG.getNode(X86ISD::EH_RETURN, dl,
7103                      MVT::Other,
7104                      Chain, DAG.getRegister(StoreAddrReg, getPointerTy()));
7105 }
7106
7107 SDValue X86TargetLowering::LowerTRAMPOLINE(SDValue Op,
7108                                              SelectionDAG &DAG) {
7109   SDValue Root = Op.getOperand(0);
7110   SDValue Trmp = Op.getOperand(1); // trampoline
7111   SDValue FPtr = Op.getOperand(2); // nested function
7112   SDValue Nest = Op.getOperand(3); // 'nest' parameter value
7113   DebugLoc dl  = Op.getDebugLoc();
7114
7115   const Value *TrmpAddr = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
7116
7117   if (Subtarget->is64Bit()) {
7118     SDValue OutChains[6];
7119
7120     // Large code-model.
7121     const unsigned char JMP64r  = 0xFF; // 64-bit jmp through register opcode.
7122     const unsigned char MOV64ri = 0xB8; // X86::MOV64ri opcode.
7123
7124     const unsigned char N86R10 = RegInfo->getX86RegNum(X86::R10);
7125     const unsigned char N86R11 = RegInfo->getX86RegNum(X86::R11);
7126
7127     const unsigned char REX_WB = 0x40 | 0x08 | 0x01; // REX prefix
7128
7129     // Load the pointer to the nested function into R11.
7130     unsigned OpCode = ((MOV64ri | N86R11) << 8) | REX_WB; // movabsq r11
7131     SDValue Addr = Trmp;
7132     OutChains[0] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
7133                                 Addr, TrmpAddr, 0, false, false, 0);
7134
7135     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
7136                        DAG.getConstant(2, MVT::i64));
7137     OutChains[1] = DAG.getStore(Root, dl, FPtr, Addr, TrmpAddr, 2,
7138                                 false, false, 2);
7139
7140     // Load the 'nest' parameter value into R10.
7141     // R10 is specified in X86CallingConv.td
7142     OpCode = ((MOV64ri | N86R10) << 8) | REX_WB; // movabsq r10
7143     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
7144                        DAG.getConstant(10, MVT::i64));
7145     OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
7146                                 Addr, TrmpAddr, 10, false, false, 0);
7147
7148     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
7149                        DAG.getConstant(12, MVT::i64));
7150     OutChains[3] = DAG.getStore(Root, dl, Nest, Addr, TrmpAddr, 12,
7151                                 false, false, 2);
7152
7153     // Jump to the nested function.
7154     OpCode = (JMP64r << 8) | REX_WB; // jmpq *...
7155     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
7156                        DAG.getConstant(20, MVT::i64));
7157     OutChains[4] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
7158                                 Addr, TrmpAddr, 20, false, false, 0);
7159
7160     unsigned char ModRM = N86R11 | (4 << 3) | (3 << 6); // ...r11
7161     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
7162                        DAG.getConstant(22, MVT::i64));
7163     OutChains[5] = DAG.getStore(Root, dl, DAG.getConstant(ModRM, MVT::i8), Addr,
7164                                 TrmpAddr, 22, false, false, 0);
7165
7166     SDValue Ops[] =
7167       { Trmp, DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains, 6) };
7168     return DAG.getMergeValues(Ops, 2, dl);
7169   } else {
7170     const Function *Func =
7171       cast<Function>(cast<SrcValueSDNode>(Op.getOperand(5))->getValue());
7172     CallingConv::ID CC = Func->getCallingConv();
7173     unsigned NestReg;
7174
7175     switch (CC) {
7176     default:
7177       llvm_unreachable("Unsupported calling convention");
7178     case CallingConv::C:
7179     case CallingConv::X86_StdCall: {
7180       // Pass 'nest' parameter in ECX.
7181       // Must be kept in sync with X86CallingConv.td
7182       NestReg = X86::ECX;
7183
7184       // Check that ECX wasn't needed by an 'inreg' parameter.
7185       const FunctionType *FTy = Func->getFunctionType();
7186       const AttrListPtr &Attrs = Func->getAttributes();
7187
7188       if (!Attrs.isEmpty() && !Func->isVarArg()) {
7189         unsigned InRegCount = 0;
7190         unsigned Idx = 1;
7191
7192         for (FunctionType::param_iterator I = FTy->param_begin(),
7193              E = FTy->param_end(); I != E; ++I, ++Idx)
7194           if (Attrs.paramHasAttr(Idx, Attribute::InReg))
7195             // FIXME: should only count parameters that are lowered to integers.
7196             InRegCount += (TD->getTypeSizeInBits(*I) + 31) / 32;
7197
7198         if (InRegCount > 2) {
7199           llvm_report_error("Nest register in use - reduce number of inreg parameters!");
7200         }
7201       }
7202       break;
7203     }
7204     case CallingConv::X86_FastCall:
7205     case CallingConv::Fast:
7206       // Pass 'nest' parameter in EAX.
7207       // Must be kept in sync with X86CallingConv.td
7208       NestReg = X86::EAX;
7209       break;
7210     }
7211
7212     SDValue OutChains[4];
7213     SDValue Addr, Disp;
7214
7215     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
7216                        DAG.getConstant(10, MVT::i32));
7217     Disp = DAG.getNode(ISD::SUB, dl, MVT::i32, FPtr, Addr);
7218
7219     // This is storing the opcode for MOV32ri.
7220     const unsigned char MOV32ri = 0xB8; // X86::MOV32ri's opcode byte.
7221     const unsigned char N86Reg = RegInfo->getX86RegNum(NestReg);
7222     OutChains[0] = DAG.getStore(Root, dl,
7223                                 DAG.getConstant(MOV32ri|N86Reg, MVT::i8),
7224                                 Trmp, TrmpAddr, 0, false, false, 0);
7225
7226     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
7227                        DAG.getConstant(1, MVT::i32));
7228     OutChains[1] = DAG.getStore(Root, dl, Nest, Addr, TrmpAddr, 1,
7229                                 false, false, 1);
7230
7231     const unsigned char JMP = 0xE9; // jmp <32bit dst> opcode.
7232     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
7233                        DAG.getConstant(5, MVT::i32));
7234     OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(JMP, MVT::i8), Addr,
7235                                 TrmpAddr, 5, false, false, 1);
7236
7237     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
7238                        DAG.getConstant(6, MVT::i32));
7239     OutChains[3] = DAG.getStore(Root, dl, Disp, Addr, TrmpAddr, 6,
7240                                 false, false, 1);
7241
7242     SDValue Ops[] =
7243       { Trmp, DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains, 4) };
7244     return DAG.getMergeValues(Ops, 2, dl);
7245   }
7246 }
7247
7248 SDValue X86TargetLowering::LowerFLT_ROUNDS_(SDValue Op, SelectionDAG &DAG) {
7249   /*
7250    The rounding mode is in bits 11:10 of FPSR, and has the following
7251    settings:
7252      00 Round to nearest
7253      01 Round to -inf
7254      10 Round to +inf
7255      11 Round to 0
7256
7257   FLT_ROUNDS, on the other hand, expects the following:
7258     -1 Undefined
7259      0 Round to 0
7260      1 Round to nearest
7261      2 Round to +inf
7262      3 Round to -inf
7263
7264   To perform the conversion, we do:
7265     (((((FPSR & 0x800) >> 11) | ((FPSR & 0x400) >> 9)) + 1) & 3)
7266   */
7267
7268   MachineFunction &MF = DAG.getMachineFunction();
7269   const TargetMachine &TM = MF.getTarget();
7270   const TargetFrameInfo &TFI = *TM.getFrameInfo();
7271   unsigned StackAlignment = TFI.getStackAlignment();
7272   EVT VT = Op.getValueType();
7273   DebugLoc dl = Op.getDebugLoc();
7274
7275   // Save FP Control Word to stack slot
7276   int SSFI = MF.getFrameInfo()->CreateStackObject(2, StackAlignment, false);
7277   SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
7278
7279   SDValue Chain = DAG.getNode(X86ISD::FNSTCW16m, dl, MVT::Other,
7280                               DAG.getEntryNode(), StackSlot);
7281
7282   // Load FP Control Word from stack slot
7283   SDValue CWD = DAG.getLoad(MVT::i16, dl, Chain, StackSlot, NULL, 0,
7284                             false, false, 0);
7285
7286   // Transform as necessary
7287   SDValue CWD1 =
7288     DAG.getNode(ISD::SRL, dl, MVT::i16,
7289                 DAG.getNode(ISD::AND, dl, MVT::i16,
7290                             CWD, DAG.getConstant(0x800, MVT::i16)),
7291                 DAG.getConstant(11, MVT::i8));
7292   SDValue CWD2 =
7293     DAG.getNode(ISD::SRL, dl, MVT::i16,
7294                 DAG.getNode(ISD::AND, dl, MVT::i16,
7295                             CWD, DAG.getConstant(0x400, MVT::i16)),
7296                 DAG.getConstant(9, MVT::i8));
7297
7298   SDValue RetVal =
7299     DAG.getNode(ISD::AND, dl, MVT::i16,
7300                 DAG.getNode(ISD::ADD, dl, MVT::i16,
7301                             DAG.getNode(ISD::OR, dl, MVT::i16, CWD1, CWD2),
7302                             DAG.getConstant(1, MVT::i16)),
7303                 DAG.getConstant(3, MVT::i16));
7304
7305
7306   return DAG.getNode((VT.getSizeInBits() < 16 ?
7307                       ISD::TRUNCATE : ISD::ZERO_EXTEND), dl, VT, RetVal);
7308 }
7309
7310 SDValue X86TargetLowering::LowerCTLZ(SDValue Op, SelectionDAG &DAG) {
7311   EVT VT = Op.getValueType();
7312   EVT OpVT = VT;
7313   unsigned NumBits = VT.getSizeInBits();
7314   DebugLoc dl = Op.getDebugLoc();
7315
7316   Op = Op.getOperand(0);
7317   if (VT == MVT::i8) {
7318     // Zero extend to i32 since there is not an i8 bsr.
7319     OpVT = MVT::i32;
7320     Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
7321   }
7322
7323   // Issue a bsr (scan bits in reverse) which also sets EFLAGS.
7324   SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
7325   Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
7326
7327   // If src is zero (i.e. bsr sets ZF), returns NumBits.
7328   SDValue Ops[] = {
7329     Op,
7330     DAG.getConstant(NumBits+NumBits-1, OpVT),
7331     DAG.getConstant(X86::COND_E, MVT::i8),
7332     Op.getValue(1)
7333   };
7334   Op = DAG.getNode(X86ISD::CMOV, dl, OpVT, Ops, array_lengthof(Ops));
7335
7336   // Finally xor with NumBits-1.
7337   Op = DAG.getNode(ISD::XOR, dl, OpVT, Op, DAG.getConstant(NumBits-1, OpVT));
7338
7339   if (VT == MVT::i8)
7340     Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
7341   return Op;
7342 }
7343
7344 SDValue X86TargetLowering::LowerCTTZ(SDValue Op, SelectionDAG &DAG) {
7345   EVT VT = Op.getValueType();
7346   EVT OpVT = VT;
7347   unsigned NumBits = VT.getSizeInBits();
7348   DebugLoc dl = Op.getDebugLoc();
7349
7350   Op = Op.getOperand(0);
7351   if (VT == MVT::i8) {
7352     OpVT = MVT::i32;
7353     Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
7354   }
7355
7356   // Issue a bsf (scan bits forward) which also sets EFLAGS.
7357   SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
7358   Op = DAG.getNode(X86ISD::BSF, dl, VTs, Op);
7359
7360   // If src is zero (i.e. bsf sets ZF), returns NumBits.
7361   SDValue Ops[] = {
7362     Op,
7363     DAG.getConstant(NumBits, OpVT),
7364     DAG.getConstant(X86::COND_E, MVT::i8),
7365     Op.getValue(1)
7366   };
7367   Op = DAG.getNode(X86ISD::CMOV, dl, OpVT, Ops, array_lengthof(Ops));
7368
7369   if (VT == MVT::i8)
7370     Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
7371   return Op;
7372 }
7373
7374 SDValue X86TargetLowering::LowerMUL_V2I64(SDValue Op, SelectionDAG &DAG) {
7375   EVT VT = Op.getValueType();
7376   assert(VT == MVT::v2i64 && "Only know how to lower V2I64 multiply");
7377   DebugLoc dl = Op.getDebugLoc();
7378
7379   //  ulong2 Ahi = __builtin_ia32_psrlqi128( a, 32);
7380   //  ulong2 Bhi = __builtin_ia32_psrlqi128( b, 32);
7381   //  ulong2 AloBlo = __builtin_ia32_pmuludq128( a, b );
7382   //  ulong2 AloBhi = __builtin_ia32_pmuludq128( a, Bhi );
7383   //  ulong2 AhiBlo = __builtin_ia32_pmuludq128( Ahi, b );
7384   //
7385   //  AloBhi = __builtin_ia32_psllqi128( AloBhi, 32 );
7386   //  AhiBlo = __builtin_ia32_psllqi128( AhiBlo, 32 );
7387   //  return AloBlo + AloBhi + AhiBlo;
7388
7389   SDValue A = Op.getOperand(0);
7390   SDValue B = Op.getOperand(1);
7391
7392   SDValue Ahi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
7393                        DAG.getConstant(Intrinsic::x86_sse2_psrli_q, MVT::i32),
7394                        A, DAG.getConstant(32, MVT::i32));
7395   SDValue Bhi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
7396                        DAG.getConstant(Intrinsic::x86_sse2_psrli_q, MVT::i32),
7397                        B, DAG.getConstant(32, MVT::i32));
7398   SDValue AloBlo = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
7399                        DAG.getConstant(Intrinsic::x86_sse2_pmulu_dq, MVT::i32),
7400                        A, B);
7401   SDValue AloBhi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
7402                        DAG.getConstant(Intrinsic::x86_sse2_pmulu_dq, MVT::i32),
7403                        A, Bhi);
7404   SDValue AhiBlo = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
7405                        DAG.getConstant(Intrinsic::x86_sse2_pmulu_dq, MVT::i32),
7406                        Ahi, B);
7407   AloBhi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
7408                        DAG.getConstant(Intrinsic::x86_sse2_pslli_q, MVT::i32),
7409                        AloBhi, DAG.getConstant(32, MVT::i32));
7410   AhiBlo = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
7411                        DAG.getConstant(Intrinsic::x86_sse2_pslli_q, MVT::i32),
7412                        AhiBlo, DAG.getConstant(32, MVT::i32));
7413   SDValue Res = DAG.getNode(ISD::ADD, dl, VT, AloBlo, AloBhi);
7414   Res = DAG.getNode(ISD::ADD, dl, VT, Res, AhiBlo);
7415   return Res;
7416 }
7417
7418
7419 SDValue X86TargetLowering::LowerXALUO(SDValue Op, SelectionDAG &DAG) {
7420   // Lower the "add/sub/mul with overflow" instruction into a regular ins plus
7421   // a "setcc" instruction that checks the overflow flag. The "brcond" lowering
7422   // looks for this combo and may remove the "setcc" instruction if the "setcc"
7423   // has only one use.
7424   SDNode *N = Op.getNode();
7425   SDValue LHS = N->getOperand(0);
7426   SDValue RHS = N->getOperand(1);
7427   unsigned BaseOp = 0;
7428   unsigned Cond = 0;
7429   DebugLoc dl = Op.getDebugLoc();
7430
7431   switch (Op.getOpcode()) {
7432   default: llvm_unreachable("Unknown ovf instruction!");
7433   case ISD::SADDO:
7434     // A subtract of one will be selected as a INC. Note that INC doesn't
7435     // set CF, so we can't do this for UADDO.
7436     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op))
7437       if (C->getAPIntValue() == 1) {
7438         BaseOp = X86ISD::INC;
7439         Cond = X86::COND_O;
7440         break;
7441       }
7442     BaseOp = X86ISD::ADD;
7443     Cond = X86::COND_O;
7444     break;
7445   case ISD::UADDO:
7446     BaseOp = X86ISD::ADD;
7447     Cond = X86::COND_B;
7448     break;
7449   case ISD::SSUBO:
7450     // A subtract of one will be selected as a DEC. Note that DEC doesn't
7451     // set CF, so we can't do this for USUBO.
7452     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op))
7453       if (C->getAPIntValue() == 1) {
7454         BaseOp = X86ISD::DEC;
7455         Cond = X86::COND_O;
7456         break;
7457       }
7458     BaseOp = X86ISD::SUB;
7459     Cond = X86::COND_O;
7460     break;
7461   case ISD::USUBO:
7462     BaseOp = X86ISD::SUB;
7463     Cond = X86::COND_B;
7464     break;
7465   case ISD::SMULO:
7466     BaseOp = X86ISD::SMUL;
7467     Cond = X86::COND_O;
7468     break;
7469   case ISD::UMULO:
7470     BaseOp = X86ISD::UMUL;
7471     Cond = X86::COND_B;
7472     break;
7473   }
7474
7475   // Also sets EFLAGS.
7476   SDVTList VTs = DAG.getVTList(N->getValueType(0), MVT::i32);
7477   SDValue Sum = DAG.getNode(BaseOp, dl, VTs, LHS, RHS);
7478
7479   SDValue SetCC =
7480     DAG.getNode(X86ISD::SETCC, dl, N->getValueType(1),
7481                 DAG.getConstant(Cond, MVT::i32), SDValue(Sum.getNode(), 1));
7482
7483   DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), SetCC);
7484   return Sum;
7485 }
7486
7487 SDValue X86TargetLowering::LowerCMP_SWAP(SDValue Op, SelectionDAG &DAG) {
7488   EVT T = Op.getValueType();
7489   DebugLoc dl = Op.getDebugLoc();
7490   unsigned Reg = 0;
7491   unsigned size = 0;
7492   switch(T.getSimpleVT().SimpleTy) {
7493   default:
7494     assert(false && "Invalid value type!");
7495   case MVT::i8:  Reg = X86::AL;  size = 1; break;
7496   case MVT::i16: Reg = X86::AX;  size = 2; break;
7497   case MVT::i32: Reg = X86::EAX; size = 4; break;
7498   case MVT::i64:
7499     assert(Subtarget->is64Bit() && "Node not type legal!");
7500     Reg = X86::RAX; size = 8;
7501     break;
7502   }
7503   SDValue cpIn = DAG.getCopyToReg(Op.getOperand(0), dl, Reg,
7504                                     Op.getOperand(2), SDValue());
7505   SDValue Ops[] = { cpIn.getValue(0),
7506                     Op.getOperand(1),
7507                     Op.getOperand(3),
7508                     DAG.getTargetConstant(size, MVT::i8),
7509                     cpIn.getValue(1) };
7510   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Flag);
7511   SDValue Result = DAG.getNode(X86ISD::LCMPXCHG_DAG, dl, Tys, Ops, 5);
7512   SDValue cpOut =
7513     DAG.getCopyFromReg(Result.getValue(0), dl, Reg, T, Result.getValue(1));
7514   return cpOut;
7515 }
7516
7517 SDValue X86TargetLowering::LowerREADCYCLECOUNTER(SDValue Op,
7518                                                  SelectionDAG &DAG) {
7519   assert(Subtarget->is64Bit() && "Result not type legalized?");
7520   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Flag);
7521   SDValue TheChain = Op.getOperand(0);
7522   DebugLoc dl = Op.getDebugLoc();
7523   SDValue rd = DAG.getNode(X86ISD::RDTSC_DAG, dl, Tys, &TheChain, 1);
7524   SDValue rax = DAG.getCopyFromReg(rd, dl, X86::RAX, MVT::i64, rd.getValue(1));
7525   SDValue rdx = DAG.getCopyFromReg(rax.getValue(1), dl, X86::RDX, MVT::i64,
7526                                    rax.getValue(2));
7527   SDValue Tmp = DAG.getNode(ISD::SHL, dl, MVT::i64, rdx,
7528                             DAG.getConstant(32, MVT::i8));
7529   SDValue Ops[] = {
7530     DAG.getNode(ISD::OR, dl, MVT::i64, rax, Tmp),
7531     rdx.getValue(1)
7532   };
7533   return DAG.getMergeValues(Ops, 2, dl);
7534 }
7535
7536 SDValue X86TargetLowering::LowerLOAD_SUB(SDValue Op, SelectionDAG &DAG) {
7537   SDNode *Node = Op.getNode();
7538   DebugLoc dl = Node->getDebugLoc();
7539   EVT T = Node->getValueType(0);
7540   SDValue negOp = DAG.getNode(ISD::SUB, dl, T,
7541                               DAG.getConstant(0, T), Node->getOperand(2));
7542   return DAG.getAtomic(ISD::ATOMIC_LOAD_ADD, dl,
7543                        cast<AtomicSDNode>(Node)->getMemoryVT(),
7544                        Node->getOperand(0),
7545                        Node->getOperand(1), negOp,
7546                        cast<AtomicSDNode>(Node)->getSrcValue(),
7547                        cast<AtomicSDNode>(Node)->getAlignment());
7548 }
7549
7550 /// LowerOperation - Provide custom lowering hooks for some operations.
7551 ///
7552 SDValue X86TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) {
7553   switch (Op.getOpcode()) {
7554   default: llvm_unreachable("Should not custom lower this!");
7555   case ISD::ATOMIC_CMP_SWAP:    return LowerCMP_SWAP(Op,DAG);
7556   case ISD::ATOMIC_LOAD_SUB:    return LowerLOAD_SUB(Op,DAG);
7557   case ISD::BUILD_VECTOR:       return LowerBUILD_VECTOR(Op, DAG);
7558   case ISD::CONCAT_VECTORS:     return LowerCONCAT_VECTORS(Op, DAG);
7559   case ISD::VECTOR_SHUFFLE:     return LowerVECTOR_SHUFFLE(Op, DAG);
7560   case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
7561   case ISD::INSERT_VECTOR_ELT:  return LowerINSERT_VECTOR_ELT(Op, DAG);
7562   case ISD::SCALAR_TO_VECTOR:   return LowerSCALAR_TO_VECTOR(Op, DAG);
7563   case ISD::ConstantPool:       return LowerConstantPool(Op, DAG);
7564   case ISD::GlobalAddress:      return LowerGlobalAddress(Op, DAG);
7565   case ISD::GlobalTLSAddress:   return LowerGlobalTLSAddress(Op, DAG);
7566   case ISD::ExternalSymbol:     return LowerExternalSymbol(Op, DAG);
7567   case ISD::BlockAddress:       return LowerBlockAddress(Op, DAG);
7568   case ISD::SHL_PARTS:
7569   case ISD::SRA_PARTS:
7570   case ISD::SRL_PARTS:          return LowerShift(Op, DAG);
7571   case ISD::SINT_TO_FP:         return LowerSINT_TO_FP(Op, DAG);
7572   case ISD::UINT_TO_FP:         return LowerUINT_TO_FP(Op, DAG);
7573   case ISD::FP_TO_SINT:         return LowerFP_TO_SINT(Op, DAG);
7574   case ISD::FP_TO_UINT:         return LowerFP_TO_UINT(Op, DAG);
7575   case ISD::FABS:               return LowerFABS(Op, DAG);
7576   case ISD::FNEG:               return LowerFNEG(Op, DAG);
7577   case ISD::FCOPYSIGN:          return LowerFCOPYSIGN(Op, DAG);
7578   case ISD::SETCC:              return LowerSETCC(Op, DAG);
7579   case ISD::VSETCC:             return LowerVSETCC(Op, DAG);
7580   case ISD::SELECT:             return LowerSELECT(Op, DAG);
7581   case ISD::BRCOND:             return LowerBRCOND(Op, DAG);
7582   case ISD::JumpTable:          return LowerJumpTable(Op, DAG);
7583   case ISD::VASTART:            return LowerVASTART(Op, DAG);
7584   case ISD::VAARG:              return LowerVAARG(Op, DAG);
7585   case ISD::VACOPY:             return LowerVACOPY(Op, DAG);
7586   case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
7587   case ISD::RETURNADDR:         return LowerRETURNADDR(Op, DAG);
7588   case ISD::FRAMEADDR:          return LowerFRAMEADDR(Op, DAG);
7589   case ISD::FRAME_TO_ARGS_OFFSET:
7590                                 return LowerFRAME_TO_ARGS_OFFSET(Op, DAG);
7591   case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG);
7592   case ISD::EH_RETURN:          return LowerEH_RETURN(Op, DAG);
7593   case ISD::TRAMPOLINE:         return LowerTRAMPOLINE(Op, DAG);
7594   case ISD::FLT_ROUNDS_:        return LowerFLT_ROUNDS_(Op, DAG);
7595   case ISD::CTLZ:               return LowerCTLZ(Op, DAG);
7596   case ISD::CTTZ:               return LowerCTTZ(Op, DAG);
7597   case ISD::MUL:                return LowerMUL_V2I64(Op, DAG);
7598   case ISD::SADDO:
7599   case ISD::UADDO:
7600   case ISD::SSUBO:
7601   case ISD::USUBO:
7602   case ISD::SMULO:
7603   case ISD::UMULO:              return LowerXALUO(Op, DAG);
7604   case ISD::READCYCLECOUNTER:   return LowerREADCYCLECOUNTER(Op, DAG);
7605   }
7606 }
7607
7608 void X86TargetLowering::
7609 ReplaceATOMIC_BINARY_64(SDNode *Node, SmallVectorImpl<SDValue>&Results,
7610                         SelectionDAG &DAG, unsigned NewOp) {
7611   EVT T = Node->getValueType(0);
7612   DebugLoc dl = Node->getDebugLoc();
7613   assert (T == MVT::i64 && "Only know how to expand i64 atomics");
7614
7615   SDValue Chain = Node->getOperand(0);
7616   SDValue In1 = Node->getOperand(1);
7617   SDValue In2L = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
7618                              Node->getOperand(2), DAG.getIntPtrConstant(0));
7619   SDValue In2H = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
7620                              Node->getOperand(2), DAG.getIntPtrConstant(1));
7621   SDValue Ops[] = { Chain, In1, In2L, In2H };
7622   SDVTList Tys = DAG.getVTList(MVT::i32, MVT::i32, MVT::Other);
7623   SDValue Result =
7624     DAG.getMemIntrinsicNode(NewOp, dl, Tys, Ops, 4, MVT::i64,
7625                             cast<MemSDNode>(Node)->getMemOperand());
7626   SDValue OpsF[] = { Result.getValue(0), Result.getValue(1)};
7627   Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, OpsF, 2));
7628   Results.push_back(Result.getValue(2));
7629 }
7630
7631 /// ReplaceNodeResults - Replace a node with an illegal result type
7632 /// with a new node built out of custom code.
7633 void X86TargetLowering::ReplaceNodeResults(SDNode *N,
7634                                            SmallVectorImpl<SDValue>&Results,
7635                                            SelectionDAG &DAG) {
7636   DebugLoc dl = N->getDebugLoc();
7637   switch (N->getOpcode()) {
7638   default:
7639     assert(false && "Do not know how to custom type legalize this operation!");
7640     return;
7641   case ISD::FP_TO_SINT: {
7642     std::pair<SDValue,SDValue> Vals =
7643         FP_TO_INTHelper(SDValue(N, 0), DAG, true);
7644     SDValue FIST = Vals.first, StackSlot = Vals.second;
7645     if (FIST.getNode() != 0) {
7646       EVT VT = N->getValueType(0);
7647       // Return a load from the stack slot.
7648       Results.push_back(DAG.getLoad(VT, dl, FIST, StackSlot, NULL, 0,
7649                                     false, false, 0));
7650     }
7651     return;
7652   }
7653   case ISD::READCYCLECOUNTER: {
7654     SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Flag);
7655     SDValue TheChain = N->getOperand(0);
7656     SDValue rd = DAG.getNode(X86ISD::RDTSC_DAG, dl, Tys, &TheChain, 1);
7657     SDValue eax = DAG.getCopyFromReg(rd, dl, X86::EAX, MVT::i32,
7658                                      rd.getValue(1));
7659     SDValue edx = DAG.getCopyFromReg(eax.getValue(1), dl, X86::EDX, MVT::i32,
7660                                      eax.getValue(2));
7661     // Use a buildpair to merge the two 32-bit values into a 64-bit one.
7662     SDValue Ops[] = { eax, edx };
7663     Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Ops, 2));
7664     Results.push_back(edx.getValue(1));
7665     return;
7666   }
7667   case ISD::ATOMIC_CMP_SWAP: {
7668     EVT T = N->getValueType(0);
7669     assert (T == MVT::i64 && "Only know how to expand i64 Cmp and Swap");
7670     SDValue cpInL, cpInH;
7671     cpInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(2),
7672                         DAG.getConstant(0, MVT::i32));
7673     cpInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(2),
7674                         DAG.getConstant(1, MVT::i32));
7675     cpInL = DAG.getCopyToReg(N->getOperand(0), dl, X86::EAX, cpInL, SDValue());
7676     cpInH = DAG.getCopyToReg(cpInL.getValue(0), dl, X86::EDX, cpInH,
7677                              cpInL.getValue(1));
7678     SDValue swapInL, swapInH;
7679     swapInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(3),
7680                           DAG.getConstant(0, MVT::i32));
7681     swapInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(3),
7682                           DAG.getConstant(1, MVT::i32));
7683     swapInL = DAG.getCopyToReg(cpInH.getValue(0), dl, X86::EBX, swapInL,
7684                                cpInH.getValue(1));
7685     swapInH = DAG.getCopyToReg(swapInL.getValue(0), dl, X86::ECX, swapInH,
7686                                swapInL.getValue(1));
7687     SDValue Ops[] = { swapInH.getValue(0),
7688                       N->getOperand(1),
7689                       swapInH.getValue(1) };
7690     SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Flag);
7691     SDValue Result = DAG.getNode(X86ISD::LCMPXCHG8_DAG, dl, Tys, Ops, 3);
7692     SDValue cpOutL = DAG.getCopyFromReg(Result.getValue(0), dl, X86::EAX,
7693                                         MVT::i32, Result.getValue(1));
7694     SDValue cpOutH = DAG.getCopyFromReg(cpOutL.getValue(1), dl, X86::EDX,
7695                                         MVT::i32, cpOutL.getValue(2));
7696     SDValue OpsF[] = { cpOutL.getValue(0), cpOutH.getValue(0)};
7697     Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, OpsF, 2));
7698     Results.push_back(cpOutH.getValue(1));
7699     return;
7700   }
7701   case ISD::ATOMIC_LOAD_ADD:
7702     ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMADD64_DAG);
7703     return;
7704   case ISD::ATOMIC_LOAD_AND:
7705     ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMAND64_DAG);
7706     return;
7707   case ISD::ATOMIC_LOAD_NAND:
7708     ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMNAND64_DAG);
7709     return;
7710   case ISD::ATOMIC_LOAD_OR:
7711     ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMOR64_DAG);
7712     return;
7713   case ISD::ATOMIC_LOAD_SUB:
7714     ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMSUB64_DAG);
7715     return;
7716   case ISD::ATOMIC_LOAD_XOR:
7717     ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMXOR64_DAG);
7718     return;
7719   case ISD::ATOMIC_SWAP:
7720     ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMSWAP64_DAG);
7721     return;
7722   }
7723 }
7724
7725 const char *X86TargetLowering::getTargetNodeName(unsigned Opcode) const {
7726   switch (Opcode) {
7727   default: return NULL;
7728   case X86ISD::BSF:                return "X86ISD::BSF";
7729   case X86ISD::BSR:                return "X86ISD::BSR";
7730   case X86ISD::SHLD:               return "X86ISD::SHLD";
7731   case X86ISD::SHRD:               return "X86ISD::SHRD";
7732   case X86ISD::FAND:               return "X86ISD::FAND";
7733   case X86ISD::FOR:                return "X86ISD::FOR";
7734   case X86ISD::FXOR:               return "X86ISD::FXOR";
7735   case X86ISD::FSRL:               return "X86ISD::FSRL";
7736   case X86ISD::FILD:               return "X86ISD::FILD";
7737   case X86ISD::FILD_FLAG:          return "X86ISD::FILD_FLAG";
7738   case X86ISD::FP_TO_INT16_IN_MEM: return "X86ISD::FP_TO_INT16_IN_MEM";
7739   case X86ISD::FP_TO_INT32_IN_MEM: return "X86ISD::FP_TO_INT32_IN_MEM";
7740   case X86ISD::FP_TO_INT64_IN_MEM: return "X86ISD::FP_TO_INT64_IN_MEM";
7741   case X86ISD::FLD:                return "X86ISD::FLD";
7742   case X86ISD::FST:                return "X86ISD::FST";
7743   case X86ISD::CALL:               return "X86ISD::CALL";
7744   case X86ISD::RDTSC_DAG:          return "X86ISD::RDTSC_DAG";
7745   case X86ISD::BT:                 return "X86ISD::BT";
7746   case X86ISD::CMP:                return "X86ISD::CMP";
7747   case X86ISD::COMI:               return "X86ISD::COMI";
7748   case X86ISD::UCOMI:              return "X86ISD::UCOMI";
7749   case X86ISD::SETCC:              return "X86ISD::SETCC";
7750   case X86ISD::SETCC_CARRY:        return "X86ISD::SETCC_CARRY";
7751   case X86ISD::CMOV:               return "X86ISD::CMOV";
7752   case X86ISD::BRCOND:             return "X86ISD::BRCOND";
7753   case X86ISD::RET_FLAG:           return "X86ISD::RET_FLAG";
7754   case X86ISD::REP_STOS:           return "X86ISD::REP_STOS";
7755   case X86ISD::REP_MOVS:           return "X86ISD::REP_MOVS";
7756   case X86ISD::GlobalBaseReg:      return "X86ISD::GlobalBaseReg";
7757   case X86ISD::Wrapper:            return "X86ISD::Wrapper";
7758   case X86ISD::WrapperRIP:         return "X86ISD::WrapperRIP";
7759   case X86ISD::PEXTRB:             return "X86ISD::PEXTRB";
7760   case X86ISD::PEXTRW:             return "X86ISD::PEXTRW";
7761   case X86ISD::INSERTPS:           return "X86ISD::INSERTPS";
7762   case X86ISD::PINSRB:             return "X86ISD::PINSRB";
7763   case X86ISD::PINSRW:             return "X86ISD::PINSRW";
7764   case X86ISD::MMX_PINSRW:         return "X86ISD::MMX_PINSRW";
7765   case X86ISD::PSHUFB:             return "X86ISD::PSHUFB";
7766   case X86ISD::FMAX:               return "X86ISD::FMAX";
7767   case X86ISD::FMIN:               return "X86ISD::FMIN";
7768   case X86ISD::FRSQRT:             return "X86ISD::FRSQRT";
7769   case X86ISD::FRCP:               return "X86ISD::FRCP";
7770   case X86ISD::TLSADDR:            return "X86ISD::TLSADDR";
7771   case X86ISD::SegmentBaseAddress: return "X86ISD::SegmentBaseAddress";
7772   case X86ISD::EH_RETURN:          return "X86ISD::EH_RETURN";
7773   case X86ISD::TC_RETURN:          return "X86ISD::TC_RETURN";
7774   case X86ISD::FNSTCW16m:          return "X86ISD::FNSTCW16m";
7775   case X86ISD::LCMPXCHG_DAG:       return "X86ISD::LCMPXCHG_DAG";
7776   case X86ISD::LCMPXCHG8_DAG:      return "X86ISD::LCMPXCHG8_DAG";
7777   case X86ISD::ATOMADD64_DAG:      return "X86ISD::ATOMADD64_DAG";
7778   case X86ISD::ATOMSUB64_DAG:      return "X86ISD::ATOMSUB64_DAG";
7779   case X86ISD::ATOMOR64_DAG:       return "X86ISD::ATOMOR64_DAG";
7780   case X86ISD::ATOMXOR64_DAG:      return "X86ISD::ATOMXOR64_DAG";
7781   case X86ISD::ATOMAND64_DAG:      return "X86ISD::ATOMAND64_DAG";
7782   case X86ISD::ATOMNAND64_DAG:     return "X86ISD::ATOMNAND64_DAG";
7783   case X86ISD::VZEXT_MOVL:         return "X86ISD::VZEXT_MOVL";
7784   case X86ISD::VZEXT_LOAD:         return "X86ISD::VZEXT_LOAD";
7785   case X86ISD::VSHL:               return "X86ISD::VSHL";
7786   case X86ISD::VSRL:               return "X86ISD::VSRL";
7787   case X86ISD::CMPPD:              return "X86ISD::CMPPD";
7788   case X86ISD::CMPPS:              return "X86ISD::CMPPS";
7789   case X86ISD::PCMPEQB:            return "X86ISD::PCMPEQB";
7790   case X86ISD::PCMPEQW:            return "X86ISD::PCMPEQW";
7791   case X86ISD::PCMPEQD:            return "X86ISD::PCMPEQD";
7792   case X86ISD::PCMPEQQ:            return "X86ISD::PCMPEQQ";
7793   case X86ISD::PCMPGTB:            return "X86ISD::PCMPGTB";
7794   case X86ISD::PCMPGTW:            return "X86ISD::PCMPGTW";
7795   case X86ISD::PCMPGTD:            return "X86ISD::PCMPGTD";
7796   case X86ISD::PCMPGTQ:            return "X86ISD::PCMPGTQ";
7797   case X86ISD::ADD:                return "X86ISD::ADD";
7798   case X86ISD::SUB:                return "X86ISD::SUB";
7799   case X86ISD::SMUL:               return "X86ISD::SMUL";
7800   case X86ISD::UMUL:               return "X86ISD::UMUL";
7801   case X86ISD::INC:                return "X86ISD::INC";
7802   case X86ISD::DEC:                return "X86ISD::DEC";
7803   case X86ISD::OR:                 return "X86ISD::OR";
7804   case X86ISD::XOR:                return "X86ISD::XOR";
7805   case X86ISD::AND:                return "X86ISD::AND";
7806   case X86ISD::MUL_IMM:            return "X86ISD::MUL_IMM";
7807   case X86ISD::PTEST:              return "X86ISD::PTEST";
7808   case X86ISD::VASTART_SAVE_XMM_REGS: return "X86ISD::VASTART_SAVE_XMM_REGS";
7809   case X86ISD::MINGW_ALLOCA:       return "X86ISD::MINGW_ALLOCA";
7810   }
7811 }
7812
7813 // isLegalAddressingMode - Return true if the addressing mode represented
7814 // by AM is legal for this target, for a load/store of the specified type.
7815 bool X86TargetLowering::isLegalAddressingMode(const AddrMode &AM,
7816                                               const Type *Ty) const {
7817   // X86 supports extremely general addressing modes.
7818   CodeModel::Model M = getTargetMachine().getCodeModel();
7819
7820   // X86 allows a sign-extended 32-bit immediate field as a displacement.
7821   if (!X86::isOffsetSuitableForCodeModel(AM.BaseOffs, M, AM.BaseGV != NULL))
7822     return false;
7823
7824   if (AM.BaseGV) {
7825     unsigned GVFlags =
7826       Subtarget->ClassifyGlobalReference(AM.BaseGV, getTargetMachine());
7827
7828     // If a reference to this global requires an extra load, we can't fold it.
7829     if (isGlobalStubReference(GVFlags))
7830       return false;
7831
7832     // If BaseGV requires a register for the PIC base, we cannot also have a
7833     // BaseReg specified.
7834     if (AM.HasBaseReg && isGlobalRelativeToPICBase(GVFlags))
7835       return false;
7836
7837     // If lower 4G is not available, then we must use rip-relative addressing.
7838     if (Subtarget->is64Bit() && (AM.BaseOffs || AM.Scale > 1))
7839       return false;
7840   }
7841
7842   switch (AM.Scale) {
7843   case 0:
7844   case 1:
7845   case 2:
7846   case 4:
7847   case 8:
7848     // These scales always work.
7849     break;
7850   case 3:
7851   case 5:
7852   case 9:
7853     // These scales are formed with basereg+scalereg.  Only accept if there is
7854     // no basereg yet.
7855     if (AM.HasBaseReg)
7856       return false;
7857     break;
7858   default:  // Other stuff never works.
7859     return false;
7860   }
7861
7862   return true;
7863 }
7864
7865
7866 bool X86TargetLowering::isTruncateFree(const Type *Ty1, const Type *Ty2) const {
7867   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
7868     return false;
7869   unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
7870   unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
7871   if (NumBits1 <= NumBits2)
7872     return false;
7873   return true;
7874 }
7875
7876 bool X86TargetLowering::isTruncateFree(EVT VT1, EVT VT2) const {
7877   if (!VT1.isInteger() || !VT2.isInteger())
7878     return false;
7879   unsigned NumBits1 = VT1.getSizeInBits();
7880   unsigned NumBits2 = VT2.getSizeInBits();
7881   if (NumBits1 <= NumBits2)
7882     return false;
7883   return true;
7884 }
7885
7886 bool X86TargetLowering::isZExtFree(const Type *Ty1, const Type *Ty2) const {
7887   // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
7888   return Ty1->isIntegerTy(32) && Ty2->isIntegerTy(64) && Subtarget->is64Bit();
7889 }
7890
7891 bool X86TargetLowering::isZExtFree(EVT VT1, EVT VT2) const {
7892   // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
7893   return VT1 == MVT::i32 && VT2 == MVT::i64 && Subtarget->is64Bit();
7894 }
7895
7896 bool X86TargetLowering::isNarrowingProfitable(EVT VT1, EVT VT2) const {
7897   // i16 instructions are longer (0x66 prefix) and potentially slower.
7898   return !(VT1 == MVT::i32 && VT2 == MVT::i16);
7899 }
7900
7901 /// isShuffleMaskLegal - Targets can use this to indicate that they only
7902 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
7903 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
7904 /// are assumed to be legal.
7905 bool
7906 X86TargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M,
7907                                       EVT VT) const {
7908   // Only do shuffles on 128-bit vector types for now.
7909   if (VT.getSizeInBits() == 64)
7910     return false;
7911
7912   // FIXME: pshufb, blends, shifts.
7913   return (VT.getVectorNumElements() == 2 ||
7914           ShuffleVectorSDNode::isSplatMask(&M[0], VT) ||
7915           isMOVLMask(M, VT) ||
7916           isSHUFPMask(M, VT) ||
7917           isPSHUFDMask(M, VT) ||
7918           isPSHUFHWMask(M, VT) ||
7919           isPSHUFLWMask(M, VT) ||
7920           isPALIGNRMask(M, VT, Subtarget->hasSSSE3()) ||
7921           isUNPCKLMask(M, VT) ||
7922           isUNPCKHMask(M, VT) ||
7923           isUNPCKL_v_undef_Mask(M, VT) ||
7924           isUNPCKH_v_undef_Mask(M, VT));
7925 }
7926
7927 bool
7928 X86TargetLowering::isVectorClearMaskLegal(const SmallVectorImpl<int> &Mask,
7929                                           EVT VT) const {
7930   unsigned NumElts = VT.getVectorNumElements();
7931   // FIXME: This collection of masks seems suspect.
7932   if (NumElts == 2)
7933     return true;
7934   if (NumElts == 4 && VT.getSizeInBits() == 128) {
7935     return (isMOVLMask(Mask, VT)  ||
7936             isCommutedMOVLMask(Mask, VT, true) ||
7937             isSHUFPMask(Mask, VT) ||
7938             isCommutedSHUFPMask(Mask, VT));
7939   }
7940   return false;
7941 }
7942
7943 //===----------------------------------------------------------------------===//
7944 //                           X86 Scheduler Hooks
7945 //===----------------------------------------------------------------------===//
7946
7947 // private utility function
7948 MachineBasicBlock *
7949 X86TargetLowering::EmitAtomicBitwiseWithCustomInserter(MachineInstr *bInstr,
7950                                                        MachineBasicBlock *MBB,
7951                                                        unsigned regOpc,
7952                                                        unsigned immOpc,
7953                                                        unsigned LoadOpc,
7954                                                        unsigned CXchgOpc,
7955                                                        unsigned copyOpc,
7956                                                        unsigned notOpc,
7957                                                        unsigned EAXreg,
7958                                                        TargetRegisterClass *RC,
7959                                                        bool invSrc) const {
7960   // For the atomic bitwise operator, we generate
7961   //   thisMBB:
7962   //   newMBB:
7963   //     ld  t1 = [bitinstr.addr]
7964   //     op  t2 = t1, [bitinstr.val]
7965   //     mov EAX = t1
7966   //     lcs dest = [bitinstr.addr], t2  [EAX is implicit]
7967   //     bz  newMBB
7968   //     fallthrough -->nextMBB
7969   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
7970   const BasicBlock *LLVM_BB = MBB->getBasicBlock();
7971   MachineFunction::iterator MBBIter = MBB;
7972   ++MBBIter;
7973
7974   /// First build the CFG
7975   MachineFunction *F = MBB->getParent();
7976   MachineBasicBlock *thisMBB = MBB;
7977   MachineBasicBlock *newMBB = F->CreateMachineBasicBlock(LLVM_BB);
7978   MachineBasicBlock *nextMBB = F->CreateMachineBasicBlock(LLVM_BB);
7979   F->insert(MBBIter, newMBB);
7980   F->insert(MBBIter, nextMBB);
7981
7982   // Move all successors to thisMBB to nextMBB
7983   nextMBB->transferSuccessors(thisMBB);
7984
7985   // Update thisMBB to fall through to newMBB
7986   thisMBB->addSuccessor(newMBB);
7987
7988   // newMBB jumps to itself and fall through to nextMBB
7989   newMBB->addSuccessor(nextMBB);
7990   newMBB->addSuccessor(newMBB);
7991
7992   // Insert instructions into newMBB based on incoming instruction
7993   assert(bInstr->getNumOperands() < X86AddrNumOperands + 4 &&
7994          "unexpected number of operands");
7995   DebugLoc dl = bInstr->getDebugLoc();
7996   MachineOperand& destOper = bInstr->getOperand(0);
7997   MachineOperand* argOpers[2 + X86AddrNumOperands];
7998   int numArgs = bInstr->getNumOperands() - 1;
7999   for (int i=0; i < numArgs; ++i)
8000     argOpers[i] = &bInstr->getOperand(i+1);
8001
8002   // x86 address has 4 operands: base, index, scale, and displacement
8003   int lastAddrIndx = X86AddrNumOperands - 1; // [0,3]
8004   int valArgIndx = lastAddrIndx + 1;
8005
8006   unsigned t1 = F->getRegInfo().createVirtualRegister(RC);
8007   MachineInstrBuilder MIB = BuildMI(newMBB, dl, TII->get(LoadOpc), t1);
8008   for (int i=0; i <= lastAddrIndx; ++i)
8009     (*MIB).addOperand(*argOpers[i]);
8010
8011   unsigned tt = F->getRegInfo().createVirtualRegister(RC);
8012   if (invSrc) {
8013     MIB = BuildMI(newMBB, dl, TII->get(notOpc), tt).addReg(t1);
8014   }
8015   else
8016     tt = t1;
8017
8018   unsigned t2 = F->getRegInfo().createVirtualRegister(RC);
8019   assert((argOpers[valArgIndx]->isReg() ||
8020           argOpers[valArgIndx]->isImm()) &&
8021          "invalid operand");
8022   if (argOpers[valArgIndx]->isReg())
8023     MIB = BuildMI(newMBB, dl, TII->get(regOpc), t2);
8024   else
8025     MIB = BuildMI(newMBB, dl, TII->get(immOpc), t2);
8026   MIB.addReg(tt);
8027   (*MIB).addOperand(*argOpers[valArgIndx]);
8028
8029   MIB = BuildMI(newMBB, dl, TII->get(copyOpc), EAXreg);
8030   MIB.addReg(t1);
8031
8032   MIB = BuildMI(newMBB, dl, TII->get(CXchgOpc));
8033   for (int i=0; i <= lastAddrIndx; ++i)
8034     (*MIB).addOperand(*argOpers[i]);
8035   MIB.addReg(t2);
8036   assert(bInstr->hasOneMemOperand() && "Unexpected number of memoperand");
8037   (*MIB).setMemRefs(bInstr->memoperands_begin(),
8038                     bInstr->memoperands_end());
8039
8040   MIB = BuildMI(newMBB, dl, TII->get(copyOpc), destOper.getReg());
8041   MIB.addReg(EAXreg);
8042
8043   // insert branch
8044   BuildMI(newMBB, dl, TII->get(X86::JNE_4)).addMBB(newMBB);
8045
8046   F->DeleteMachineInstr(bInstr);   // The pseudo instruction is gone now.
8047   return nextMBB;
8048 }
8049
8050 // private utility function:  64 bit atomics on 32 bit host.
8051 MachineBasicBlock *
8052 X86TargetLowering::EmitAtomicBit6432WithCustomInserter(MachineInstr *bInstr,
8053                                                        MachineBasicBlock *MBB,
8054                                                        unsigned regOpcL,
8055                                                        unsigned regOpcH,
8056                                                        unsigned immOpcL,
8057                                                        unsigned immOpcH,
8058                                                        bool invSrc) const {
8059   // For the atomic bitwise operator, we generate
8060   //   thisMBB (instructions are in pairs, except cmpxchg8b)
8061   //     ld t1,t2 = [bitinstr.addr]
8062   //   newMBB:
8063   //     out1, out2 = phi (thisMBB, t1/t2) (newMBB, t3/t4)
8064   //     op  t5, t6 <- out1, out2, [bitinstr.val]
8065   //      (for SWAP, substitute:  mov t5, t6 <- [bitinstr.val])
8066   //     mov ECX, EBX <- t5, t6
8067   //     mov EAX, EDX <- t1, t2
8068   //     cmpxchg8b [bitinstr.addr]  [EAX, EDX, EBX, ECX implicit]
8069   //     mov t3, t4 <- EAX, EDX
8070   //     bz  newMBB
8071   //     result in out1, out2
8072   //     fallthrough -->nextMBB
8073
8074   const TargetRegisterClass *RC = X86::GR32RegisterClass;
8075   const unsigned LoadOpc = X86::MOV32rm;
8076   const unsigned copyOpc = X86::MOV32rr;
8077   const unsigned NotOpc = X86::NOT32r;
8078   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
8079   const BasicBlock *LLVM_BB = MBB->getBasicBlock();
8080   MachineFunction::iterator MBBIter = MBB;
8081   ++MBBIter;
8082
8083   /// First build the CFG
8084   MachineFunction *F = MBB->getParent();
8085   MachineBasicBlock *thisMBB = MBB;
8086   MachineBasicBlock *newMBB = F->CreateMachineBasicBlock(LLVM_BB);
8087   MachineBasicBlock *nextMBB = F->CreateMachineBasicBlock(LLVM_BB);
8088   F->insert(MBBIter, newMBB);
8089   F->insert(MBBIter, nextMBB);
8090
8091   // Move all successors to thisMBB to nextMBB
8092   nextMBB->transferSuccessors(thisMBB);
8093
8094   // Update thisMBB to fall through to newMBB
8095   thisMBB->addSuccessor(newMBB);
8096
8097   // newMBB jumps to itself and fall through to nextMBB
8098   newMBB->addSuccessor(nextMBB);
8099   newMBB->addSuccessor(newMBB);
8100
8101   DebugLoc dl = bInstr->getDebugLoc();
8102   // Insert instructions into newMBB based on incoming instruction
8103   // There are 8 "real" operands plus 9 implicit def/uses, ignored here.
8104   assert(bInstr->getNumOperands() < X86AddrNumOperands + 14 &&
8105          "unexpected number of operands");
8106   MachineOperand& dest1Oper = bInstr->getOperand(0);
8107   MachineOperand& dest2Oper = bInstr->getOperand(1);
8108   MachineOperand* argOpers[2 + X86AddrNumOperands];
8109   for (int i=0; i < 2 + X86AddrNumOperands; ++i)
8110     argOpers[i] = &bInstr->getOperand(i+2);
8111
8112   // x86 address has 5 operands: base, index, scale, displacement, and segment.
8113   int lastAddrIndx = X86AddrNumOperands - 1; // [0,3]
8114
8115   unsigned t1 = F->getRegInfo().createVirtualRegister(RC);
8116   MachineInstrBuilder MIB = BuildMI(thisMBB, dl, TII->get(LoadOpc), t1);
8117   for (int i=0; i <= lastAddrIndx; ++i)
8118     (*MIB).addOperand(*argOpers[i]);
8119   unsigned t2 = F->getRegInfo().createVirtualRegister(RC);
8120   MIB = BuildMI(thisMBB, dl, TII->get(LoadOpc), t2);
8121   // add 4 to displacement.
8122   for (int i=0; i <= lastAddrIndx-2; ++i)
8123     (*MIB).addOperand(*argOpers[i]);
8124   MachineOperand newOp3 = *(argOpers[3]);
8125   if (newOp3.isImm())
8126     newOp3.setImm(newOp3.getImm()+4);
8127   else
8128     newOp3.setOffset(newOp3.getOffset()+4);
8129   (*MIB).addOperand(newOp3);
8130   (*MIB).addOperand(*argOpers[lastAddrIndx]);
8131
8132   // t3/4 are defined later, at the bottom of the loop
8133   unsigned t3 = F->getRegInfo().createVirtualRegister(RC);
8134   unsigned t4 = F->getRegInfo().createVirtualRegister(RC);
8135   BuildMI(newMBB, dl, TII->get(X86::PHI), dest1Oper.getReg())
8136     .addReg(t1).addMBB(thisMBB).addReg(t3).addMBB(newMBB);
8137   BuildMI(newMBB, dl, TII->get(X86::PHI), dest2Oper.getReg())
8138     .addReg(t2).addMBB(thisMBB).addReg(t4).addMBB(newMBB);
8139
8140   // The subsequent operations should be using the destination registers of
8141   //the PHI instructions.
8142   if (invSrc) {
8143     t1 = F->getRegInfo().createVirtualRegister(RC);
8144     t2 = F->getRegInfo().createVirtualRegister(RC);
8145     MIB = BuildMI(newMBB, dl, TII->get(NotOpc), t1).addReg(dest1Oper.getReg());
8146     MIB = BuildMI(newMBB, dl, TII->get(NotOpc), t2).addReg(dest2Oper.getReg());
8147   } else {
8148     t1 = dest1Oper.getReg();
8149     t2 = dest2Oper.getReg();
8150   }
8151
8152   int valArgIndx = lastAddrIndx + 1;
8153   assert((argOpers[valArgIndx]->isReg() ||
8154           argOpers[valArgIndx]->isImm()) &&
8155          "invalid operand");
8156   unsigned t5 = F->getRegInfo().createVirtualRegister(RC);
8157   unsigned t6 = F->getRegInfo().createVirtualRegister(RC);
8158   if (argOpers[valArgIndx]->isReg())
8159     MIB = BuildMI(newMBB, dl, TII->get(regOpcL), t5);
8160   else
8161     MIB = BuildMI(newMBB, dl, TII->get(immOpcL), t5);
8162   if (regOpcL != X86::MOV32rr)
8163     MIB.addReg(t1);
8164   (*MIB).addOperand(*argOpers[valArgIndx]);
8165   assert(argOpers[valArgIndx + 1]->isReg() ==
8166          argOpers[valArgIndx]->isReg());
8167   assert(argOpers[valArgIndx + 1]->isImm() ==
8168          argOpers[valArgIndx]->isImm());
8169   if (argOpers[valArgIndx + 1]->isReg())
8170     MIB = BuildMI(newMBB, dl, TII->get(regOpcH), t6);
8171   else
8172     MIB = BuildMI(newMBB, dl, TII->get(immOpcH), t6);
8173   if (regOpcH != X86::MOV32rr)
8174     MIB.addReg(t2);
8175   (*MIB).addOperand(*argOpers[valArgIndx + 1]);
8176
8177   MIB = BuildMI(newMBB, dl, TII->get(copyOpc), X86::EAX);
8178   MIB.addReg(t1);
8179   MIB = BuildMI(newMBB, dl, TII->get(copyOpc), X86::EDX);
8180   MIB.addReg(t2);
8181
8182   MIB = BuildMI(newMBB, dl, TII->get(copyOpc), X86::EBX);
8183   MIB.addReg(t5);
8184   MIB = BuildMI(newMBB, dl, TII->get(copyOpc), X86::ECX);
8185   MIB.addReg(t6);
8186
8187   MIB = BuildMI(newMBB, dl, TII->get(X86::LCMPXCHG8B));
8188   for (int i=0; i <= lastAddrIndx; ++i)
8189     (*MIB).addOperand(*argOpers[i]);
8190
8191   assert(bInstr->hasOneMemOperand() && "Unexpected number of memoperand");
8192   (*MIB).setMemRefs(bInstr->memoperands_begin(),
8193                     bInstr->memoperands_end());
8194
8195   MIB = BuildMI(newMBB, dl, TII->get(copyOpc), t3);
8196   MIB.addReg(X86::EAX);
8197   MIB = BuildMI(newMBB, dl, TII->get(copyOpc), t4);
8198   MIB.addReg(X86::EDX);
8199
8200   // insert branch
8201   BuildMI(newMBB, dl, TII->get(X86::JNE_4)).addMBB(newMBB);
8202
8203   F->DeleteMachineInstr(bInstr);   // The pseudo instruction is gone now.
8204   return nextMBB;
8205 }
8206
8207 // private utility function
8208 MachineBasicBlock *
8209 X86TargetLowering::EmitAtomicMinMaxWithCustomInserter(MachineInstr *mInstr,
8210                                                       MachineBasicBlock *MBB,
8211                                                       unsigned cmovOpc) const {
8212   // For the atomic min/max operator, we generate
8213   //   thisMBB:
8214   //   newMBB:
8215   //     ld t1 = [min/max.addr]
8216   //     mov t2 = [min/max.val]
8217   //     cmp  t1, t2
8218   //     cmov[cond] t2 = t1
8219   //     mov EAX = t1
8220   //     lcs dest = [bitinstr.addr], t2  [EAX is implicit]
8221   //     bz   newMBB
8222   //     fallthrough -->nextMBB
8223   //
8224   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
8225   const BasicBlock *LLVM_BB = MBB->getBasicBlock();
8226   MachineFunction::iterator MBBIter = MBB;
8227   ++MBBIter;
8228
8229   /// First build the CFG
8230   MachineFunction *F = MBB->getParent();
8231   MachineBasicBlock *thisMBB = MBB;
8232   MachineBasicBlock *newMBB = F->CreateMachineBasicBlock(LLVM_BB);
8233   MachineBasicBlock *nextMBB = F->CreateMachineBasicBlock(LLVM_BB);
8234   F->insert(MBBIter, newMBB);
8235   F->insert(MBBIter, nextMBB);
8236
8237   // Move all successors of thisMBB to nextMBB
8238   nextMBB->transferSuccessors(thisMBB);
8239
8240   // Update thisMBB to fall through to newMBB
8241   thisMBB->addSuccessor(newMBB);
8242
8243   // newMBB jumps to newMBB and fall through to nextMBB
8244   newMBB->addSuccessor(nextMBB);
8245   newMBB->addSuccessor(newMBB);
8246
8247   DebugLoc dl = mInstr->getDebugLoc();
8248   // Insert instructions into newMBB based on incoming instruction
8249   assert(mInstr->getNumOperands() < X86AddrNumOperands + 4 &&
8250          "unexpected number of operands");
8251   MachineOperand& destOper = mInstr->getOperand(0);
8252   MachineOperand* argOpers[2 + X86AddrNumOperands];
8253   int numArgs = mInstr->getNumOperands() - 1;
8254   for (int i=0; i < numArgs; ++i)
8255     argOpers[i] = &mInstr->getOperand(i+1);
8256
8257   // x86 address has 4 operands: base, index, scale, and displacement
8258   int lastAddrIndx = X86AddrNumOperands - 1; // [0,3]
8259   int valArgIndx = lastAddrIndx + 1;
8260
8261   unsigned t1 = F->getRegInfo().createVirtualRegister(X86::GR32RegisterClass);
8262   MachineInstrBuilder MIB = BuildMI(newMBB, dl, TII->get(X86::MOV32rm), t1);
8263   for (int i=0; i <= lastAddrIndx; ++i)
8264     (*MIB).addOperand(*argOpers[i]);
8265
8266   // We only support register and immediate values
8267   assert((argOpers[valArgIndx]->isReg() ||
8268           argOpers[valArgIndx]->isImm()) &&
8269          "invalid operand");
8270
8271   unsigned t2 = F->getRegInfo().createVirtualRegister(X86::GR32RegisterClass);
8272   if (argOpers[valArgIndx]->isReg())
8273     MIB = BuildMI(newMBB, dl, TII->get(X86::MOV32rr), t2);
8274   else
8275     MIB = BuildMI(newMBB, dl, TII->get(X86::MOV32rr), t2);
8276   (*MIB).addOperand(*argOpers[valArgIndx]);
8277
8278   MIB = BuildMI(newMBB, dl, TII->get(X86::MOV32rr), X86::EAX);
8279   MIB.addReg(t1);
8280
8281   MIB = BuildMI(newMBB, dl, TII->get(X86::CMP32rr));
8282   MIB.addReg(t1);
8283   MIB.addReg(t2);
8284
8285   // Generate movc
8286   unsigned t3 = F->getRegInfo().createVirtualRegister(X86::GR32RegisterClass);
8287   MIB = BuildMI(newMBB, dl, TII->get(cmovOpc),t3);
8288   MIB.addReg(t2);
8289   MIB.addReg(t1);
8290
8291   // Cmp and exchange if none has modified the memory location
8292   MIB = BuildMI(newMBB, dl, TII->get(X86::LCMPXCHG32));
8293   for (int i=0; i <= lastAddrIndx; ++i)
8294     (*MIB).addOperand(*argOpers[i]);
8295   MIB.addReg(t3);
8296   assert(mInstr->hasOneMemOperand() && "Unexpected number of memoperand");
8297   (*MIB).setMemRefs(mInstr->memoperands_begin(),
8298                     mInstr->memoperands_end());
8299
8300   MIB = BuildMI(newMBB, dl, TII->get(X86::MOV32rr), destOper.getReg());
8301   MIB.addReg(X86::EAX);
8302
8303   // insert branch
8304   BuildMI(newMBB, dl, TII->get(X86::JNE_4)).addMBB(newMBB);
8305
8306   F->DeleteMachineInstr(mInstr);   // The pseudo instruction is gone now.
8307   return nextMBB;
8308 }
8309
8310 // FIXME: When we get size specific XMM0 registers, i.e. XMM0_V16I8
8311 // all of this code can be replaced with that in the .td file.
8312 MachineBasicBlock *
8313 X86TargetLowering::EmitPCMP(MachineInstr *MI, MachineBasicBlock *BB,
8314                             unsigned numArgs, bool memArg) const {
8315
8316   MachineFunction *F = BB->getParent();
8317   DebugLoc dl = MI->getDebugLoc();
8318   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
8319
8320   unsigned Opc;
8321   if (memArg)
8322     Opc = numArgs == 3 ? X86::PCMPISTRM128rm : X86::PCMPESTRM128rm;
8323   else
8324     Opc = numArgs == 3 ? X86::PCMPISTRM128rr : X86::PCMPESTRM128rr;
8325
8326   MachineInstrBuilder MIB = BuildMI(BB, dl, TII->get(Opc));
8327
8328   for (unsigned i = 0; i < numArgs; ++i) {
8329     MachineOperand &Op = MI->getOperand(i+1);
8330
8331     if (!(Op.isReg() && Op.isImplicit()))
8332       MIB.addOperand(Op);
8333   }
8334
8335   BuildMI(BB, dl, TII->get(X86::MOVAPSrr), MI->getOperand(0).getReg())
8336     .addReg(X86::XMM0);
8337
8338   F->DeleteMachineInstr(MI);
8339
8340   return BB;
8341 }
8342
8343 MachineBasicBlock *
8344 X86TargetLowering::EmitVAStartSaveXMMRegsWithCustomInserter(
8345                                                  MachineInstr *MI,
8346                                                  MachineBasicBlock *MBB) const {
8347   // Emit code to save XMM registers to the stack. The ABI says that the
8348   // number of registers to save is given in %al, so it's theoretically
8349   // possible to do an indirect jump trick to avoid saving all of them,
8350   // however this code takes a simpler approach and just executes all
8351   // of the stores if %al is non-zero. It's less code, and it's probably
8352   // easier on the hardware branch predictor, and stores aren't all that
8353   // expensive anyway.
8354
8355   // Create the new basic blocks. One block contains all the XMM stores,
8356   // and one block is the final destination regardless of whether any
8357   // stores were performed.
8358   const BasicBlock *LLVM_BB = MBB->getBasicBlock();
8359   MachineFunction *F = MBB->getParent();
8360   MachineFunction::iterator MBBIter = MBB;
8361   ++MBBIter;
8362   MachineBasicBlock *XMMSaveMBB = F->CreateMachineBasicBlock(LLVM_BB);
8363   MachineBasicBlock *EndMBB = F->CreateMachineBasicBlock(LLVM_BB);
8364   F->insert(MBBIter, XMMSaveMBB);
8365   F->insert(MBBIter, EndMBB);
8366
8367   // Set up the CFG.
8368   // Move any original successors of MBB to the end block.
8369   EndMBB->transferSuccessors(MBB);
8370   // The original block will now fall through to the XMM save block.
8371   MBB->addSuccessor(XMMSaveMBB);
8372   // The XMMSaveMBB will fall through to the end block.
8373   XMMSaveMBB->addSuccessor(EndMBB);
8374
8375   // Now add the instructions.
8376   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
8377   DebugLoc DL = MI->getDebugLoc();
8378
8379   unsigned CountReg = MI->getOperand(0).getReg();
8380   int64_t RegSaveFrameIndex = MI->getOperand(1).getImm();
8381   int64_t VarArgsFPOffset = MI->getOperand(2).getImm();
8382
8383   if (!Subtarget->isTargetWin64()) {
8384     // If %al is 0, branch around the XMM save block.
8385     BuildMI(MBB, DL, TII->get(X86::TEST8rr)).addReg(CountReg).addReg(CountReg);
8386     BuildMI(MBB, DL, TII->get(X86::JE_4)).addMBB(EndMBB);
8387     MBB->addSuccessor(EndMBB);
8388   }
8389
8390   // In the XMM save block, save all the XMM argument registers.
8391   for (int i = 3, e = MI->getNumOperands(); i != e; ++i) {
8392     int64_t Offset = (i - 3) * 16 + VarArgsFPOffset;
8393     MachineMemOperand *MMO =
8394       F->getMachineMemOperand(
8395         PseudoSourceValue::getFixedStack(RegSaveFrameIndex),
8396         MachineMemOperand::MOStore, Offset,
8397         /*Size=*/16, /*Align=*/16);
8398     BuildMI(XMMSaveMBB, DL, TII->get(X86::MOVAPSmr))
8399       .addFrameIndex(RegSaveFrameIndex)
8400       .addImm(/*Scale=*/1)
8401       .addReg(/*IndexReg=*/0)
8402       .addImm(/*Disp=*/Offset)
8403       .addReg(/*Segment=*/0)
8404       .addReg(MI->getOperand(i).getReg())
8405       .addMemOperand(MMO);
8406   }
8407
8408   F->DeleteMachineInstr(MI);   // The pseudo instruction is gone now.
8409
8410   return EndMBB;
8411 }
8412
8413 MachineBasicBlock *
8414 X86TargetLowering::EmitLoweredSelect(MachineInstr *MI,
8415                                      MachineBasicBlock *BB,
8416                    DenseMap<MachineBasicBlock*, MachineBasicBlock*> *EM) const {
8417   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
8418   DebugLoc DL = MI->getDebugLoc();
8419
8420   // To "insert" a SELECT_CC instruction, we actually have to insert the
8421   // diamond control-flow pattern.  The incoming instruction knows the
8422   // destination vreg to set, the condition code register to branch on, the
8423   // true/false values to select between, and a branch opcode to use.
8424   const BasicBlock *LLVM_BB = BB->getBasicBlock();
8425   MachineFunction::iterator It = BB;
8426   ++It;
8427
8428   //  thisMBB:
8429   //  ...
8430   //   TrueVal = ...
8431   //   cmpTY ccX, r1, r2
8432   //   bCC copy1MBB
8433   //   fallthrough --> copy0MBB
8434   MachineBasicBlock *thisMBB = BB;
8435   MachineFunction *F = BB->getParent();
8436   MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
8437   MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
8438   unsigned Opc =
8439     X86::GetCondBranchFromCond((X86::CondCode)MI->getOperand(3).getImm());
8440   BuildMI(BB, DL, TII->get(Opc)).addMBB(sinkMBB);
8441   F->insert(It, copy0MBB);
8442   F->insert(It, sinkMBB);
8443   // Update machine-CFG edges by first adding all successors of the current
8444   // block to the new block which will contain the Phi node for the select.
8445   // Also inform sdisel of the edge changes.
8446   for (MachineBasicBlock::succ_iterator I = BB->succ_begin(),
8447          E = BB->succ_end(); I != E; ++I) {
8448     EM->insert(std::make_pair(*I, sinkMBB));
8449     sinkMBB->addSuccessor(*I);
8450   }
8451   // Next, remove all successors of the current block, and add the true
8452   // and fallthrough blocks as its successors.
8453   while (!BB->succ_empty())
8454     BB->removeSuccessor(BB->succ_begin());
8455   // Add the true and fallthrough blocks as its successors.
8456   BB->addSuccessor(copy0MBB);
8457   BB->addSuccessor(sinkMBB);
8458
8459   //  copy0MBB:
8460   //   %FalseValue = ...
8461   //   # fallthrough to sinkMBB
8462   BB = copy0MBB;
8463
8464   // Update machine-CFG edges
8465   BB->addSuccessor(sinkMBB);
8466
8467   //  sinkMBB:
8468   //   %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
8469   //  ...
8470   BB = sinkMBB;
8471   BuildMI(BB, DL, TII->get(X86::PHI), MI->getOperand(0).getReg())
8472     .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB)
8473     .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
8474
8475   F->DeleteMachineInstr(MI);   // The pseudo instruction is gone now.
8476   return BB;
8477 }
8478
8479 MachineBasicBlock *
8480 X86TargetLowering::EmitLoweredMingwAlloca(MachineInstr *MI,
8481                                           MachineBasicBlock *BB,
8482                    DenseMap<MachineBasicBlock*, MachineBasicBlock*> *EM) const {
8483   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
8484   DebugLoc DL = MI->getDebugLoc();
8485   MachineFunction *F = BB->getParent();
8486
8487   // The lowering is pretty easy: we're just emitting the call to _alloca.  The
8488   // non-trivial part is impdef of ESP.
8489   // FIXME: The code should be tweaked as soon as we'll try to do codegen for
8490   // mingw-w64.
8491
8492   BuildMI(BB, DL, TII->get(X86::CALLpcrel32))
8493     .addExternalSymbol("_alloca")
8494     .addReg(X86::EAX, RegState::Implicit)
8495     .addReg(X86::ESP, RegState::Implicit)
8496     .addReg(X86::EAX, RegState::Define | RegState::Implicit)
8497     .addReg(X86::ESP, RegState::Define | RegState::Implicit);
8498
8499   F->DeleteMachineInstr(MI);   // The pseudo instruction is gone now.
8500   return BB;
8501 }
8502
8503 MachineBasicBlock *
8504 X86TargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
8505                                                MachineBasicBlock *BB,
8506                    DenseMap<MachineBasicBlock*, MachineBasicBlock*> *EM) const {
8507   switch (MI->getOpcode()) {
8508   default: assert(false && "Unexpected instr type to insert");
8509   case X86::MINGW_ALLOCA:
8510     return EmitLoweredMingwAlloca(MI, BB, EM);
8511   case X86::CMOV_GR8:
8512   case X86::CMOV_V1I64:
8513   case X86::CMOV_FR32:
8514   case X86::CMOV_FR64:
8515   case X86::CMOV_V4F32:
8516   case X86::CMOV_V2F64:
8517   case X86::CMOV_V2I64:
8518   case X86::CMOV_GR16:
8519   case X86::CMOV_GR32:
8520   case X86::CMOV_RFP32:
8521   case X86::CMOV_RFP64:
8522   case X86::CMOV_RFP80:
8523     return EmitLoweredSelect(MI, BB, EM);
8524
8525   case X86::FP32_TO_INT16_IN_MEM:
8526   case X86::FP32_TO_INT32_IN_MEM:
8527   case X86::FP32_TO_INT64_IN_MEM:
8528   case X86::FP64_TO_INT16_IN_MEM:
8529   case X86::FP64_TO_INT32_IN_MEM:
8530   case X86::FP64_TO_INT64_IN_MEM:
8531   case X86::FP80_TO_INT16_IN_MEM:
8532   case X86::FP80_TO_INT32_IN_MEM:
8533   case X86::FP80_TO_INT64_IN_MEM: {
8534     const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
8535     DebugLoc DL = MI->getDebugLoc();
8536
8537     // Change the floating point control register to use "round towards zero"
8538     // mode when truncating to an integer value.
8539     MachineFunction *F = BB->getParent();
8540     int CWFrameIdx = F->getFrameInfo()->CreateStackObject(2, 2, false);
8541     addFrameReference(BuildMI(BB, DL, TII->get(X86::FNSTCW16m)), CWFrameIdx);
8542
8543     // Load the old value of the high byte of the control word...
8544     unsigned OldCW =
8545       F->getRegInfo().createVirtualRegister(X86::GR16RegisterClass);
8546     addFrameReference(BuildMI(BB, DL, TII->get(X86::MOV16rm), OldCW),
8547                       CWFrameIdx);
8548
8549     // Set the high part to be round to zero...
8550     addFrameReference(BuildMI(BB, DL, TII->get(X86::MOV16mi)), CWFrameIdx)
8551       .addImm(0xC7F);
8552
8553     // Reload the modified control word now...
8554     addFrameReference(BuildMI(BB, DL, TII->get(X86::FLDCW16m)), CWFrameIdx);
8555
8556     // Restore the memory image of control word to original value
8557     addFrameReference(BuildMI(BB, DL, TII->get(X86::MOV16mr)), CWFrameIdx)
8558       .addReg(OldCW);
8559
8560     // Get the X86 opcode to use.
8561     unsigned Opc;
8562     switch (MI->getOpcode()) {
8563     default: llvm_unreachable("illegal opcode!");
8564     case X86::FP32_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m32; break;
8565     case X86::FP32_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m32; break;
8566     case X86::FP32_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m32; break;
8567     case X86::FP64_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m64; break;
8568     case X86::FP64_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m64; break;
8569     case X86::FP64_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m64; break;
8570     case X86::FP80_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m80; break;
8571     case X86::FP80_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m80; break;
8572     case X86::FP80_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m80; break;
8573     }
8574
8575     X86AddressMode AM;
8576     MachineOperand &Op = MI->getOperand(0);
8577     if (Op.isReg()) {
8578       AM.BaseType = X86AddressMode::RegBase;
8579       AM.Base.Reg = Op.getReg();
8580     } else {
8581       AM.BaseType = X86AddressMode::FrameIndexBase;
8582       AM.Base.FrameIndex = Op.getIndex();
8583     }
8584     Op = MI->getOperand(1);
8585     if (Op.isImm())
8586       AM.Scale = Op.getImm();
8587     Op = MI->getOperand(2);
8588     if (Op.isImm())
8589       AM.IndexReg = Op.getImm();
8590     Op = MI->getOperand(3);
8591     if (Op.isGlobal()) {
8592       AM.GV = Op.getGlobal();
8593     } else {
8594       AM.Disp = Op.getImm();
8595     }
8596     addFullAddress(BuildMI(BB, DL, TII->get(Opc)), AM)
8597                       .addReg(MI->getOperand(X86AddrNumOperands).getReg());
8598
8599     // Reload the original control word now.
8600     addFrameReference(BuildMI(BB, DL, TII->get(X86::FLDCW16m)), CWFrameIdx);
8601
8602     F->DeleteMachineInstr(MI);   // The pseudo instruction is gone now.
8603     return BB;
8604   }
8605     // DBG_VALUE.  Only the frame index case is done here.
8606   case X86::DBG_VALUE: {
8607     const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
8608     DebugLoc DL = MI->getDebugLoc();
8609     X86AddressMode AM;
8610     MachineFunction *F = BB->getParent();
8611     AM.BaseType = X86AddressMode::FrameIndexBase;
8612     AM.Base.FrameIndex = MI->getOperand(0).getImm();
8613     addFullAddress(BuildMI(BB, DL, TII->get(X86::DBG_VALUE)), AM).
8614       addImm(MI->getOperand(1).getImm()).
8615       addMetadata(MI->getOperand(2).getMetadata());
8616     F->DeleteMachineInstr(MI);      // Remove pseudo.
8617     return BB;
8618   }
8619
8620     // String/text processing lowering.
8621   case X86::PCMPISTRM128REG:
8622     return EmitPCMP(MI, BB, 3, false /* in-mem */);
8623   case X86::PCMPISTRM128MEM:
8624     return EmitPCMP(MI, BB, 3, true /* in-mem */);
8625   case X86::PCMPESTRM128REG:
8626     return EmitPCMP(MI, BB, 5, false /* in mem */);
8627   case X86::PCMPESTRM128MEM:
8628     return EmitPCMP(MI, BB, 5, true /* in mem */);
8629
8630     // Atomic Lowering.
8631   case X86::ATOMAND32:
8632     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND32rr,
8633                                                X86::AND32ri, X86::MOV32rm,
8634                                                X86::LCMPXCHG32, X86::MOV32rr,
8635                                                X86::NOT32r, X86::EAX,
8636                                                X86::GR32RegisterClass);
8637   case X86::ATOMOR32:
8638     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR32rr,
8639                                                X86::OR32ri, X86::MOV32rm,
8640                                                X86::LCMPXCHG32, X86::MOV32rr,
8641                                                X86::NOT32r, X86::EAX,
8642                                                X86::GR32RegisterClass);
8643   case X86::ATOMXOR32:
8644     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR32rr,
8645                                                X86::XOR32ri, X86::MOV32rm,
8646                                                X86::LCMPXCHG32, X86::MOV32rr,
8647                                                X86::NOT32r, X86::EAX,
8648                                                X86::GR32RegisterClass);
8649   case X86::ATOMNAND32:
8650     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND32rr,
8651                                                X86::AND32ri, X86::MOV32rm,
8652                                                X86::LCMPXCHG32, X86::MOV32rr,
8653                                                X86::NOT32r, X86::EAX,
8654                                                X86::GR32RegisterClass, true);
8655   case X86::ATOMMIN32:
8656     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVL32rr);
8657   case X86::ATOMMAX32:
8658     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVG32rr);
8659   case X86::ATOMUMIN32:
8660     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVB32rr);
8661   case X86::ATOMUMAX32:
8662     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVA32rr);
8663
8664   case X86::ATOMAND16:
8665     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND16rr,
8666                                                X86::AND16ri, X86::MOV16rm,
8667                                                X86::LCMPXCHG16, X86::MOV16rr,
8668                                                X86::NOT16r, X86::AX,
8669                                                X86::GR16RegisterClass);
8670   case X86::ATOMOR16:
8671     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR16rr,
8672                                                X86::OR16ri, X86::MOV16rm,
8673                                                X86::LCMPXCHG16, X86::MOV16rr,
8674                                                X86::NOT16r, X86::AX,
8675                                                X86::GR16RegisterClass);
8676   case X86::ATOMXOR16:
8677     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR16rr,
8678                                                X86::XOR16ri, X86::MOV16rm,
8679                                                X86::LCMPXCHG16, X86::MOV16rr,
8680                                                X86::NOT16r, X86::AX,
8681                                                X86::GR16RegisterClass);
8682   case X86::ATOMNAND16:
8683     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND16rr,
8684                                                X86::AND16ri, X86::MOV16rm,
8685                                                X86::LCMPXCHG16, X86::MOV16rr,
8686                                                X86::NOT16r, X86::AX,
8687                                                X86::GR16RegisterClass, true);
8688   case X86::ATOMMIN16:
8689     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVL16rr);
8690   case X86::ATOMMAX16:
8691     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVG16rr);
8692   case X86::ATOMUMIN16:
8693     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVB16rr);
8694   case X86::ATOMUMAX16:
8695     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVA16rr);
8696
8697   case X86::ATOMAND8:
8698     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND8rr,
8699                                                X86::AND8ri, X86::MOV8rm,
8700                                                X86::LCMPXCHG8, X86::MOV8rr,
8701                                                X86::NOT8r, X86::AL,
8702                                                X86::GR8RegisterClass);
8703   case X86::ATOMOR8:
8704     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR8rr,
8705                                                X86::OR8ri, X86::MOV8rm,
8706                                                X86::LCMPXCHG8, X86::MOV8rr,
8707                                                X86::NOT8r, X86::AL,
8708                                                X86::GR8RegisterClass);
8709   case X86::ATOMXOR8:
8710     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR8rr,
8711                                                X86::XOR8ri, X86::MOV8rm,
8712                                                X86::LCMPXCHG8, X86::MOV8rr,
8713                                                X86::NOT8r, X86::AL,
8714                                                X86::GR8RegisterClass);
8715   case X86::ATOMNAND8:
8716     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND8rr,
8717                                                X86::AND8ri, X86::MOV8rm,
8718                                                X86::LCMPXCHG8, X86::MOV8rr,
8719                                                X86::NOT8r, X86::AL,
8720                                                X86::GR8RegisterClass, true);
8721   // FIXME: There are no CMOV8 instructions; MIN/MAX need some other way.
8722   // This group is for 64-bit host.
8723   case X86::ATOMAND64:
8724     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND64rr,
8725                                                X86::AND64ri32, X86::MOV64rm,
8726                                                X86::LCMPXCHG64, X86::MOV64rr,
8727                                                X86::NOT64r, X86::RAX,
8728                                                X86::GR64RegisterClass);
8729   case X86::ATOMOR64:
8730     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR64rr,
8731                                                X86::OR64ri32, X86::MOV64rm,
8732                                                X86::LCMPXCHG64, X86::MOV64rr,
8733                                                X86::NOT64r, X86::RAX,
8734                                                X86::GR64RegisterClass);
8735   case X86::ATOMXOR64:
8736     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR64rr,
8737                                                X86::XOR64ri32, X86::MOV64rm,
8738                                                X86::LCMPXCHG64, X86::MOV64rr,
8739                                                X86::NOT64r, X86::RAX,
8740                                                X86::GR64RegisterClass);
8741   case X86::ATOMNAND64:
8742     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND64rr,
8743                                                X86::AND64ri32, X86::MOV64rm,
8744                                                X86::LCMPXCHG64, X86::MOV64rr,
8745                                                X86::NOT64r, X86::RAX,
8746                                                X86::GR64RegisterClass, true);
8747   case X86::ATOMMIN64:
8748     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVL64rr);
8749   case X86::ATOMMAX64:
8750     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVG64rr);
8751   case X86::ATOMUMIN64:
8752     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVB64rr);
8753   case X86::ATOMUMAX64:
8754     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVA64rr);
8755
8756   // This group does 64-bit operations on a 32-bit host.
8757   case X86::ATOMAND6432:
8758     return EmitAtomicBit6432WithCustomInserter(MI, BB,
8759                                                X86::AND32rr, X86::AND32rr,
8760                                                X86::AND32ri, X86::AND32ri,
8761                                                false);
8762   case X86::ATOMOR6432:
8763     return EmitAtomicBit6432WithCustomInserter(MI, BB,
8764                                                X86::OR32rr, X86::OR32rr,
8765                                                X86::OR32ri, X86::OR32ri,
8766                                                false);
8767   case X86::ATOMXOR6432:
8768     return EmitAtomicBit6432WithCustomInserter(MI, BB,
8769                                                X86::XOR32rr, X86::XOR32rr,
8770                                                X86::XOR32ri, X86::XOR32ri,
8771                                                false);
8772   case X86::ATOMNAND6432:
8773     return EmitAtomicBit6432WithCustomInserter(MI, BB,
8774                                                X86::AND32rr, X86::AND32rr,
8775                                                X86::AND32ri, X86::AND32ri,
8776                                                true);
8777   case X86::ATOMADD6432:
8778     return EmitAtomicBit6432WithCustomInserter(MI, BB,
8779                                                X86::ADD32rr, X86::ADC32rr,
8780                                                X86::ADD32ri, X86::ADC32ri,
8781                                                false);
8782   case X86::ATOMSUB6432:
8783     return EmitAtomicBit6432WithCustomInserter(MI, BB,
8784                                                X86::SUB32rr, X86::SBB32rr,
8785                                                X86::SUB32ri, X86::SBB32ri,
8786                                                false);
8787   case X86::ATOMSWAP6432:
8788     return EmitAtomicBit6432WithCustomInserter(MI, BB,
8789                                                X86::MOV32rr, X86::MOV32rr,
8790                                                X86::MOV32ri, X86::MOV32ri,
8791                                                false);
8792   case X86::VASTART_SAVE_XMM_REGS:
8793     return EmitVAStartSaveXMMRegsWithCustomInserter(MI, BB);
8794   }
8795 }
8796
8797 //===----------------------------------------------------------------------===//
8798 //                           X86 Optimization Hooks
8799 //===----------------------------------------------------------------------===//
8800
8801 void X86TargetLowering::computeMaskedBitsForTargetNode(const SDValue Op,
8802                                                        const APInt &Mask,
8803                                                        APInt &KnownZero,
8804                                                        APInt &KnownOne,
8805                                                        const SelectionDAG &DAG,
8806                                                        unsigned Depth) const {
8807   unsigned Opc = Op.getOpcode();
8808   assert((Opc >= ISD::BUILTIN_OP_END ||
8809           Opc == ISD::INTRINSIC_WO_CHAIN ||
8810           Opc == ISD::INTRINSIC_W_CHAIN ||
8811           Opc == ISD::INTRINSIC_VOID) &&
8812          "Should use MaskedValueIsZero if you don't know whether Op"
8813          " is a target node!");
8814
8815   KnownZero = KnownOne = APInt(Mask.getBitWidth(), 0);   // Don't know anything.
8816   switch (Opc) {
8817   default: break;
8818   case X86ISD::ADD:
8819   case X86ISD::SUB:
8820   case X86ISD::SMUL:
8821   case X86ISD::UMUL:
8822   case X86ISD::INC:
8823   case X86ISD::DEC:
8824   case X86ISD::OR:
8825   case X86ISD::XOR:
8826   case X86ISD::AND:
8827     // These nodes' second result is a boolean.
8828     if (Op.getResNo() == 0)
8829       break;
8830     // Fallthrough
8831   case X86ISD::SETCC:
8832     KnownZero |= APInt::getHighBitsSet(Mask.getBitWidth(),
8833                                        Mask.getBitWidth() - 1);
8834     break;
8835   }
8836 }
8837
8838 /// isGAPlusOffset - Returns true (and the GlobalValue and the offset) if the
8839 /// node is a GlobalAddress + offset.
8840 bool X86TargetLowering::isGAPlusOffset(SDNode *N,
8841                                        GlobalValue* &GA, int64_t &Offset) const{
8842   if (N->getOpcode() == X86ISD::Wrapper) {
8843     if (isa<GlobalAddressSDNode>(N->getOperand(0))) {
8844       GA = cast<GlobalAddressSDNode>(N->getOperand(0))->getGlobal();
8845       Offset = cast<GlobalAddressSDNode>(N->getOperand(0))->getOffset();
8846       return true;
8847     }
8848   }
8849   return TargetLowering::isGAPlusOffset(N, GA, Offset);
8850 }
8851
8852 /// PerformShuffleCombine - Combine a vector_shuffle that is equal to
8853 /// build_vector load1, load2, load3, load4, <0, 1, 2, 3> into a 128-bit load
8854 /// if the load addresses are consecutive, non-overlapping, and in the right
8855 /// order.
8856 static SDValue PerformShuffleCombine(SDNode *N, SelectionDAG &DAG,
8857                                      const TargetLowering &TLI) {
8858   DebugLoc dl = N->getDebugLoc();
8859   EVT VT = N->getValueType(0);
8860   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
8861
8862   if (VT.getSizeInBits() != 128)
8863     return SDValue();
8864
8865   SmallVector<SDValue, 16> Elts;
8866   for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i)
8867     Elts.push_back(DAG.getShuffleScalarElt(SVN, i));
8868   
8869   return EltsFromConsecutiveLoads(VT, Elts, dl, DAG);
8870 }
8871
8872 /// PerformShuffleCombine - Detect vector gather/scatter index generation
8873 /// and convert it from being a bunch of shuffles and extracts to a simple
8874 /// store and scalar loads to extract the elements.
8875 static SDValue PerformEXTRACT_VECTOR_ELTCombine(SDNode *N, SelectionDAG &DAG,
8876                                                 const TargetLowering &TLI) {
8877   SDValue InputVector = N->getOperand(0);
8878
8879   // Only operate on vectors of 4 elements, where the alternative shuffling
8880   // gets to be more expensive.
8881   if (InputVector.getValueType() != MVT::v4i32)
8882     return SDValue();
8883
8884   // Check whether every use of InputVector is an EXTRACT_VECTOR_ELT with a
8885   // single use which is a sign-extend or zero-extend, and all elements are
8886   // used.
8887   SmallVector<SDNode *, 4> Uses;
8888   unsigned ExtractedElements = 0;
8889   for (SDNode::use_iterator UI = InputVector.getNode()->use_begin(),
8890        UE = InputVector.getNode()->use_end(); UI != UE; ++UI) {
8891     if (UI.getUse().getResNo() != InputVector.getResNo())
8892       return SDValue();
8893
8894     SDNode *Extract = *UI;
8895     if (Extract->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
8896       return SDValue();
8897
8898     if (Extract->getValueType(0) != MVT::i32)
8899       return SDValue();
8900     if (!Extract->hasOneUse())
8901       return SDValue();
8902     if (Extract->use_begin()->getOpcode() != ISD::SIGN_EXTEND &&
8903         Extract->use_begin()->getOpcode() != ISD::ZERO_EXTEND)
8904       return SDValue();
8905     if (!isa<ConstantSDNode>(Extract->getOperand(1)))
8906       return SDValue();
8907
8908     // Record which element was extracted.
8909     ExtractedElements |=
8910       1 << cast<ConstantSDNode>(Extract->getOperand(1))->getZExtValue();
8911
8912     Uses.push_back(Extract);
8913   }
8914
8915   // If not all the elements were used, this may not be worthwhile.
8916   if (ExtractedElements != 15)
8917     return SDValue();
8918
8919   // Ok, we've now decided to do the transformation.
8920   DebugLoc dl = InputVector.getDebugLoc();
8921
8922   // Store the value to a temporary stack slot.
8923   SDValue StackPtr = DAG.CreateStackTemporary(InputVector.getValueType());
8924   SDValue Ch = DAG.getStore(DAG.getEntryNode(), dl, InputVector, StackPtr, NULL, 0,
8925                             false, false, 0);
8926
8927   // Replace each use (extract) with a load of the appropriate element.
8928   for (SmallVectorImpl<SDNode *>::iterator UI = Uses.begin(),
8929        UE = Uses.end(); UI != UE; ++UI) {
8930     SDNode *Extract = *UI;
8931
8932     // Compute the element's address.
8933     SDValue Idx = Extract->getOperand(1);
8934     unsigned EltSize =
8935         InputVector.getValueType().getVectorElementType().getSizeInBits()/8;
8936     uint64_t Offset = EltSize * cast<ConstantSDNode>(Idx)->getZExtValue();
8937     SDValue OffsetVal = DAG.getConstant(Offset, TLI.getPointerTy());
8938
8939     SDValue ScalarAddr = DAG.getNode(ISD::ADD, dl, Idx.getValueType(), OffsetVal, StackPtr);
8940
8941     // Load the scalar.
8942     SDValue LoadScalar = DAG.getLoad(Extract->getValueType(0), dl, Ch, ScalarAddr,
8943                           NULL, 0, false, false, 0);
8944
8945     // Replace the exact with the load.
8946     DAG.ReplaceAllUsesOfValueWith(SDValue(Extract, 0), LoadScalar);
8947   }
8948
8949   // The replacement was made in place; don't return anything.
8950   return SDValue();
8951 }
8952
8953 /// PerformSELECTCombine - Do target-specific dag combines on SELECT nodes.
8954 static SDValue PerformSELECTCombine(SDNode *N, SelectionDAG &DAG,
8955                                     const X86Subtarget *Subtarget) {
8956   DebugLoc DL = N->getDebugLoc();
8957   SDValue Cond = N->getOperand(0);
8958   // Get the LHS/RHS of the select.
8959   SDValue LHS = N->getOperand(1);
8960   SDValue RHS = N->getOperand(2);
8961
8962   // If we have SSE[12] support, try to form min/max nodes. SSE min/max
8963   // instructions match the semantics of the common C idiom x<y?x:y but not
8964   // x<=y?x:y, because of how they handle negative zero (which can be
8965   // ignored in unsafe-math mode).
8966   if (Subtarget->hasSSE2() &&
8967       (LHS.getValueType() == MVT::f32 || LHS.getValueType() == MVT::f64) &&
8968       Cond.getOpcode() == ISD::SETCC) {
8969     ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
8970
8971     unsigned Opcode = 0;
8972     // Check for x CC y ? x : y.
8973     if (DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
8974         DAG.isEqualTo(RHS, Cond.getOperand(1))) {
8975       switch (CC) {
8976       default: break;
8977       case ISD::SETULT:
8978         // Converting this to a min would handle NaNs incorrectly, and swapping
8979         // the operands would cause it to handle comparisons between positive
8980         // and negative zero incorrectly.
8981         if (!FiniteOnlyFPMath() &&
8982             (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))) {
8983           if (!UnsafeFPMath &&
8984               !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
8985             break;
8986           std::swap(LHS, RHS);
8987         }
8988         Opcode = X86ISD::FMIN;
8989         break;
8990       case ISD::SETOLE:
8991         // Converting this to a min would handle comparisons between positive
8992         // and negative zero incorrectly.
8993         if (!UnsafeFPMath &&
8994             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
8995           break;
8996         Opcode = X86ISD::FMIN;
8997         break;
8998       case ISD::SETULE:
8999         // Converting this to a min would handle both negative zeros and NaNs
9000         // incorrectly, but we can swap the operands to fix both.
9001         std::swap(LHS, RHS);
9002       case ISD::SETOLT:
9003       case ISD::SETLT:
9004       case ISD::SETLE:
9005         Opcode = X86ISD::FMIN;
9006         break;
9007
9008       case ISD::SETOGE:
9009         // Converting this to a max would handle comparisons between positive
9010         // and negative zero incorrectly.
9011         if (!UnsafeFPMath &&
9012             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(LHS))
9013           break;
9014         Opcode = X86ISD::FMAX;
9015         break;
9016       case ISD::SETUGT:
9017         // Converting this to a max would handle NaNs incorrectly, and swapping
9018         // the operands would cause it to handle comparisons between positive
9019         // and negative zero incorrectly.
9020         if (!FiniteOnlyFPMath() &&
9021             (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))) {
9022           if (!UnsafeFPMath &&
9023               !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
9024             break;
9025           std::swap(LHS, RHS);
9026         }
9027         Opcode = X86ISD::FMAX;
9028         break;
9029       case ISD::SETUGE:
9030         // Converting this to a max would handle both negative zeros and NaNs
9031         // incorrectly, but we can swap the operands to fix both.
9032         std::swap(LHS, RHS);
9033       case ISD::SETOGT:
9034       case ISD::SETGT:
9035       case ISD::SETGE:
9036         Opcode = X86ISD::FMAX;
9037         break;
9038       }
9039     // Check for x CC y ? y : x -- a min/max with reversed arms.
9040     } else if (DAG.isEqualTo(LHS, Cond.getOperand(1)) &&
9041                DAG.isEqualTo(RHS, Cond.getOperand(0))) {
9042       switch (CC) {
9043       default: break;
9044       case ISD::SETOGE:
9045         // Converting this to a min would handle comparisons between positive
9046         // and negative zero incorrectly, and swapping the operands would
9047         // cause it to handle NaNs incorrectly.
9048         if (!UnsafeFPMath &&
9049             !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS))) {
9050           if (!FiniteOnlyFPMath() &&
9051               (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)))
9052             break;
9053           std::swap(LHS, RHS);
9054         }
9055         Opcode = X86ISD::FMIN;
9056         break;
9057       case ISD::SETUGT:
9058         // Converting this to a min would handle NaNs incorrectly.
9059         if (!UnsafeFPMath &&
9060             (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)))
9061           break;
9062         Opcode = X86ISD::FMIN;
9063         break;
9064       case ISD::SETUGE:
9065         // Converting this to a min would handle both negative zeros and NaNs
9066         // incorrectly, but we can swap the operands to fix both.
9067         std::swap(LHS, RHS);
9068       case ISD::SETOGT:
9069       case ISD::SETGT:
9070       case ISD::SETGE:
9071         Opcode = X86ISD::FMIN;
9072         break;
9073
9074       case ISD::SETULT:
9075         // Converting this to a max would handle NaNs incorrectly.
9076         if (!FiniteOnlyFPMath() &&
9077             (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)))
9078           break;
9079         Opcode = X86ISD::FMAX;
9080         break;
9081       case ISD::SETOLE:
9082         // Converting this to a max would handle comparisons between positive
9083         // and negative zero incorrectly, and swapping the operands would
9084         // cause it to handle NaNs incorrectly.
9085         if (!UnsafeFPMath &&
9086             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS)) {
9087           if (!FiniteOnlyFPMath() &&
9088               (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)))
9089             break;
9090           std::swap(LHS, RHS);
9091         }
9092         Opcode = X86ISD::FMAX;
9093         break;
9094       case ISD::SETULE:
9095         // Converting this to a max would handle both negative zeros and NaNs
9096         // incorrectly, but we can swap the operands to fix both.
9097         std::swap(LHS, RHS);
9098       case ISD::SETOLT:
9099       case ISD::SETLT:
9100       case ISD::SETLE:
9101         Opcode = X86ISD::FMAX;
9102         break;
9103       }
9104     }
9105
9106     if (Opcode)
9107       return DAG.getNode(Opcode, DL, N->getValueType(0), LHS, RHS);
9108   }
9109
9110   // If this is a select between two integer constants, try to do some
9111   // optimizations.
9112   if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(LHS)) {
9113     if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(RHS))
9114       // Don't do this for crazy integer types.
9115       if (DAG.getTargetLoweringInfo().isTypeLegal(LHS.getValueType())) {
9116         // If this is efficiently invertible, canonicalize the LHSC/RHSC values
9117         // so that TrueC (the true value) is larger than FalseC.
9118         bool NeedsCondInvert = false;
9119
9120         if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue()) &&
9121             // Efficiently invertible.
9122             (Cond.getOpcode() == ISD::SETCC ||  // setcc -> invertible.
9123              (Cond.getOpcode() == ISD::XOR &&   // xor(X, C) -> invertible.
9124               isa<ConstantSDNode>(Cond.getOperand(1))))) {
9125           NeedsCondInvert = true;
9126           std::swap(TrueC, FalseC);
9127         }
9128
9129         // Optimize C ? 8 : 0 -> zext(C) << 3.  Likewise for any pow2/0.
9130         if (FalseC->getAPIntValue() == 0 &&
9131             TrueC->getAPIntValue().isPowerOf2()) {
9132           if (NeedsCondInvert) // Invert the condition if needed.
9133             Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
9134                                DAG.getConstant(1, Cond.getValueType()));
9135
9136           // Zero extend the condition if needed.
9137           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, LHS.getValueType(), Cond);
9138
9139           unsigned ShAmt = TrueC->getAPIntValue().logBase2();
9140           return DAG.getNode(ISD::SHL, DL, LHS.getValueType(), Cond,
9141                              DAG.getConstant(ShAmt, MVT::i8));
9142         }
9143
9144         // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.
9145         if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
9146           if (NeedsCondInvert) // Invert the condition if needed.
9147             Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
9148                                DAG.getConstant(1, Cond.getValueType()));
9149
9150           // Zero extend the condition if needed.
9151           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
9152                              FalseC->getValueType(0), Cond);
9153           return DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
9154                              SDValue(FalseC, 0));
9155         }
9156
9157         // Optimize cases that will turn into an LEA instruction.  This requires
9158         // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
9159         if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
9160           uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
9161           if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
9162
9163           bool isFastMultiplier = false;
9164           if (Diff < 10) {
9165             switch ((unsigned char)Diff) {
9166               default: break;
9167               case 1:  // result = add base, cond
9168               case 2:  // result = lea base(    , cond*2)
9169               case 3:  // result = lea base(cond, cond*2)
9170               case 4:  // result = lea base(    , cond*4)
9171               case 5:  // result = lea base(cond, cond*4)
9172               case 8:  // result = lea base(    , cond*8)
9173               case 9:  // result = lea base(cond, cond*8)
9174                 isFastMultiplier = true;
9175                 break;
9176             }
9177           }
9178
9179           if (isFastMultiplier) {
9180             APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
9181             if (NeedsCondInvert) // Invert the condition if needed.
9182               Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
9183                                  DAG.getConstant(1, Cond.getValueType()));
9184
9185             // Zero extend the condition if needed.
9186             Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
9187                                Cond);
9188             // Scale the condition by the difference.
9189             if (Diff != 1)
9190               Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
9191                                  DAG.getConstant(Diff, Cond.getValueType()));
9192
9193             // Add the base if non-zero.
9194             if (FalseC->getAPIntValue() != 0)
9195               Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
9196                                  SDValue(FalseC, 0));
9197             return Cond;
9198           }
9199         }
9200       }
9201   }
9202
9203   return SDValue();
9204 }
9205
9206 /// Optimize X86ISD::CMOV [LHS, RHS, CONDCODE (e.g. X86::COND_NE), CONDVAL]
9207 static SDValue PerformCMOVCombine(SDNode *N, SelectionDAG &DAG,
9208                                   TargetLowering::DAGCombinerInfo &DCI) {
9209   DebugLoc DL = N->getDebugLoc();
9210
9211   // If the flag operand isn't dead, don't touch this CMOV.
9212   if (N->getNumValues() == 2 && !SDValue(N, 1).use_empty())
9213     return SDValue();
9214
9215   // If this is a select between two integer constants, try to do some
9216   // optimizations.  Note that the operands are ordered the opposite of SELECT
9217   // operands.
9218   if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(N->getOperand(1))) {
9219     if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(N->getOperand(0))) {
9220       // Canonicalize the TrueC/FalseC values so that TrueC (the true value) is
9221       // larger than FalseC (the false value).
9222       X86::CondCode CC = (X86::CondCode)N->getConstantOperandVal(2);
9223
9224       if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue())) {
9225         CC = X86::GetOppositeBranchCondition(CC);
9226         std::swap(TrueC, FalseC);
9227       }
9228
9229       // Optimize C ? 8 : 0 -> zext(setcc(C)) << 3.  Likewise for any pow2/0.
9230       // This is efficient for any integer data type (including i8/i16) and
9231       // shift amount.
9232       if (FalseC->getAPIntValue() == 0 && TrueC->getAPIntValue().isPowerOf2()) {
9233         SDValue Cond = N->getOperand(3);
9234         Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
9235                            DAG.getConstant(CC, MVT::i8), Cond);
9236
9237         // Zero extend the condition if needed.
9238         Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, TrueC->getValueType(0), Cond);
9239
9240         unsigned ShAmt = TrueC->getAPIntValue().logBase2();
9241         Cond = DAG.getNode(ISD::SHL, DL, Cond.getValueType(), Cond,
9242                            DAG.getConstant(ShAmt, MVT::i8));
9243         if (N->getNumValues() == 2)  // Dead flag value?
9244           return DCI.CombineTo(N, Cond, SDValue());
9245         return Cond;
9246       }
9247
9248       // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.  This is efficient
9249       // for any integer data type, including i8/i16.
9250       if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
9251         SDValue Cond = N->getOperand(3);
9252         Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
9253                            DAG.getConstant(CC, MVT::i8), Cond);
9254
9255         // Zero extend the condition if needed.
9256         Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
9257                            FalseC->getValueType(0), Cond);
9258         Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
9259                            SDValue(FalseC, 0));
9260
9261         if (N->getNumValues() == 2)  // Dead flag value?
9262           return DCI.CombineTo(N, Cond, SDValue());
9263         return Cond;
9264       }
9265
9266       // Optimize cases that will turn into an LEA instruction.  This requires
9267       // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
9268       if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
9269         uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
9270         if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
9271
9272         bool isFastMultiplier = false;
9273         if (Diff < 10) {
9274           switch ((unsigned char)Diff) {
9275           default: break;
9276           case 1:  // result = add base, cond
9277           case 2:  // result = lea base(    , cond*2)
9278           case 3:  // result = lea base(cond, cond*2)
9279           case 4:  // result = lea base(    , cond*4)
9280           case 5:  // result = lea base(cond, cond*4)
9281           case 8:  // result = lea base(    , cond*8)
9282           case 9:  // result = lea base(cond, cond*8)
9283             isFastMultiplier = true;
9284             break;
9285           }
9286         }
9287
9288         if (isFastMultiplier) {
9289           APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
9290           SDValue Cond = N->getOperand(3);
9291           Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
9292                              DAG.getConstant(CC, MVT::i8), Cond);
9293           // Zero extend the condition if needed.
9294           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
9295                              Cond);
9296           // Scale the condition by the difference.
9297           if (Diff != 1)
9298             Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
9299                                DAG.getConstant(Diff, Cond.getValueType()));
9300
9301           // Add the base if non-zero.
9302           if (FalseC->getAPIntValue() != 0)
9303             Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
9304                                SDValue(FalseC, 0));
9305           if (N->getNumValues() == 2)  // Dead flag value?
9306             return DCI.CombineTo(N, Cond, SDValue());
9307           return Cond;
9308         }
9309       }
9310     }
9311   }
9312   return SDValue();
9313 }
9314
9315
9316 /// PerformMulCombine - Optimize a single multiply with constant into two
9317 /// in order to implement it with two cheaper instructions, e.g.
9318 /// LEA + SHL, LEA + LEA.
9319 static SDValue PerformMulCombine(SDNode *N, SelectionDAG &DAG,
9320                                  TargetLowering::DAGCombinerInfo &DCI) {
9321   if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
9322     return SDValue();
9323
9324   EVT VT = N->getValueType(0);
9325   if (VT != MVT::i64)
9326     return SDValue();
9327
9328   ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
9329   if (!C)
9330     return SDValue();
9331   uint64_t MulAmt = C->getZExtValue();
9332   if (isPowerOf2_64(MulAmt) || MulAmt == 3 || MulAmt == 5 || MulAmt == 9)
9333     return SDValue();
9334
9335   uint64_t MulAmt1 = 0;
9336   uint64_t MulAmt2 = 0;
9337   if ((MulAmt % 9) == 0) {
9338     MulAmt1 = 9;
9339     MulAmt2 = MulAmt / 9;
9340   } else if ((MulAmt % 5) == 0) {
9341     MulAmt1 = 5;
9342     MulAmt2 = MulAmt / 5;
9343   } else if ((MulAmt % 3) == 0) {
9344     MulAmt1 = 3;
9345     MulAmt2 = MulAmt / 3;
9346   }
9347   if (MulAmt2 &&
9348       (isPowerOf2_64(MulAmt2) || MulAmt2 == 3 || MulAmt2 == 5 || MulAmt2 == 9)){
9349     DebugLoc DL = N->getDebugLoc();
9350
9351     if (isPowerOf2_64(MulAmt2) &&
9352         !(N->hasOneUse() && N->use_begin()->getOpcode() == ISD::ADD))
9353       // If second multiplifer is pow2, issue it first. We want the multiply by
9354       // 3, 5, or 9 to be folded into the addressing mode unless the lone use
9355       // is an add.
9356       std::swap(MulAmt1, MulAmt2);
9357
9358     SDValue NewMul;
9359     if (isPowerOf2_64(MulAmt1))
9360       NewMul = DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
9361                            DAG.getConstant(Log2_64(MulAmt1), MVT::i8));
9362     else
9363       NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, N->getOperand(0),
9364                            DAG.getConstant(MulAmt1, VT));
9365
9366     if (isPowerOf2_64(MulAmt2))
9367       NewMul = DAG.getNode(ISD::SHL, DL, VT, NewMul,
9368                            DAG.getConstant(Log2_64(MulAmt2), MVT::i8));
9369     else
9370       NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, NewMul,
9371                            DAG.getConstant(MulAmt2, VT));
9372
9373     // Do not add new nodes to DAG combiner worklist.
9374     DCI.CombineTo(N, NewMul, false);
9375   }
9376   return SDValue();
9377 }
9378
9379 static SDValue PerformSHLCombine(SDNode *N, SelectionDAG &DAG) {
9380   SDValue N0 = N->getOperand(0);
9381   SDValue N1 = N->getOperand(1);
9382   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
9383   EVT VT = N0.getValueType();
9384
9385   // fold (shl (and (setcc_c), c1), c2) -> (and setcc_c, (c1 << c2))
9386   // since the result of setcc_c is all zero's or all ones.
9387   if (N1C && N0.getOpcode() == ISD::AND &&
9388       N0.getOperand(1).getOpcode() == ISD::Constant) {
9389     SDValue N00 = N0.getOperand(0);
9390     if (N00.getOpcode() == X86ISD::SETCC_CARRY ||
9391         ((N00.getOpcode() == ISD::ANY_EXTEND ||
9392           N00.getOpcode() == ISD::ZERO_EXTEND) &&
9393          N00.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY)) {
9394       APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
9395       APInt ShAmt = N1C->getAPIntValue();
9396       Mask = Mask.shl(ShAmt);
9397       if (Mask != 0)
9398         return DAG.getNode(ISD::AND, N->getDebugLoc(), VT,
9399                            N00, DAG.getConstant(Mask, VT));
9400     }
9401   }
9402
9403   return SDValue();
9404 }
9405
9406 /// PerformShiftCombine - Transforms vector shift nodes to use vector shifts
9407 ///                       when possible.
9408 static SDValue PerformShiftCombine(SDNode* N, SelectionDAG &DAG,
9409                                    const X86Subtarget *Subtarget) {
9410   EVT VT = N->getValueType(0);
9411   if (!VT.isVector() && VT.isInteger() &&
9412       N->getOpcode() == ISD::SHL)
9413     return PerformSHLCombine(N, DAG);
9414
9415   // On X86 with SSE2 support, we can transform this to a vector shift if
9416   // all elements are shifted by the same amount.  We can't do this in legalize
9417   // because the a constant vector is typically transformed to a constant pool
9418   // so we have no knowledge of the shift amount.
9419   if (!Subtarget->hasSSE2())
9420     return SDValue();
9421
9422   if (VT != MVT::v2i64 && VT != MVT::v4i32 && VT != MVT::v8i16)
9423     return SDValue();
9424
9425   SDValue ShAmtOp = N->getOperand(1);
9426   EVT EltVT = VT.getVectorElementType();
9427   DebugLoc DL = N->getDebugLoc();
9428   SDValue BaseShAmt = SDValue();
9429   if (ShAmtOp.getOpcode() == ISD::BUILD_VECTOR) {
9430     unsigned NumElts = VT.getVectorNumElements();
9431     unsigned i = 0;
9432     for (; i != NumElts; ++i) {
9433       SDValue Arg = ShAmtOp.getOperand(i);
9434       if (Arg.getOpcode() == ISD::UNDEF) continue;
9435       BaseShAmt = Arg;
9436       break;
9437     }
9438     for (; i != NumElts; ++i) {
9439       SDValue Arg = ShAmtOp.getOperand(i);
9440       if (Arg.getOpcode() == ISD::UNDEF) continue;
9441       if (Arg != BaseShAmt) {
9442         return SDValue();
9443       }
9444     }
9445   } else if (ShAmtOp.getOpcode() == ISD::VECTOR_SHUFFLE &&
9446              cast<ShuffleVectorSDNode>(ShAmtOp)->isSplat()) {
9447     SDValue InVec = ShAmtOp.getOperand(0);
9448     if (InVec.getOpcode() == ISD::BUILD_VECTOR) {
9449       unsigned NumElts = InVec.getValueType().getVectorNumElements();
9450       unsigned i = 0;
9451       for (; i != NumElts; ++i) {
9452         SDValue Arg = InVec.getOperand(i);
9453         if (Arg.getOpcode() == ISD::UNDEF) continue;
9454         BaseShAmt = Arg;
9455         break;
9456       }
9457     } else if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT) {
9458        if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(InVec.getOperand(2))) {
9459          unsigned SplatIdx= cast<ShuffleVectorSDNode>(ShAmtOp)->getSplatIndex();
9460          if (C->getZExtValue() == SplatIdx)
9461            BaseShAmt = InVec.getOperand(1);
9462        }
9463     }
9464     if (BaseShAmt.getNode() == 0)
9465       BaseShAmt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, EltVT, ShAmtOp,
9466                               DAG.getIntPtrConstant(0));
9467   } else
9468     return SDValue();
9469
9470   // The shift amount is an i32.
9471   if (EltVT.bitsGT(MVT::i32))
9472     BaseShAmt = DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, BaseShAmt);
9473   else if (EltVT.bitsLT(MVT::i32))
9474     BaseShAmt = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, BaseShAmt);
9475
9476   // The shift amount is identical so we can do a vector shift.
9477   SDValue  ValOp = N->getOperand(0);
9478   switch (N->getOpcode()) {
9479   default:
9480     llvm_unreachable("Unknown shift opcode!");
9481     break;
9482   case ISD::SHL:
9483     if (VT == MVT::v2i64)
9484       return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
9485                          DAG.getConstant(Intrinsic::x86_sse2_pslli_q, MVT::i32),
9486                          ValOp, BaseShAmt);
9487     if (VT == MVT::v4i32)
9488       return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
9489                          DAG.getConstant(Intrinsic::x86_sse2_pslli_d, MVT::i32),
9490                          ValOp, BaseShAmt);
9491     if (VT == MVT::v8i16)
9492       return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
9493                          DAG.getConstant(Intrinsic::x86_sse2_pslli_w, MVT::i32),
9494                          ValOp, BaseShAmt);
9495     break;
9496   case ISD::SRA:
9497     if (VT == MVT::v4i32)
9498       return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
9499                          DAG.getConstant(Intrinsic::x86_sse2_psrai_d, MVT::i32),
9500                          ValOp, BaseShAmt);
9501     if (VT == MVT::v8i16)
9502       return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
9503                          DAG.getConstant(Intrinsic::x86_sse2_psrai_w, MVT::i32),
9504                          ValOp, BaseShAmt);
9505     break;
9506   case ISD::SRL:
9507     if (VT == MVT::v2i64)
9508       return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
9509                          DAG.getConstant(Intrinsic::x86_sse2_psrli_q, MVT::i32),
9510                          ValOp, BaseShAmt);
9511     if (VT == MVT::v4i32)
9512       return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
9513                          DAG.getConstant(Intrinsic::x86_sse2_psrli_d, MVT::i32),
9514                          ValOp, BaseShAmt);
9515     if (VT ==  MVT::v8i16)
9516       return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
9517                          DAG.getConstant(Intrinsic::x86_sse2_psrli_w, MVT::i32),
9518                          ValOp, BaseShAmt);
9519     break;
9520   }
9521   return SDValue();
9522 }
9523
9524 static SDValue PerformOrCombine(SDNode *N, SelectionDAG &DAG,
9525                                 const X86Subtarget *Subtarget) {
9526   EVT VT = N->getValueType(0);
9527   if (VT != MVT::i64 || !Subtarget->is64Bit())
9528     return SDValue();
9529
9530   // fold (or (x << c) | (y >> (64 - c))) ==> (shld64 x, y, c)
9531   SDValue N0 = N->getOperand(0);
9532   SDValue N1 = N->getOperand(1);
9533   if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL)
9534     std::swap(N0, N1);
9535   if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL)
9536     return SDValue();
9537
9538   SDValue ShAmt0 = N0.getOperand(1);
9539   if (ShAmt0.getValueType() != MVT::i8)
9540     return SDValue();
9541   SDValue ShAmt1 = N1.getOperand(1);
9542   if (ShAmt1.getValueType() != MVT::i8)
9543     return SDValue();
9544   if (ShAmt0.getOpcode() == ISD::TRUNCATE)
9545     ShAmt0 = ShAmt0.getOperand(0);
9546   if (ShAmt1.getOpcode() == ISD::TRUNCATE)
9547     ShAmt1 = ShAmt1.getOperand(0);
9548
9549   DebugLoc DL = N->getDebugLoc();
9550   unsigned Opc = X86ISD::SHLD;
9551   SDValue Op0 = N0.getOperand(0);
9552   SDValue Op1 = N1.getOperand(0);
9553   if (ShAmt0.getOpcode() == ISD::SUB) {
9554     Opc = X86ISD::SHRD;
9555     std::swap(Op0, Op1);
9556     std::swap(ShAmt0, ShAmt1);
9557   }
9558
9559   if (ShAmt1.getOpcode() == ISD::SUB) {
9560     SDValue Sum = ShAmt1.getOperand(0);
9561     if (ConstantSDNode *SumC = dyn_cast<ConstantSDNode>(Sum)) {
9562       if (SumC->getSExtValue() == 64 &&
9563           ShAmt1.getOperand(1) == ShAmt0)
9564         return DAG.getNode(Opc, DL, VT,
9565                            Op0, Op1,
9566                            DAG.getNode(ISD::TRUNCATE, DL,
9567                                        MVT::i8, ShAmt0));
9568     }
9569   } else if (ConstantSDNode *ShAmt1C = dyn_cast<ConstantSDNode>(ShAmt1)) {
9570     ConstantSDNode *ShAmt0C = dyn_cast<ConstantSDNode>(ShAmt0);
9571     if (ShAmt0C &&
9572         ShAmt0C->getSExtValue() + ShAmt1C->getSExtValue() == 64)
9573       return DAG.getNode(Opc, DL, VT,
9574                          N0.getOperand(0), N1.getOperand(0),
9575                          DAG.getNode(ISD::TRUNCATE, DL,
9576                                        MVT::i8, ShAmt0));
9577   }
9578
9579   return SDValue();
9580 }
9581
9582 /// PerformSTORECombine - Do target-specific dag combines on STORE nodes.
9583 static SDValue PerformSTORECombine(SDNode *N, SelectionDAG &DAG,
9584                                    const X86Subtarget *Subtarget) {
9585   // Turn load->store of MMX types into GPR load/stores.  This avoids clobbering
9586   // the FP state in cases where an emms may be missing.
9587   // A preferable solution to the general problem is to figure out the right
9588   // places to insert EMMS.  This qualifies as a quick hack.
9589
9590   // Similarly, turn load->store of i64 into double load/stores in 32-bit mode.
9591   StoreSDNode *St = cast<StoreSDNode>(N);
9592   EVT VT = St->getValue().getValueType();
9593   if (VT.getSizeInBits() != 64)
9594     return SDValue();
9595
9596   const Function *F = DAG.getMachineFunction().getFunction();
9597   bool NoImplicitFloatOps = F->hasFnAttr(Attribute::NoImplicitFloat);
9598   bool F64IsLegal = !UseSoftFloat && !NoImplicitFloatOps
9599     && Subtarget->hasSSE2();
9600   if ((VT.isVector() ||
9601        (VT == MVT::i64 && F64IsLegal && !Subtarget->is64Bit())) &&
9602       isa<LoadSDNode>(St->getValue()) &&
9603       !cast<LoadSDNode>(St->getValue())->isVolatile() &&
9604       St->getChain().hasOneUse() && !St->isVolatile()) {
9605     SDNode* LdVal = St->getValue().getNode();
9606     LoadSDNode *Ld = 0;
9607     int TokenFactorIndex = -1;
9608     SmallVector<SDValue, 8> Ops;
9609     SDNode* ChainVal = St->getChain().getNode();
9610     // Must be a store of a load.  We currently handle two cases:  the load
9611     // is a direct child, and it's under an intervening TokenFactor.  It is
9612     // possible to dig deeper under nested TokenFactors.
9613     if (ChainVal == LdVal)
9614       Ld = cast<LoadSDNode>(St->getChain());
9615     else if (St->getValue().hasOneUse() &&
9616              ChainVal->getOpcode() == ISD::TokenFactor) {
9617       for (unsigned i=0, e = ChainVal->getNumOperands(); i != e; ++i) {
9618         if (ChainVal->getOperand(i).getNode() == LdVal) {
9619           TokenFactorIndex = i;
9620           Ld = cast<LoadSDNode>(St->getValue());
9621         } else
9622           Ops.push_back(ChainVal->getOperand(i));
9623       }
9624     }
9625
9626     if (!Ld || !ISD::isNormalLoad(Ld))
9627       return SDValue();
9628
9629     // If this is not the MMX case, i.e. we are just turning i64 load/store
9630     // into f64 load/store, avoid the transformation if there are multiple
9631     // uses of the loaded value.
9632     if (!VT.isVector() && !Ld->hasNUsesOfValue(1, 0))
9633       return SDValue();
9634
9635     DebugLoc LdDL = Ld->getDebugLoc();
9636     DebugLoc StDL = N->getDebugLoc();
9637     // If we are a 64-bit capable x86, lower to a single movq load/store pair.
9638     // Otherwise, if it's legal to use f64 SSE instructions, use f64 load/store
9639     // pair instead.
9640     if (Subtarget->is64Bit() || F64IsLegal) {
9641       EVT LdVT = Subtarget->is64Bit() ? MVT::i64 : MVT::f64;
9642       SDValue NewLd = DAG.getLoad(LdVT, LdDL, Ld->getChain(),
9643                                   Ld->getBasePtr(), Ld->getSrcValue(),
9644                                   Ld->getSrcValueOffset(), Ld->isVolatile(),
9645                                   Ld->isNonTemporal(), Ld->getAlignment());
9646       SDValue NewChain = NewLd.getValue(1);
9647       if (TokenFactorIndex != -1) {
9648         Ops.push_back(NewChain);
9649         NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, &Ops[0],
9650                                Ops.size());
9651       }
9652       return DAG.getStore(NewChain, StDL, NewLd, St->getBasePtr(),
9653                           St->getSrcValue(), St->getSrcValueOffset(),
9654                           St->isVolatile(), St->isNonTemporal(),
9655                           St->getAlignment());
9656     }
9657
9658     // Otherwise, lower to two pairs of 32-bit loads / stores.
9659     SDValue LoAddr = Ld->getBasePtr();
9660     SDValue HiAddr = DAG.getNode(ISD::ADD, LdDL, MVT::i32, LoAddr,
9661                                  DAG.getConstant(4, MVT::i32));
9662
9663     SDValue LoLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), LoAddr,
9664                                Ld->getSrcValue(), Ld->getSrcValueOffset(),
9665                                Ld->isVolatile(), Ld->isNonTemporal(),
9666                                Ld->getAlignment());
9667     SDValue HiLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), HiAddr,
9668                                Ld->getSrcValue(), Ld->getSrcValueOffset()+4,
9669                                Ld->isVolatile(), Ld->isNonTemporal(),
9670                                MinAlign(Ld->getAlignment(), 4));
9671
9672     SDValue NewChain = LoLd.getValue(1);
9673     if (TokenFactorIndex != -1) {
9674       Ops.push_back(LoLd);
9675       Ops.push_back(HiLd);
9676       NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, &Ops[0],
9677                              Ops.size());
9678     }
9679
9680     LoAddr = St->getBasePtr();
9681     HiAddr = DAG.getNode(ISD::ADD, StDL, MVT::i32, LoAddr,
9682                          DAG.getConstant(4, MVT::i32));
9683
9684     SDValue LoSt = DAG.getStore(NewChain, StDL, LoLd, LoAddr,
9685                                 St->getSrcValue(), St->getSrcValueOffset(),
9686                                 St->isVolatile(), St->isNonTemporal(),
9687                                 St->getAlignment());
9688     SDValue HiSt = DAG.getStore(NewChain, StDL, HiLd, HiAddr,
9689                                 St->getSrcValue(),
9690                                 St->getSrcValueOffset() + 4,
9691                                 St->isVolatile(),
9692                                 St->isNonTemporal(),
9693                                 MinAlign(St->getAlignment(), 4));
9694     return DAG.getNode(ISD::TokenFactor, StDL, MVT::Other, LoSt, HiSt);
9695   }
9696   return SDValue();
9697 }
9698
9699 /// PerformFORCombine - Do target-specific dag combines on X86ISD::FOR and
9700 /// X86ISD::FXOR nodes.
9701 static SDValue PerformFORCombine(SDNode *N, SelectionDAG &DAG) {
9702   assert(N->getOpcode() == X86ISD::FOR || N->getOpcode() == X86ISD::FXOR);
9703   // F[X]OR(0.0, x) -> x
9704   // F[X]OR(x, 0.0) -> x
9705   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
9706     if (C->getValueAPF().isPosZero())
9707       return N->getOperand(1);
9708   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
9709     if (C->getValueAPF().isPosZero())
9710       return N->getOperand(0);
9711   return SDValue();
9712 }
9713
9714 /// PerformFANDCombine - Do target-specific dag combines on X86ISD::FAND nodes.
9715 static SDValue PerformFANDCombine(SDNode *N, SelectionDAG &DAG) {
9716   // FAND(0.0, x) -> 0.0
9717   // FAND(x, 0.0) -> 0.0
9718   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
9719     if (C->getValueAPF().isPosZero())
9720       return N->getOperand(0);
9721   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
9722     if (C->getValueAPF().isPosZero())
9723       return N->getOperand(1);
9724   return SDValue();
9725 }
9726
9727 static SDValue PerformBTCombine(SDNode *N,
9728                                 SelectionDAG &DAG,
9729                                 TargetLowering::DAGCombinerInfo &DCI) {
9730   // BT ignores high bits in the bit index operand.
9731   SDValue Op1 = N->getOperand(1);
9732   if (Op1.hasOneUse()) {
9733     unsigned BitWidth = Op1.getValueSizeInBits();
9734     APInt DemandedMask = APInt::getLowBitsSet(BitWidth, Log2_32(BitWidth));
9735     APInt KnownZero, KnownOne;
9736     TargetLowering::TargetLoweringOpt TLO(DAG);
9737     TargetLowering &TLI = DAG.getTargetLoweringInfo();
9738     if (TLO.ShrinkDemandedConstant(Op1, DemandedMask) ||
9739         TLI.SimplifyDemandedBits(Op1, DemandedMask, KnownZero, KnownOne, TLO))
9740       DCI.CommitTargetLoweringOpt(TLO);
9741   }
9742   return SDValue();
9743 }
9744
9745 static SDValue PerformVZEXT_MOVLCombine(SDNode *N, SelectionDAG &DAG) {
9746   SDValue Op = N->getOperand(0);
9747   if (Op.getOpcode() == ISD::BIT_CONVERT)
9748     Op = Op.getOperand(0);
9749   EVT VT = N->getValueType(0), OpVT = Op.getValueType();
9750   if (Op.getOpcode() == X86ISD::VZEXT_LOAD &&
9751       VT.getVectorElementType().getSizeInBits() ==
9752       OpVT.getVectorElementType().getSizeInBits()) {
9753     return DAG.getNode(ISD::BIT_CONVERT, N->getDebugLoc(), VT, Op);
9754   }
9755   return SDValue();
9756 }
9757
9758 // On X86 and X86-64, atomic operations are lowered to locked instructions.
9759 // Locked instructions, in turn, have implicit fence semantics (all memory
9760 // operations are flushed before issuing the locked instruction, and the
9761 // are not buffered), so we can fold away the common pattern of
9762 // fence-atomic-fence.
9763 static SDValue PerformMEMBARRIERCombine(SDNode* N, SelectionDAG &DAG) {
9764   SDValue atomic = N->getOperand(0);
9765   switch (atomic.getOpcode()) {
9766     case ISD::ATOMIC_CMP_SWAP:
9767     case ISD::ATOMIC_SWAP:
9768     case ISD::ATOMIC_LOAD_ADD:
9769     case ISD::ATOMIC_LOAD_SUB:
9770     case ISD::ATOMIC_LOAD_AND:
9771     case ISD::ATOMIC_LOAD_OR:
9772     case ISD::ATOMIC_LOAD_XOR:
9773     case ISD::ATOMIC_LOAD_NAND:
9774     case ISD::ATOMIC_LOAD_MIN:
9775     case ISD::ATOMIC_LOAD_MAX:
9776     case ISD::ATOMIC_LOAD_UMIN:
9777     case ISD::ATOMIC_LOAD_UMAX:
9778       break;
9779     default:
9780       return SDValue();
9781   }
9782
9783   SDValue fence = atomic.getOperand(0);
9784   if (fence.getOpcode() != ISD::MEMBARRIER)
9785     return SDValue();
9786
9787   switch (atomic.getOpcode()) {
9788     case ISD::ATOMIC_CMP_SWAP:
9789       return DAG.UpdateNodeOperands(atomic, fence.getOperand(0),
9790                                     atomic.getOperand(1), atomic.getOperand(2),
9791                                     atomic.getOperand(3));
9792     case ISD::ATOMIC_SWAP:
9793     case ISD::ATOMIC_LOAD_ADD:
9794     case ISD::ATOMIC_LOAD_SUB:
9795     case ISD::ATOMIC_LOAD_AND:
9796     case ISD::ATOMIC_LOAD_OR:
9797     case ISD::ATOMIC_LOAD_XOR:
9798     case ISD::ATOMIC_LOAD_NAND:
9799     case ISD::ATOMIC_LOAD_MIN:
9800     case ISD::ATOMIC_LOAD_MAX:
9801     case ISD::ATOMIC_LOAD_UMIN:
9802     case ISD::ATOMIC_LOAD_UMAX:
9803       return DAG.UpdateNodeOperands(atomic, fence.getOperand(0),
9804                                     atomic.getOperand(1), atomic.getOperand(2));
9805     default:
9806       return SDValue();
9807   }
9808 }
9809
9810 static SDValue PerformZExtCombine(SDNode *N, SelectionDAG &DAG) {
9811   // (i32 zext (and (i8  x86isd::setcc_carry), 1)) ->
9812   //           (and (i32 x86isd::setcc_carry), 1)
9813   // This eliminates the zext. This transformation is necessary because
9814   // ISD::SETCC is always legalized to i8.
9815   DebugLoc dl = N->getDebugLoc();
9816   SDValue N0 = N->getOperand(0);
9817   EVT VT = N->getValueType(0);
9818   if (N0.getOpcode() == ISD::AND &&
9819       N0.hasOneUse() &&
9820       N0.getOperand(0).hasOneUse()) {
9821     SDValue N00 = N0.getOperand(0);
9822     if (N00.getOpcode() != X86ISD::SETCC_CARRY)
9823       return SDValue();
9824     ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
9825     if (!C || C->getZExtValue() != 1)
9826       return SDValue();
9827     return DAG.getNode(ISD::AND, dl, VT,
9828                        DAG.getNode(X86ISD::SETCC_CARRY, dl, VT,
9829                                    N00.getOperand(0), N00.getOperand(1)),
9830                        DAG.getConstant(1, VT));
9831   }
9832
9833   return SDValue();
9834 }
9835
9836 SDValue X86TargetLowering::PerformDAGCombine(SDNode *N,
9837                                              DAGCombinerInfo &DCI) const {
9838   SelectionDAG &DAG = DCI.DAG;
9839   switch (N->getOpcode()) {
9840   default: break;
9841   case ISD::VECTOR_SHUFFLE: return PerformShuffleCombine(N, DAG, *this);
9842   case ISD::EXTRACT_VECTOR_ELT:
9843                         return PerformEXTRACT_VECTOR_ELTCombine(N, DAG, *this);
9844   case ISD::SELECT:         return PerformSELECTCombine(N, DAG, Subtarget);
9845   case X86ISD::CMOV:        return PerformCMOVCombine(N, DAG, DCI);
9846   case ISD::MUL:            return PerformMulCombine(N, DAG, DCI);
9847   case ISD::SHL:
9848   case ISD::SRA:
9849   case ISD::SRL:            return PerformShiftCombine(N, DAG, Subtarget);
9850   case ISD::OR:             return PerformOrCombine(N, DAG, Subtarget);
9851   case ISD::STORE:          return PerformSTORECombine(N, DAG, Subtarget);
9852   case X86ISD::FXOR:
9853   case X86ISD::FOR:         return PerformFORCombine(N, DAG);
9854   case X86ISD::FAND:        return PerformFANDCombine(N, DAG);
9855   case X86ISD::BT:          return PerformBTCombine(N, DAG, DCI);
9856   case X86ISD::VZEXT_MOVL:  return PerformVZEXT_MOVLCombine(N, DAG);
9857   case ISD::MEMBARRIER:     return PerformMEMBARRIERCombine(N, DAG);
9858   case ISD::ZERO_EXTEND:    return PerformZExtCombine(N, DAG);
9859   }
9860
9861   return SDValue();
9862 }
9863
9864 //===----------------------------------------------------------------------===//
9865 //                           X86 Inline Assembly Support
9866 //===----------------------------------------------------------------------===//
9867
9868 static bool LowerToBSwap(CallInst *CI) {
9869   // FIXME: this should verify that we are targetting a 486 or better.  If not,
9870   // we will turn this bswap into something that will be lowered to logical ops
9871   // instead of emitting the bswap asm.  For now, we don't support 486 or lower
9872   // so don't worry about this.
9873
9874   // Verify this is a simple bswap.
9875   if (CI->getNumOperands() != 2 ||
9876       CI->getType() != CI->getOperand(1)->getType() ||
9877       !CI->getType()->isIntegerTy())
9878     return false;
9879
9880   const IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
9881   if (!Ty || Ty->getBitWidth() % 16 != 0)
9882     return false;
9883
9884   // Okay, we can do this xform, do so now.
9885   const Type *Tys[] = { Ty };
9886   Module *M = CI->getParent()->getParent()->getParent();
9887   Constant *Int = Intrinsic::getDeclaration(M, Intrinsic::bswap, Tys, 1);
9888
9889   Value *Op = CI->getOperand(1);
9890   Op = CallInst::Create(Int, Op, CI->getName(), CI);
9891
9892   CI->replaceAllUsesWith(Op);
9893   CI->eraseFromParent();
9894   return true;
9895 }
9896
9897 bool X86TargetLowering::ExpandInlineAsm(CallInst *CI) const {
9898   InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue());
9899   std::vector<InlineAsm::ConstraintInfo> Constraints = IA->ParseConstraints();
9900
9901   std::string AsmStr = IA->getAsmString();
9902
9903   // TODO: should remove alternatives from the asmstring: "foo {a|b}" -> "foo a"
9904   SmallVector<StringRef, 4> AsmPieces;
9905   SplitString(AsmStr, AsmPieces, "\n");  // ; as separator?
9906
9907   switch (AsmPieces.size()) {
9908   default: return false;
9909   case 1:
9910     AsmStr = AsmPieces[0];
9911     AsmPieces.clear();
9912     SplitString(AsmStr, AsmPieces, " \t");  // Split with whitespace.
9913
9914     // bswap $0
9915     if (AsmPieces.size() == 2 &&
9916         (AsmPieces[0] == "bswap" ||
9917          AsmPieces[0] == "bswapq" ||
9918          AsmPieces[0] == "bswapl") &&
9919         (AsmPieces[1] == "$0" ||
9920          AsmPieces[1] == "${0:q}")) {
9921       // No need to check constraints, nothing other than the equivalent of
9922       // "=r,0" would be valid here.
9923       return LowerToBSwap(CI);
9924     }
9925     // rorw $$8, ${0:w}  -->  llvm.bswap.i16
9926     if (CI->getType()->isIntegerTy(16) &&
9927         AsmPieces.size() == 3 &&
9928         (AsmPieces[0] == "rorw" || AsmPieces[0] == "rolw") &&
9929         AsmPieces[1] == "$$8," &&
9930         AsmPieces[2] == "${0:w}" &&
9931         IA->getConstraintString().compare(0, 5, "=r,0,") == 0) {
9932       AsmPieces.clear();
9933       const std::string &Constraints = IA->getConstraintString();
9934       SplitString(StringRef(Constraints).substr(5), AsmPieces, ",");
9935       std::sort(AsmPieces.begin(), AsmPieces.end());
9936       if (AsmPieces.size() == 4 &&
9937           AsmPieces[0] == "~{cc}" &&
9938           AsmPieces[1] == "~{dirflag}" &&
9939           AsmPieces[2] == "~{flags}" &&
9940           AsmPieces[3] == "~{fpsr}") {
9941         return LowerToBSwap(CI);
9942       }
9943     }
9944     break;
9945   case 3:
9946     if (CI->getType()->isIntegerTy(64) &&
9947         Constraints.size() >= 2 &&
9948         Constraints[0].Codes.size() == 1 && Constraints[0].Codes[0] == "A" &&
9949         Constraints[1].Codes.size() == 1 && Constraints[1].Codes[0] == "0") {
9950       // bswap %eax / bswap %edx / xchgl %eax, %edx  -> llvm.bswap.i64
9951       SmallVector<StringRef, 4> Words;
9952       SplitString(AsmPieces[0], Words, " \t");
9953       if (Words.size() == 2 && Words[0] == "bswap" && Words[1] == "%eax") {
9954         Words.clear();
9955         SplitString(AsmPieces[1], Words, " \t");
9956         if (Words.size() == 2 && Words[0] == "bswap" && Words[1] == "%edx") {
9957           Words.clear();
9958           SplitString(AsmPieces[2], Words, " \t,");
9959           if (Words.size() == 3 && Words[0] == "xchgl" && Words[1] == "%eax" &&
9960               Words[2] == "%edx") {
9961             return LowerToBSwap(CI);
9962           }
9963         }
9964       }
9965     }
9966     break;
9967   }
9968   return false;
9969 }
9970
9971
9972
9973 /// getConstraintType - Given a constraint letter, return the type of
9974 /// constraint it is for this target.
9975 X86TargetLowering::ConstraintType
9976 X86TargetLowering::getConstraintType(const std::string &Constraint) const {
9977   if (Constraint.size() == 1) {
9978     switch (Constraint[0]) {
9979     case 'A':
9980       return C_Register;
9981     case 'f':
9982     case 'r':
9983     case 'R':
9984     case 'l':
9985     case 'q':
9986     case 'Q':
9987     case 'x':
9988     case 'y':
9989     case 'Y':
9990       return C_RegisterClass;
9991     case 'e':
9992     case 'Z':
9993       return C_Other;
9994     default:
9995       break;
9996     }
9997   }
9998   return TargetLowering::getConstraintType(Constraint);
9999 }
10000
10001 /// LowerXConstraint - try to replace an X constraint, which matches anything,
10002 /// with another that has more specific requirements based on the type of the
10003 /// corresponding operand.
10004 const char *X86TargetLowering::
10005 LowerXConstraint(EVT ConstraintVT) const {
10006   // FP X constraints get lowered to SSE1/2 registers if available, otherwise
10007   // 'f' like normal targets.
10008   if (ConstraintVT.isFloatingPoint()) {
10009     if (Subtarget->hasSSE2())
10010       return "Y";
10011     if (Subtarget->hasSSE1())
10012       return "x";
10013   }
10014
10015   return TargetLowering::LowerXConstraint(ConstraintVT);
10016 }
10017
10018 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
10019 /// vector.  If it is invalid, don't add anything to Ops.
10020 void X86TargetLowering::LowerAsmOperandForConstraint(SDValue Op,
10021                                                      char Constraint,
10022                                                      bool hasMemory,
10023                                                      std::vector<SDValue>&Ops,
10024                                                      SelectionDAG &DAG) const {
10025   SDValue Result(0, 0);
10026
10027   switch (Constraint) {
10028   default: break;
10029   case 'I':
10030     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
10031       if (C->getZExtValue() <= 31) {
10032         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
10033         break;
10034       }
10035     }
10036     return;
10037   case 'J':
10038     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
10039       if (C->getZExtValue() <= 63) {
10040         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
10041         break;
10042       }
10043     }
10044     return;
10045   case 'K':
10046     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
10047       if ((int8_t)C->getSExtValue() == C->getSExtValue()) {
10048         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
10049         break;
10050       }
10051     }
10052     return;
10053   case 'N':
10054     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
10055       if (C->getZExtValue() <= 255) {
10056         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
10057         break;
10058       }
10059     }
10060     return;
10061   case 'e': {
10062     // 32-bit signed value
10063     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
10064       const ConstantInt *CI = C->getConstantIntValue();
10065       if (CI->isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
10066                                   C->getSExtValue())) {
10067         // Widen to 64 bits here to get it sign extended.
10068         Result = DAG.getTargetConstant(C->getSExtValue(), MVT::i64);
10069         break;
10070       }
10071     // FIXME gcc accepts some relocatable values here too, but only in certain
10072     // memory models; it's complicated.
10073     }
10074     return;
10075   }
10076   case 'Z': {
10077     // 32-bit unsigned value
10078     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
10079       const ConstantInt *CI = C->getConstantIntValue();
10080       if (CI->isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
10081                                   C->getZExtValue())) {
10082         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
10083         break;
10084       }
10085     }
10086     // FIXME gcc accepts some relocatable values here too, but only in certain
10087     // memory models; it's complicated.
10088     return;
10089   }
10090   case 'i': {
10091     // Literal immediates are always ok.
10092     if (ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op)) {
10093       // Widen to 64 bits here to get it sign extended.
10094       Result = DAG.getTargetConstant(CST->getSExtValue(), MVT::i64);
10095       break;
10096     }
10097
10098     // If we are in non-pic codegen mode, we allow the address of a global (with
10099     // an optional displacement) to be used with 'i'.
10100     GlobalAddressSDNode *GA = 0;
10101     int64_t Offset = 0;
10102
10103     // Match either (GA), (GA+C), (GA+C1+C2), etc.
10104     while (1) {
10105       if ((GA = dyn_cast<GlobalAddressSDNode>(Op))) {
10106         Offset += GA->getOffset();
10107         break;
10108       } else if (Op.getOpcode() == ISD::ADD) {
10109         if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
10110           Offset += C->getZExtValue();
10111           Op = Op.getOperand(0);
10112           continue;
10113         }
10114       } else if (Op.getOpcode() == ISD::SUB) {
10115         if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
10116           Offset += -C->getZExtValue();
10117           Op = Op.getOperand(0);
10118           continue;
10119         }
10120       }
10121
10122       // Otherwise, this isn't something we can handle, reject it.
10123       return;
10124     }
10125
10126     GlobalValue *GV = GA->getGlobal();
10127     // If we require an extra load to get this address, as in PIC mode, we
10128     // can't accept it.
10129     if (isGlobalStubReference(Subtarget->ClassifyGlobalReference(GV,
10130                                                         getTargetMachine())))
10131       return;
10132
10133     if (hasMemory)
10134       Op = LowerGlobalAddress(GV, Op.getDebugLoc(), Offset, DAG);
10135     else
10136       Op = DAG.getTargetGlobalAddress(GV, GA->getValueType(0), Offset);
10137     Result = Op;
10138     break;
10139   }
10140   }
10141
10142   if (Result.getNode()) {
10143     Ops.push_back(Result);
10144     return;
10145   }
10146   return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, hasMemory,
10147                                                       Ops, DAG);
10148 }
10149
10150 std::vector<unsigned> X86TargetLowering::
10151 getRegClassForInlineAsmConstraint(const std::string &Constraint,
10152                                   EVT VT) const {
10153   if (Constraint.size() == 1) {
10154     // FIXME: not handling fp-stack yet!
10155     switch (Constraint[0]) {      // GCC X86 Constraint Letters
10156     default: break;  // Unknown constraint letter
10157     case 'q':   // GENERAL_REGS in 64-bit mode, Q_REGS in 32-bit mode.
10158       if (Subtarget->is64Bit()) {
10159         if (VT == MVT::i32)
10160           return make_vector<unsigned>(X86::EAX, X86::EDX, X86::ECX, X86::EBX,
10161                                        X86::ESI, X86::EDI, X86::R8D, X86::R9D,
10162                                        X86::R10D,X86::R11D,X86::R12D,
10163                                        X86::R13D,X86::R14D,X86::R15D,
10164                                        X86::EBP, X86::ESP, 0);
10165         else if (VT == MVT::i16)
10166           return make_vector<unsigned>(X86::AX,  X86::DX,  X86::CX, X86::BX,
10167                                        X86::SI,  X86::DI,  X86::R8W,X86::R9W,
10168                                        X86::R10W,X86::R11W,X86::R12W,
10169                                        X86::R13W,X86::R14W,X86::R15W,
10170                                        X86::BP,  X86::SP, 0);
10171         else if (VT == MVT::i8)
10172           return make_vector<unsigned>(X86::AL,  X86::DL,  X86::CL, X86::BL,
10173                                        X86::SIL, X86::DIL, X86::R8B,X86::R9B,
10174                                        X86::R10B,X86::R11B,X86::R12B,
10175                                        X86::R13B,X86::R14B,X86::R15B,
10176                                        X86::BPL, X86::SPL, 0);
10177
10178         else if (VT == MVT::i64)
10179           return make_vector<unsigned>(X86::RAX, X86::RDX, X86::RCX, X86::RBX,
10180                                        X86::RSI, X86::RDI, X86::R8,  X86::R9,
10181                                        X86::R10, X86::R11, X86::R12,
10182                                        X86::R13, X86::R14, X86::R15,
10183                                        X86::RBP, X86::RSP, 0);
10184
10185         break;
10186       }
10187       // 32-bit fallthrough
10188     case 'Q':   // Q_REGS
10189       if (VT == MVT::i32)
10190         return make_vector<unsigned>(X86::EAX, X86::EDX, X86::ECX, X86::EBX, 0);
10191       else if (VT == MVT::i16)
10192         return make_vector<unsigned>(X86::AX, X86::DX, X86::CX, X86::BX, 0);
10193       else if (VT == MVT::i8)
10194         return make_vector<unsigned>(X86::AL, X86::DL, X86::CL, X86::BL, 0);
10195       else if (VT == MVT::i64)
10196         return make_vector<unsigned>(X86::RAX, X86::RDX, X86::RCX, X86::RBX, 0);
10197       break;
10198     }
10199   }
10200
10201   return std::vector<unsigned>();
10202 }
10203
10204 std::pair<unsigned, const TargetRegisterClass*>
10205 X86TargetLowering::getRegForInlineAsmConstraint(const std::string &Constraint,
10206                                                 EVT VT) const {
10207   // First, see if this is a constraint that directly corresponds to an LLVM
10208   // register class.
10209   if (Constraint.size() == 1) {
10210     // GCC Constraint Letters
10211     switch (Constraint[0]) {
10212     default: break;
10213     case 'r':   // GENERAL_REGS
10214     case 'l':   // INDEX_REGS
10215       if (VT == MVT::i8)
10216         return std::make_pair(0U, X86::GR8RegisterClass);
10217       if (VT == MVT::i16)
10218         return std::make_pair(0U, X86::GR16RegisterClass);
10219       if (VT == MVT::i32 || !Subtarget->is64Bit())
10220         return std::make_pair(0U, X86::GR32RegisterClass);
10221       return std::make_pair(0U, X86::GR64RegisterClass);
10222     case 'R':   // LEGACY_REGS
10223       if (VT == MVT::i8)
10224         return std::make_pair(0U, X86::GR8_NOREXRegisterClass);
10225       if (VT == MVT::i16)
10226         return std::make_pair(0U, X86::GR16_NOREXRegisterClass);
10227       if (VT == MVT::i32 || !Subtarget->is64Bit())
10228         return std::make_pair(0U, X86::GR32_NOREXRegisterClass);
10229       return std::make_pair(0U, X86::GR64_NOREXRegisterClass);
10230     case 'f':  // FP Stack registers.
10231       // If SSE is enabled for this VT, use f80 to ensure the isel moves the
10232       // value to the correct fpstack register class.
10233       if (VT == MVT::f32 && !isScalarFPTypeInSSEReg(VT))
10234         return std::make_pair(0U, X86::RFP32RegisterClass);
10235       if (VT == MVT::f64 && !isScalarFPTypeInSSEReg(VT))
10236         return std::make_pair(0U, X86::RFP64RegisterClass);
10237       return std::make_pair(0U, X86::RFP80RegisterClass);
10238     case 'y':   // MMX_REGS if MMX allowed.
10239       if (!Subtarget->hasMMX()) break;
10240       return std::make_pair(0U, X86::VR64RegisterClass);
10241     case 'Y':   // SSE_REGS if SSE2 allowed
10242       if (!Subtarget->hasSSE2()) break;
10243       // FALL THROUGH.
10244     case 'x':   // SSE_REGS if SSE1 allowed
10245       if (!Subtarget->hasSSE1()) break;
10246
10247       switch (VT.getSimpleVT().SimpleTy) {
10248       default: break;
10249       // Scalar SSE types.
10250       case MVT::f32:
10251       case MVT::i32:
10252         return std::make_pair(0U, X86::FR32RegisterClass);
10253       case MVT::f64:
10254       case MVT::i64:
10255         return std::make_pair(0U, X86::FR64RegisterClass);
10256       // Vector types.
10257       case MVT::v16i8:
10258       case MVT::v8i16:
10259       case MVT::v4i32:
10260       case MVT::v2i64:
10261       case MVT::v4f32:
10262       case MVT::v2f64:
10263         return std::make_pair(0U, X86::VR128RegisterClass);
10264       }
10265       break;
10266     }
10267   }
10268
10269   // Use the default implementation in TargetLowering to convert the register
10270   // constraint into a member of a register class.
10271   std::pair<unsigned, const TargetRegisterClass*> Res;
10272   Res = TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
10273
10274   // Not found as a standard register?
10275   if (Res.second == 0) {
10276     // Map st(0) -> st(7) -> ST0
10277     if (Constraint.size() == 7 && Constraint[0] == '{' &&
10278         tolower(Constraint[1]) == 's' &&
10279         tolower(Constraint[2]) == 't' &&
10280         Constraint[3] == '(' &&
10281         (Constraint[4] >= '0' && Constraint[4] <= '7') &&
10282         Constraint[5] == ')' &&
10283         Constraint[6] == '}') {
10284
10285       Res.first = X86::ST0+Constraint[4]-'0';
10286       Res.second = X86::RFP80RegisterClass;
10287       return Res;
10288     }
10289
10290     // GCC allows "st(0)" to be called just plain "st".
10291     if (StringRef("{st}").equals_lower(Constraint)) {
10292       Res.first = X86::ST0;
10293       Res.second = X86::RFP80RegisterClass;
10294       return Res;
10295     }
10296
10297     // flags -> EFLAGS
10298     if (StringRef("{flags}").equals_lower(Constraint)) {
10299       Res.first = X86::EFLAGS;
10300       Res.second = X86::CCRRegisterClass;
10301       return Res;
10302     }
10303
10304     // 'A' means EAX + EDX.
10305     if (Constraint == "A") {
10306       Res.first = X86::EAX;
10307       Res.second = X86::GR32_ADRegisterClass;
10308       return Res;
10309     }
10310     return Res;
10311   }
10312
10313   // Otherwise, check to see if this is a register class of the wrong value
10314   // type.  For example, we want to map "{ax},i32" -> {eax}, we don't want it to
10315   // turn into {ax},{dx}.
10316   if (Res.second->hasType(VT))
10317     return Res;   // Correct type already, nothing to do.
10318
10319   // All of the single-register GCC register classes map their values onto
10320   // 16-bit register pieces "ax","dx","cx","bx","si","di","bp","sp".  If we
10321   // really want an 8-bit or 32-bit register, map to the appropriate register
10322   // class and return the appropriate register.
10323   if (Res.second == X86::GR16RegisterClass) {
10324     if (VT == MVT::i8) {
10325       unsigned DestReg = 0;
10326       switch (Res.first) {
10327       default: break;
10328       case X86::AX: DestReg = X86::AL; break;
10329       case X86::DX: DestReg = X86::DL; break;
10330       case X86::CX: DestReg = X86::CL; break;
10331       case X86::BX: DestReg = X86::BL; break;
10332       }
10333       if (DestReg) {
10334         Res.first = DestReg;
10335         Res.second = X86::GR8RegisterClass;
10336       }
10337     } else if (VT == MVT::i32) {
10338       unsigned DestReg = 0;
10339       switch (Res.first) {
10340       default: break;
10341       case X86::AX: DestReg = X86::EAX; break;
10342       case X86::DX: DestReg = X86::EDX; break;
10343       case X86::CX: DestReg = X86::ECX; break;
10344       case X86::BX: DestReg = X86::EBX; break;
10345       case X86::SI: DestReg = X86::ESI; break;
10346       case X86::DI: DestReg = X86::EDI; break;
10347       case X86::BP: DestReg = X86::EBP; break;
10348       case X86::SP: DestReg = X86::ESP; break;
10349       }
10350       if (DestReg) {
10351         Res.first = DestReg;
10352         Res.second = X86::GR32RegisterClass;
10353       }
10354     } else if (VT == MVT::i64) {
10355       unsigned DestReg = 0;
10356       switch (Res.first) {
10357       default: break;
10358       case X86::AX: DestReg = X86::RAX; break;
10359       case X86::DX: DestReg = X86::RDX; break;
10360       case X86::CX: DestReg = X86::RCX; break;
10361       case X86::BX: DestReg = X86::RBX; break;
10362       case X86::SI: DestReg = X86::RSI; break;
10363       case X86::DI: DestReg = X86::RDI; break;
10364       case X86::BP: DestReg = X86::RBP; break;
10365       case X86::SP: DestReg = X86::RSP; break;
10366       }
10367       if (DestReg) {
10368         Res.first = DestReg;
10369         Res.second = X86::GR64RegisterClass;
10370       }
10371     }
10372   } else if (Res.second == X86::FR32RegisterClass ||
10373              Res.second == X86::FR64RegisterClass ||
10374              Res.second == X86::VR128RegisterClass) {
10375     // Handle references to XMM physical registers that got mapped into the
10376     // wrong class.  This can happen with constraints like {xmm0} where the
10377     // target independent register mapper will just pick the first match it can
10378     // find, ignoring the required type.
10379     if (VT == MVT::f32)
10380       Res.second = X86::FR32RegisterClass;
10381     else if (VT == MVT::f64)
10382       Res.second = X86::FR64RegisterClass;
10383     else if (X86::VR128RegisterClass->hasType(VT))
10384       Res.second = X86::VR128RegisterClass;
10385   }
10386
10387   return Res;
10388 }