Add FP versions of the binary operators, keeping the int and fp worlds seperate.
[oota-llvm.git] / lib / Target / X86 / X86ISelPattern.cpp
1 //===-- X86ISelPattern.cpp - A pattern matching inst selector for X86 -----===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file was developed by the LLVM research group and is distributed under
6 // the University of Illinois Open Source License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file defines a pattern matching instruction selector for X86.
11 //
12 //===----------------------------------------------------------------------===//
13
14 #include "X86.h"
15 #include "X86InstrBuilder.h"
16 #include "X86RegisterInfo.h"
17 #include "X86Subtarget.h"
18 #include "llvm/CallingConv.h"
19 #include "llvm/Constants.h"
20 #include "llvm/Instructions.h"
21 #include "llvm/Function.h"
22 #include "llvm/CodeGen/MachineConstantPool.h"
23 #include "llvm/CodeGen/MachineFunction.h"
24 #include "llvm/CodeGen/MachineFrameInfo.h"
25 #include "llvm/CodeGen/SelectionDAG.h"
26 #include "llvm/CodeGen/SelectionDAGISel.h"
27 #include "llvm/CodeGen/SSARegMap.h"
28 #include "llvm/Target/TargetData.h"
29 #include "llvm/Target/TargetLowering.h"
30 #include "llvm/Target/TargetMachine.h"
31 #include "llvm/Target/TargetOptions.h"
32 #include "llvm/Support/CFG.h"
33 #include "llvm/Support/MathExtras.h"
34 #include "llvm/ADT/Statistic.h"
35 #include <set>
36 #include <algorithm>
37 using namespace llvm;
38
39 // FIXME: temporary.
40 #include "llvm/Support/CommandLine.h"
41 static cl::opt<bool> EnableFastCC("enable-x86-fastcc", cl::Hidden,
42                                   cl::desc("Enable fastcc on X86"));
43
44 namespace {
45   // X86 Specific DAG Nodes
46   namespace X86ISD {
47     enum NodeType {
48       // Start the numbering where the builtin ops leave off.
49       FIRST_NUMBER = ISD::BUILTIN_OP_END,
50
51       /// FILD64m - This instruction implements SINT_TO_FP with a
52       /// 64-bit source in memory and a FP reg result.  This corresponds to
53       /// the X86::FILD64m instruction.  It has two inputs (token chain and
54       /// address) and two outputs (FP value and token chain).
55       FILD64m,
56
57       /// FP_TO_INT*_IN_MEM - This instruction implements FP_TO_SINT with the
58       /// integer destination in memory and a FP reg source.  This corresponds
59       /// to the X86::FIST*m instructions and the rounding mode change stuff. It
60       /// has two inputs (token chain and address) and two outputs (FP value and
61       /// token chain).
62       FP_TO_INT16_IN_MEM,
63       FP_TO_INT32_IN_MEM,
64       FP_TO_INT64_IN_MEM,
65
66       /// CALL/TAILCALL - These operations represent an abstract X86 call
67       /// instruction, which includes a bunch of information.  In particular the
68       /// operands of these node are:
69       ///
70       ///     #0 - The incoming token chain
71       ///     #1 - The callee
72       ///     #2 - The number of arg bytes the caller pushes on the stack.
73       ///     #3 - The number of arg bytes the callee pops off the stack.
74       ///     #4 - The value to pass in AL/AX/EAX (optional)
75       ///     #5 - The value to pass in DL/DX/EDX (optional)
76       ///
77       /// The result values of these nodes are:
78       ///
79       ///     #0 - The outgoing token chain
80       ///     #1 - The first register result value (optional)
81       ///     #2 - The second register result value (optional)
82       ///
83       /// The CALL vs TAILCALL distinction boils down to whether the callee is
84       /// known not to modify the caller's stack frame, as is standard with
85       /// LLVM.
86       CALL,
87       TAILCALL,
88     };
89   }
90 }
91
92 //===----------------------------------------------------------------------===//
93 //  X86TargetLowering - X86 Implementation of the TargetLowering interface
94 namespace {
95   class X86TargetLowering : public TargetLowering {
96     int VarArgsFrameIndex;            // FrameIndex for start of varargs area.
97     int ReturnAddrIndex;              // FrameIndex for return slot.
98     int BytesToPopOnReturn;           // Number of arg bytes ret should pop.
99     int BytesCallerReserves;          // Number of arg bytes caller makes.
100   public:
101     X86TargetLowering(TargetMachine &TM) : TargetLowering(TM) {
102       // Set up the TargetLowering object.
103
104       // X86 is weird, it always uses i8 for shift amounts and setcc results.
105       setShiftAmountType(MVT::i8);
106       setSetCCResultType(MVT::i8);
107       setSetCCResultContents(ZeroOrOneSetCCResult);
108       setShiftAmountFlavor(Mask);   // shl X, 32 == shl X, 0
109
110       // Set up the register classes.
111       // FIXME: Eliminate these two classes when legalize can handle promotions
112       // well.
113       addRegisterClass(MVT::i1, X86::R8RegisterClass);
114       addRegisterClass(MVT::i8, X86::R8RegisterClass);
115       addRegisterClass(MVT::i16, X86::R16RegisterClass);
116       addRegisterClass(MVT::i32, X86::R32RegisterClass);
117
118       // Promote all UINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have this
119       // operation.
120       setOperationAction(ISD::UINT_TO_FP       , MVT::i1   , Promote);
121       setOperationAction(ISD::UINT_TO_FP       , MVT::i8   , Promote);
122       setOperationAction(ISD::UINT_TO_FP       , MVT::i16  , Promote);
123       setOperationAction(ISD::UINT_TO_FP       , MVT::i32  , Promote);
124
125       // Promote i1/i8 SINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have
126       // this operation.
127       setOperationAction(ISD::SINT_TO_FP       , MVT::i1   , Promote);
128       setOperationAction(ISD::SINT_TO_FP       , MVT::i8   , Promote);
129
130       if (!X86ScalarSSE) {
131         // We can handle SINT_TO_FP and FP_TO_SINT from/TO i64 even though i64
132         // isn't legal.
133         setOperationAction(ISD::SINT_TO_FP     , MVT::i64  , Custom);
134         setOperationAction(ISD::FP_TO_SINT     , MVT::i64  , Custom);
135         setOperationAction(ISD::FP_TO_SINT     , MVT::i32  , Custom);
136         setOperationAction(ISD::FP_TO_SINT     , MVT::i16  , Custom);
137       }
138
139       // Handle FP_TO_UINT by promoting the destination to a larger signed
140       // conversion.
141       setOperationAction(ISD::FP_TO_UINT       , MVT::i1   , Promote);
142       setOperationAction(ISD::FP_TO_UINT       , MVT::i8   , Promote);
143       setOperationAction(ISD::FP_TO_UINT       , MVT::i16  , Promote);
144
145       if (!X86ScalarSSE)
146         setOperationAction(ISD::FP_TO_UINT     , MVT::i32  , Promote);
147
148       // Promote i1/i8 FP_TO_SINT to larger FP_TO_SINTS's, as X86 doesn't have
149       // this operation.
150       setOperationAction(ISD::FP_TO_SINT       , MVT::i1   , Promote);
151       setOperationAction(ISD::FP_TO_SINT       , MVT::i8   , Promote);
152       setOperationAction(ISD::FP_TO_SINT       , MVT::i16  , Promote);
153
154       setOperationAction(ISD::BRCONDTWOWAY     , MVT::Other, Expand);
155       setOperationAction(ISD::BRTWOWAY_CC      , MVT::Other, Expand);
156       setOperationAction(ISD::MEMMOVE          , MVT::Other, Expand);
157       setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16  , Expand);
158       setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1   , Expand);
159       setOperationAction(ISD::FP_ROUND_INREG   , MVT::f32  , Expand);
160       setOperationAction(ISD::SEXTLOAD         , MVT::i1   , Expand);
161       setOperationAction(ISD::FREM             , MVT::f64  , Expand);
162       setOperationAction(ISD::CTPOP            , MVT::i8   , Expand);
163       setOperationAction(ISD::CTTZ             , MVT::i8   , Expand);
164       setOperationAction(ISD::CTLZ             , MVT::i8   , Expand);
165       setOperationAction(ISD::CTPOP            , MVT::i16  , Expand);
166       setOperationAction(ISD::CTTZ             , MVT::i16  , Expand);
167       setOperationAction(ISD::CTLZ             , MVT::i16  , Expand);
168       setOperationAction(ISD::CTPOP            , MVT::i32  , Expand);
169       setOperationAction(ISD::CTTZ             , MVT::i32  , Expand);
170       setOperationAction(ISD::CTLZ             , MVT::i32  , Expand);
171
172       setOperationAction(ISD::READIO           , MVT::i1   , Expand);
173       setOperationAction(ISD::READIO           , MVT::i8   , Expand);
174       setOperationAction(ISD::READIO           , MVT::i16  , Expand);
175       setOperationAction(ISD::READIO           , MVT::i32  , Expand);
176       setOperationAction(ISD::WRITEIO          , MVT::i1   , Expand);
177       setOperationAction(ISD::WRITEIO          , MVT::i8   , Expand);
178       setOperationAction(ISD::WRITEIO          , MVT::i16  , Expand);
179       setOperationAction(ISD::WRITEIO          , MVT::i32  , Expand);
180
181       // These should be promoted to a larger select which is supported.
182       setOperationAction(ISD::SELECT           , MVT::i1   , Promote);
183       setOperationAction(ISD::SELECT           , MVT::i8   , Promote);
184
185       if (X86ScalarSSE) {
186         // Set up the FP register classes.
187         addRegisterClass(MVT::f32, X86::RXMMRegisterClass);
188         addRegisterClass(MVT::f64, X86::RXMMRegisterClass);
189
190         // SSE has no load+extend ops
191         setOperationAction(ISD::EXTLOAD,  MVT::f32, Expand);
192         setOperationAction(ISD::ZEXTLOAD, MVT::f32, Expand);
193
194         // SSE has no i16 to fp conversion, only i32
195         setOperationAction(ISD::SINT_TO_FP, MVT::i16, Promote);
196         setOperationAction(ISD::FP_TO_SINT, MVT::i16, Promote);
197
198         // Expand FP_TO_UINT into a select.
199         // FIXME: We would like to use a Custom expander here eventually to do
200         // the optimal thing for SSE vs. the default expansion in the legalizer.
201         setOperationAction(ISD::FP_TO_UINT       , MVT::i32  , Expand);
202         
203         // We don't support sin/cos/sqrt/fmod
204         setOperationAction(ISD::FSIN , MVT::f64, Expand);
205         setOperationAction(ISD::FCOS , MVT::f64, Expand);
206         setOperationAction(ISD::FABS , MVT::f64, Expand);
207         setOperationAction(ISD::FNEG , MVT::f64, Expand);
208         setOperationAction(ISD::FREM , MVT::f64, Expand);
209         setOperationAction(ISD::FSIN , MVT::f32, Expand);
210         setOperationAction(ISD::FCOS , MVT::f32, Expand);
211         setOperationAction(ISD::FABS , MVT::f32, Expand);
212         setOperationAction(ISD::FNEG , MVT::f32, Expand);
213         setOperationAction(ISD::FREM , MVT::f32, Expand);
214
215         addLegalFPImmediate(+0.0); // xorps / xorpd
216       } else {
217         // Set up the FP register classes.
218         addRegisterClass(MVT::f64, X86::RFPRegisterClass);
219
220         if (!UnsafeFPMath) {
221           setOperationAction(ISD::FSIN           , MVT::f64  , Expand);
222           setOperationAction(ISD::FCOS           , MVT::f64  , Expand);
223         }
224
225         addLegalFPImmediate(+0.0); // FLD0
226         addLegalFPImmediate(+1.0); // FLD1
227         addLegalFPImmediate(-0.0); // FLD0/FCHS
228         addLegalFPImmediate(-1.0); // FLD1/FCHS
229       }
230       computeRegisterProperties();
231
232       maxStoresPerMemSet = 8; // For %llvm.memset -> sequence of stores
233       maxStoresPerMemCpy = 8; // For %llvm.memcpy -> sequence of stores
234       maxStoresPerMemMove = 8; // For %llvm.memmove -> sequence of stores
235       allowUnalignedMemoryAccesses = true; // x86 supports it!
236     }
237
238     // Return the number of bytes that a function should pop when it returns (in
239     // addition to the space used by the return address).
240     //
241     unsigned getBytesToPopOnReturn() const { return BytesToPopOnReturn; }
242
243     // Return the number of bytes that the caller reserves for arguments passed
244     // to this function.
245     unsigned getBytesCallerReserves() const { return BytesCallerReserves; }
246
247     /// LowerOperation - Provide custom lowering hooks for some operations.
248     ///
249     virtual SDOperand LowerOperation(SDOperand Op, SelectionDAG &DAG);
250
251     /// LowerArguments - This hook must be implemented to indicate how we should
252     /// lower the arguments for the specified function, into the specified DAG.
253     virtual std::vector<SDOperand>
254     LowerArguments(Function &F, SelectionDAG &DAG);
255
256     /// LowerCallTo - This hook lowers an abstract call to a function into an
257     /// actual call.
258     virtual std::pair<SDOperand, SDOperand>
259     LowerCallTo(SDOperand Chain, const Type *RetTy, bool isVarArg, unsigned CC,
260                 bool isTailCall, SDOperand Callee, ArgListTy &Args,
261                 SelectionDAG &DAG);
262
263     virtual SDOperand LowerVAStart(SDOperand Chain, SDOperand VAListP,
264                                    Value *VAListV, SelectionDAG &DAG);
265     virtual std::pair<SDOperand,SDOperand>
266       LowerVAArg(SDOperand Chain, SDOperand VAListP, Value *VAListV,
267                  const Type *ArgTy, SelectionDAG &DAG);
268
269     virtual std::pair<SDOperand, SDOperand>
270     LowerFrameReturnAddress(bool isFrameAddr, SDOperand Chain, unsigned Depth,
271                             SelectionDAG &DAG);
272
273     SDOperand getReturnAddressFrameIndex(SelectionDAG &DAG);
274
275   private:
276     // C Calling Convention implementation.
277     std::vector<SDOperand> LowerCCCArguments(Function &F, SelectionDAG &DAG);
278     std::pair<SDOperand, SDOperand>
279     LowerCCCCallTo(SDOperand Chain, const Type *RetTy, bool isVarArg,
280                    bool isTailCall,
281                    SDOperand Callee, ArgListTy &Args, SelectionDAG &DAG);
282
283     // Fast Calling Convention implementation.
284     std::vector<SDOperand> LowerFastCCArguments(Function &F, SelectionDAG &DAG);
285     std::pair<SDOperand, SDOperand>
286     LowerFastCCCallTo(SDOperand Chain, const Type *RetTy, bool isTailCall,
287                       SDOperand Callee, ArgListTy &Args, SelectionDAG &DAG);
288   };
289 }
290
291 std::vector<SDOperand>
292 X86TargetLowering::LowerArguments(Function &F, SelectionDAG &DAG) {
293   if (F.getCallingConv() == CallingConv::Fast && EnableFastCC)
294     return LowerFastCCArguments(F, DAG);
295   return LowerCCCArguments(F, DAG);
296 }
297
298 std::pair<SDOperand, SDOperand>
299 X86TargetLowering::LowerCallTo(SDOperand Chain, const Type *RetTy,
300                                bool isVarArg, unsigned CallingConv,
301                                bool isTailCall,
302                                SDOperand Callee, ArgListTy &Args,
303                                SelectionDAG &DAG) {
304   assert((!isVarArg || CallingConv == CallingConv::C) &&
305          "Only C takes varargs!");
306   if (CallingConv == CallingConv::Fast && EnableFastCC)
307     return LowerFastCCCallTo(Chain, RetTy, isTailCall, Callee, Args, DAG);
308   return  LowerCCCCallTo(Chain, RetTy, isVarArg, isTailCall, Callee, Args, DAG);
309 }
310
311 //===----------------------------------------------------------------------===//
312 //                    C Calling Convention implementation
313 //===----------------------------------------------------------------------===//
314
315 std::vector<SDOperand>
316 X86TargetLowering::LowerCCCArguments(Function &F, SelectionDAG &DAG) {
317   std::vector<SDOperand> ArgValues;
318
319   MachineFunction &MF = DAG.getMachineFunction();
320   MachineFrameInfo *MFI = MF.getFrameInfo();
321
322   // Add DAG nodes to load the arguments...  On entry to a function on the X86,
323   // the stack frame looks like this:
324   //
325   // [ESP] -- return address
326   // [ESP + 4] -- first argument (leftmost lexically)
327   // [ESP + 8] -- second argument, if first argument is four bytes in size
328   //    ...
329   //
330   unsigned ArgOffset = 0;   // Frame mechanisms handle retaddr slot
331   for (Function::arg_iterator I = F.arg_begin(), E = F.arg_end(); I != E; ++I) {
332     MVT::ValueType ObjectVT = getValueType(I->getType());
333     unsigned ArgIncrement = 4;
334     unsigned ObjSize;
335     switch (ObjectVT) {
336     default: assert(0 && "Unhandled argument type!");
337     case MVT::i1:
338     case MVT::i8:  ObjSize = 1;                break;
339     case MVT::i16: ObjSize = 2;                break;
340     case MVT::i32: ObjSize = 4;                break;
341     case MVT::i64: ObjSize = ArgIncrement = 8; break;
342     case MVT::f32: ObjSize = 4;                break;
343     case MVT::f64: ObjSize = ArgIncrement = 8; break;
344     }
345     // Create the frame index object for this incoming parameter...
346     int FI = MFI->CreateFixedObject(ObjSize, ArgOffset);
347
348     // Create the SelectionDAG nodes corresponding to a load from this parameter
349     SDOperand FIN = DAG.getFrameIndex(FI, MVT::i32);
350
351     // Don't codegen dead arguments.  FIXME: remove this check when we can nuke
352     // dead loads.
353     SDOperand ArgValue;
354     if (!I->use_empty())
355       ArgValue = DAG.getLoad(ObjectVT, DAG.getEntryNode(), FIN,
356                              DAG.getSrcValue(NULL));
357     else {
358       if (MVT::isInteger(ObjectVT))
359         ArgValue = DAG.getConstant(0, ObjectVT);
360       else
361         ArgValue = DAG.getConstantFP(0, ObjectVT);
362     }
363     ArgValues.push_back(ArgValue);
364
365     ArgOffset += ArgIncrement;   // Move on to the next argument...
366   }
367
368   // If the function takes variable number of arguments, make a frame index for
369   // the start of the first vararg value... for expansion of llvm.va_start.
370   if (F.isVarArg())
371     VarArgsFrameIndex = MFI->CreateFixedObject(1, ArgOffset);
372   ReturnAddrIndex = 0;     // No return address slot generated yet.
373   BytesToPopOnReturn = 0;  // Callee pops nothing.
374   BytesCallerReserves = ArgOffset;
375
376   // Finally, inform the code generator which regs we return values in.
377   switch (getValueType(F.getReturnType())) {
378   default: assert(0 && "Unknown type!");
379   case MVT::isVoid: break;
380   case MVT::i1:
381   case MVT::i8:
382   case MVT::i16:
383   case MVT::i32:
384     MF.addLiveOut(X86::EAX);
385     break;
386   case MVT::i64:
387     MF.addLiveOut(X86::EAX);
388     MF.addLiveOut(X86::EDX);
389     break;
390   case MVT::f32:
391   case MVT::f64:
392     MF.addLiveOut(X86::ST0);
393     break;
394   }
395   return ArgValues;
396 }
397
398 std::pair<SDOperand, SDOperand>
399 X86TargetLowering::LowerCCCCallTo(SDOperand Chain, const Type *RetTy,
400                                   bool isVarArg, bool isTailCall,
401                                   SDOperand Callee, ArgListTy &Args,
402                                   SelectionDAG &DAG) {
403   // Count how many bytes are to be pushed on the stack.
404   unsigned NumBytes = 0;
405
406   if (Args.empty()) {
407     // Save zero bytes.
408     Chain = DAG.getNode(ISD::CALLSEQ_START, MVT::Other, Chain,
409                         DAG.getConstant(0, getPointerTy()));
410   } else {
411     for (unsigned i = 0, e = Args.size(); i != e; ++i)
412       switch (getValueType(Args[i].second)) {
413       default: assert(0 && "Unknown value type!");
414       case MVT::i1:
415       case MVT::i8:
416       case MVT::i16:
417       case MVT::i32:
418       case MVT::f32:
419         NumBytes += 4;
420         break;
421       case MVT::i64:
422       case MVT::f64:
423         NumBytes += 8;
424         break;
425       }
426
427     Chain = DAG.getNode(ISD::CALLSEQ_START, MVT::Other, Chain,
428                         DAG.getConstant(NumBytes, getPointerTy()));
429
430     // Arguments go on the stack in reverse order, as specified by the ABI.
431     unsigned ArgOffset = 0;
432     SDOperand StackPtr = DAG.getCopyFromReg(DAG.getEntryNode(),
433                                             X86::ESP, MVT::i32);
434     std::vector<SDOperand> Stores;
435
436     for (unsigned i = 0, e = Args.size(); i != e; ++i) {
437       SDOperand PtrOff = DAG.getConstant(ArgOffset, getPointerTy());
438       PtrOff = DAG.getNode(ISD::ADD, MVT::i32, StackPtr, PtrOff);
439
440       switch (getValueType(Args[i].second)) {
441       default: assert(0 && "Unexpected ValueType for argument!");
442       case MVT::i1:
443       case MVT::i8:
444       case MVT::i16:
445         // Promote the integer to 32 bits.  If the input type is signed use a
446         // sign extend, otherwise use a zero extend.
447         if (Args[i].second->isSigned())
448           Args[i].first =DAG.getNode(ISD::SIGN_EXTEND, MVT::i32, Args[i].first);
449         else
450           Args[i].first =DAG.getNode(ISD::ZERO_EXTEND, MVT::i32, Args[i].first);
451
452         // FALL THROUGH
453       case MVT::i32:
454       case MVT::f32:
455         Stores.push_back(DAG.getNode(ISD::STORE, MVT::Other, Chain,
456                                      Args[i].first, PtrOff,
457                                      DAG.getSrcValue(NULL)));
458         ArgOffset += 4;
459         break;
460       case MVT::i64:
461       case MVT::f64:
462         Stores.push_back(DAG.getNode(ISD::STORE, MVT::Other, Chain,
463                                      Args[i].first, PtrOff,
464                                      DAG.getSrcValue(NULL)));
465         ArgOffset += 8;
466         break;
467       }
468     }
469     Chain = DAG.getNode(ISD::TokenFactor, MVT::Other, Stores);
470   }
471
472   std::vector<MVT::ValueType> RetVals;
473   MVT::ValueType RetTyVT = getValueType(RetTy);
474   RetVals.push_back(MVT::Other);
475
476   // The result values produced have to be legal.  Promote the result.
477   switch (RetTyVT) {
478   case MVT::isVoid: break;
479   default:
480     RetVals.push_back(RetTyVT);
481     break;
482   case MVT::i1:
483   case MVT::i8:
484   case MVT::i16:
485     RetVals.push_back(MVT::i32);
486     break;
487   case MVT::f32:
488     if (X86ScalarSSE)
489       RetVals.push_back(MVT::f32);
490     else
491       RetVals.push_back(MVT::f64);
492     break;
493   case MVT::i64:
494     RetVals.push_back(MVT::i32);
495     RetVals.push_back(MVT::i32);
496     break;
497   }
498   std::vector<SDOperand> Ops;
499   Ops.push_back(Chain);
500   Ops.push_back(Callee);
501   Ops.push_back(DAG.getConstant(NumBytes, getPointerTy()));
502   Ops.push_back(DAG.getConstant(0, getPointerTy()));
503   SDOperand TheCall = DAG.getNode(isTailCall ? X86ISD::TAILCALL : X86ISD::CALL,
504                                   RetVals, Ops);
505   Chain = DAG.getNode(ISD::CALLSEQ_END, MVT::Other, TheCall);
506
507   SDOperand ResultVal;
508   switch (RetTyVT) {
509   case MVT::isVoid: break;
510   default:
511     ResultVal = TheCall.getValue(1);
512     break;
513   case MVT::i1:
514   case MVT::i8:
515   case MVT::i16:
516     ResultVal = DAG.getNode(ISD::TRUNCATE, RetTyVT, TheCall.getValue(1));
517     break;
518   case MVT::f32:
519     // FIXME: we would really like to remember that this FP_ROUND operation is
520     // okay to eliminate if we allow excess FP precision.
521     ResultVal = DAG.getNode(ISD::FP_ROUND, MVT::f32, TheCall.getValue(1));
522     break;
523   case MVT::i64:
524     ResultVal = DAG.getNode(ISD::BUILD_PAIR, MVT::i64, TheCall.getValue(1),
525                             TheCall.getValue(2));
526     break;
527   }
528
529   return std::make_pair(ResultVal, Chain);
530 }
531
532 SDOperand
533 X86TargetLowering::LowerVAStart(SDOperand Chain, SDOperand VAListP,
534                                 Value *VAListV, SelectionDAG &DAG) {
535   // vastart just stores the address of the VarArgsFrameIndex slot.
536   SDOperand FR = DAG.getFrameIndex(VarArgsFrameIndex, MVT::i32);
537   return DAG.getNode(ISD::STORE, MVT::Other, Chain, FR, VAListP,
538                      DAG.getSrcValue(VAListV));
539 }
540
541
542 std::pair<SDOperand,SDOperand>
543 X86TargetLowering::LowerVAArg(SDOperand Chain, SDOperand VAListP,
544                               Value *VAListV, const Type *ArgTy,
545                               SelectionDAG &DAG) {
546   MVT::ValueType ArgVT = getValueType(ArgTy);
547   SDOperand Val = DAG.getLoad(MVT::i32, Chain,
548                               VAListP, DAG.getSrcValue(VAListV));
549   SDOperand Result = DAG.getLoad(ArgVT, Chain, Val,
550                                  DAG.getSrcValue(NULL));
551   unsigned Amt;
552   if (ArgVT == MVT::i32)
553     Amt = 4;
554   else {
555     assert((ArgVT == MVT::i64 || ArgVT == MVT::f64) &&
556            "Other types should have been promoted for varargs!");
557     Amt = 8;
558   }
559   Val = DAG.getNode(ISD::ADD, Val.getValueType(), Val,
560                     DAG.getConstant(Amt, Val.getValueType()));
561   Chain = DAG.getNode(ISD::STORE, MVT::Other, Chain,
562                       Val, VAListP, DAG.getSrcValue(VAListV));
563   return std::make_pair(Result, Chain);
564 }
565
566 //===----------------------------------------------------------------------===//
567 //                    Fast Calling Convention implementation
568 //===----------------------------------------------------------------------===//
569 //
570 // The X86 'fast' calling convention passes up to two integer arguments in
571 // registers (an appropriate portion of EAX/EDX), passes arguments in C order,
572 // and requires that the callee pop its arguments off the stack (allowing proper
573 // tail calls), and has the same return value conventions as C calling convs.
574 //
575 // This calling convention always arranges for the callee pop value to be 8n+4
576 // bytes, which is needed for tail recursion elimination and stack alignment
577 // reasons.
578 //
579 // Note that this can be enhanced in the future to pass fp vals in registers
580 // (when we have a global fp allocator) and do other tricks.
581 //
582
583 /// AddLiveIn - This helper function adds the specified physical register to the
584 /// MachineFunction as a live in value.  It also creates a corresponding virtual
585 /// register for it.
586 static unsigned AddLiveIn(MachineFunction &MF, unsigned PReg,
587                           TargetRegisterClass *RC) {
588   assert(RC->contains(PReg) && "Not the correct regclass!");
589   unsigned VReg = MF.getSSARegMap()->createVirtualRegister(RC);
590   MF.addLiveIn(PReg, VReg);
591   return VReg;
592 }
593
594
595 std::vector<SDOperand>
596 X86TargetLowering::LowerFastCCArguments(Function &F, SelectionDAG &DAG) {
597   std::vector<SDOperand> ArgValues;
598
599   MachineFunction &MF = DAG.getMachineFunction();
600   MachineFrameInfo *MFI = MF.getFrameInfo();
601
602   // Add DAG nodes to load the arguments...  On entry to a function the stack
603   // frame looks like this:
604   //
605   // [ESP] -- return address
606   // [ESP + 4] -- first nonreg argument (leftmost lexically)
607   // [ESP + 8] -- second nonreg argument, if first argument is 4 bytes in size
608   //    ...
609   unsigned ArgOffset = 0;   // Frame mechanisms handle retaddr slot
610
611   // Keep track of the number of integer regs passed so far.  This can be either
612   // 0 (neither EAX or EDX used), 1 (EAX is used) or 2 (EAX and EDX are both
613   // used).
614   unsigned NumIntRegs = 0;
615
616   for (Function::arg_iterator I = F.arg_begin(), E = F.arg_end(); I != E; ++I) {
617     MVT::ValueType ObjectVT = getValueType(I->getType());
618     unsigned ArgIncrement = 4;
619     unsigned ObjSize = 0;
620     SDOperand ArgValue;
621
622     switch (ObjectVT) {
623     default: assert(0 && "Unhandled argument type!");
624     case MVT::i1:
625     case MVT::i8:
626       if (NumIntRegs < 2) {
627         if (!I->use_empty()) {
628           unsigned VReg = AddLiveIn(MF, NumIntRegs ? X86::DL : X86::AL,
629                                     X86::R8RegisterClass);
630           ArgValue = DAG.getCopyFromReg(DAG.getRoot(), VReg, MVT::i8);
631           DAG.setRoot(ArgValue.getValue(1));
632         }
633         ++NumIntRegs;
634         break;
635       }
636
637       ObjSize = 1;
638       break;
639     case MVT::i16:
640       if (NumIntRegs < 2) {
641         if (!I->use_empty()) {
642           unsigned VReg = AddLiveIn(MF, NumIntRegs ? X86::DX : X86::AX,
643                                     X86::R16RegisterClass);
644           ArgValue = DAG.getCopyFromReg(DAG.getRoot(), VReg, MVT::i16);
645           DAG.setRoot(ArgValue.getValue(1));
646         }
647         ++NumIntRegs;
648         break;
649       }
650       ObjSize = 2;
651       break;
652     case MVT::i32:
653       if (NumIntRegs < 2) {
654         if (!I->use_empty()) {
655           unsigned VReg = AddLiveIn(MF,NumIntRegs ? X86::EDX : X86::EAX,
656                                     X86::R32RegisterClass);
657           ArgValue = DAG.getCopyFromReg(DAG.getRoot(), VReg, MVT::i32);
658           DAG.setRoot(ArgValue.getValue(1));
659         }
660         ++NumIntRegs;
661         break;
662       }
663       ObjSize = 4;
664       break;
665     case MVT::i64:
666       if (NumIntRegs == 0) {
667         if (!I->use_empty()) {
668           unsigned BotReg = AddLiveIn(MF, X86::EAX, X86::R32RegisterClass);
669           unsigned TopReg = AddLiveIn(MF, X86::EDX, X86::R32RegisterClass);
670
671           SDOperand Low = DAG.getCopyFromReg(DAG.getRoot(), BotReg, MVT::i32);
672           SDOperand Hi  = DAG.getCopyFromReg(Low.getValue(1), TopReg, MVT::i32);
673           DAG.setRoot(Hi.getValue(1));
674
675           ArgValue = DAG.getNode(ISD::BUILD_PAIR, MVT::i64, Low, Hi);
676         }
677         NumIntRegs = 2;
678         break;
679       } else if (NumIntRegs == 1) {
680         if (!I->use_empty()) {
681           unsigned BotReg = AddLiveIn(MF, X86::EDX, X86::R32RegisterClass);
682           SDOperand Low = DAG.getCopyFromReg(DAG.getRoot(), BotReg, MVT::i32);
683           DAG.setRoot(Low.getValue(1));
684
685           // Load the high part from memory.
686           // Create the frame index object for this incoming parameter...
687           int FI = MFI->CreateFixedObject(4, ArgOffset);
688           SDOperand FIN = DAG.getFrameIndex(FI, MVT::i32);
689           SDOperand Hi = DAG.getLoad(MVT::i32, DAG.getEntryNode(), FIN,
690                                      DAG.getSrcValue(NULL));
691           ArgValue = DAG.getNode(ISD::BUILD_PAIR, MVT::i64, Low, Hi);
692         }
693         ArgOffset += 4;
694         NumIntRegs = 2;
695         break;
696       }
697       ObjSize = ArgIncrement = 8;
698       break;
699     case MVT::f32: ObjSize = 4;                break;
700     case MVT::f64: ObjSize = ArgIncrement = 8; break;
701     }
702
703     // Don't codegen dead arguments.  FIXME: remove this check when we can nuke
704     // dead loads.
705     if (ObjSize && !I->use_empty()) {
706       // Create the frame index object for this incoming parameter...
707       int FI = MFI->CreateFixedObject(ObjSize, ArgOffset);
708
709       // Create the SelectionDAG nodes corresponding to a load from this
710       // parameter.
711       SDOperand FIN = DAG.getFrameIndex(FI, MVT::i32);
712
713       ArgValue = DAG.getLoad(ObjectVT, DAG.getEntryNode(), FIN,
714                              DAG.getSrcValue(NULL));
715     } else if (ArgValue.Val == 0) {
716       if (MVT::isInteger(ObjectVT))
717         ArgValue = DAG.getConstant(0, ObjectVT);
718       else
719         ArgValue = DAG.getConstantFP(0, ObjectVT);
720     }
721     ArgValues.push_back(ArgValue);
722
723     if (ObjSize)
724       ArgOffset += ArgIncrement;   // Move on to the next argument.
725   }
726
727   // Make sure the instruction takes 8n+4 bytes to make sure the start of the
728   // arguments and the arguments after the retaddr has been pushed are aligned.
729   if ((ArgOffset & 7) == 0)
730     ArgOffset += 4;
731
732   VarArgsFrameIndex = 0xAAAAAAA;   // fastcc functions can't have varargs.
733   ReturnAddrIndex = 0;             // No return address slot generated yet.
734   BytesToPopOnReturn = ArgOffset;  // Callee pops all stack arguments.
735   BytesCallerReserves = 0;
736
737   // Finally, inform the code generator which regs we return values in.
738   switch (getValueType(F.getReturnType())) {
739   default: assert(0 && "Unknown type!");
740   case MVT::isVoid: break;
741   case MVT::i1:
742   case MVT::i8:
743   case MVT::i16:
744   case MVT::i32:
745     MF.addLiveOut(X86::EAX);
746     break;
747   case MVT::i64:
748     MF.addLiveOut(X86::EAX);
749     MF.addLiveOut(X86::EDX);
750     break;
751   case MVT::f32:
752   case MVT::f64:
753     MF.addLiveOut(X86::ST0);
754     break;
755   }
756   return ArgValues;
757 }
758
759 std::pair<SDOperand, SDOperand>
760 X86TargetLowering::LowerFastCCCallTo(SDOperand Chain, const Type *RetTy,
761                                      bool isTailCall, SDOperand Callee,
762                                      ArgListTy &Args, SelectionDAG &DAG) {
763   // Count how many bytes are to be pushed on the stack.
764   unsigned NumBytes = 0;
765
766   // Keep track of the number of integer regs passed so far.  This can be either
767   // 0 (neither EAX or EDX used), 1 (EAX is used) or 2 (EAX and EDX are both
768   // used).
769   unsigned NumIntRegs = 0;
770
771   for (unsigned i = 0, e = Args.size(); i != e; ++i)
772     switch (getValueType(Args[i].second)) {
773     default: assert(0 && "Unknown value type!");
774     case MVT::i1:
775     case MVT::i8:
776     case MVT::i16:
777     case MVT::i32:
778       if (NumIntRegs < 2) {
779         ++NumIntRegs;
780         break;
781       }
782       // fall through
783     case MVT::f32:
784       NumBytes += 4;
785       break;
786     case MVT::i64:
787       if (NumIntRegs == 0) {
788         NumIntRegs = 2;
789         break;
790       } else if (NumIntRegs == 1) {
791         NumIntRegs = 2;
792         NumBytes += 4;
793         break;
794       }
795
796       // fall through
797     case MVT::f64:
798       NumBytes += 8;
799       break;
800     }
801
802   // Make sure the instruction takes 8n+4 bytes to make sure the start of the
803   // arguments and the arguments after the retaddr has been pushed are aligned.
804   if ((NumBytes & 7) == 0)
805     NumBytes += 4;
806
807   Chain = DAG.getNode(ISD::CALLSEQ_START, MVT::Other, Chain,
808                       DAG.getConstant(NumBytes, getPointerTy()));
809
810   // Arguments go on the stack in reverse order, as specified by the ABI.
811   unsigned ArgOffset = 0;
812   SDOperand StackPtr = DAG.getCopyFromReg(DAG.getEntryNode(),
813                                           X86::ESP, MVT::i32);
814   NumIntRegs = 0;
815   std::vector<SDOperand> Stores;
816   std::vector<SDOperand> RegValuesToPass;
817   for (unsigned i = 0, e = Args.size(); i != e; ++i) {
818     switch (getValueType(Args[i].second)) {
819     default: assert(0 && "Unexpected ValueType for argument!");
820     case MVT::i1:
821     case MVT::i8:
822     case MVT::i16:
823     case MVT::i32:
824       if (NumIntRegs < 2) {
825         RegValuesToPass.push_back(Args[i].first);
826         ++NumIntRegs;
827         break;
828       }
829       // Fall through
830     case MVT::f32: {
831       SDOperand PtrOff = DAG.getConstant(ArgOffset, getPointerTy());
832       PtrOff = DAG.getNode(ISD::ADD, MVT::i32, StackPtr, PtrOff);
833       Stores.push_back(DAG.getNode(ISD::STORE, MVT::Other, Chain,
834                                    Args[i].first, PtrOff,
835                                    DAG.getSrcValue(NULL)));
836       ArgOffset += 4;
837       break;
838     }
839     case MVT::i64:
840       if (NumIntRegs < 2) {    // Can pass part of it in regs?
841         SDOperand Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, MVT::i32,
842                                    Args[i].first, DAG.getConstant(1, MVT::i32));
843         SDOperand Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, MVT::i32,
844                                    Args[i].first, DAG.getConstant(0, MVT::i32));
845         RegValuesToPass.push_back(Lo);
846         ++NumIntRegs;
847         if (NumIntRegs < 2) {   // Pass both parts in regs?
848           RegValuesToPass.push_back(Hi);
849           ++NumIntRegs;
850         } else {
851           // Pass the high part in memory.
852           SDOperand PtrOff = DAG.getConstant(ArgOffset, getPointerTy());
853           PtrOff = DAG.getNode(ISD::ADD, MVT::i32, StackPtr, PtrOff);
854           Stores.push_back(DAG.getNode(ISD::STORE, MVT::Other, Chain,
855                                        Hi, PtrOff, DAG.getSrcValue(NULL)));
856           ArgOffset += 4;
857         }
858         break;
859       }
860       // Fall through
861     case MVT::f64:
862       SDOperand PtrOff = DAG.getConstant(ArgOffset, getPointerTy());
863       PtrOff = DAG.getNode(ISD::ADD, MVT::i32, StackPtr, PtrOff);
864       Stores.push_back(DAG.getNode(ISD::STORE, MVT::Other, Chain,
865                                    Args[i].first, PtrOff,
866                                    DAG.getSrcValue(NULL)));
867       ArgOffset += 8;
868       break;
869     }
870   }
871   if (!Stores.empty())
872     Chain = DAG.getNode(ISD::TokenFactor, MVT::Other, Stores);
873
874   // Make sure the instruction takes 8n+4 bytes to make sure the start of the
875   // arguments and the arguments after the retaddr has been pushed are aligned.
876   if ((ArgOffset & 7) == 0)
877     ArgOffset += 4;
878
879   std::vector<MVT::ValueType> RetVals;
880   MVT::ValueType RetTyVT = getValueType(RetTy);
881
882   RetVals.push_back(MVT::Other);
883
884   // The result values produced have to be legal.  Promote the result.
885   switch (RetTyVT) {
886   case MVT::isVoid: break;
887   default:
888     RetVals.push_back(RetTyVT);
889     break;
890   case MVT::i1:
891   case MVT::i8:
892   case MVT::i16:
893     RetVals.push_back(MVT::i32);
894     break;
895   case MVT::f32:
896     if (X86ScalarSSE)
897       RetVals.push_back(MVT::f32);
898     else
899       RetVals.push_back(MVT::f64);
900     break;
901   case MVT::i64:
902     RetVals.push_back(MVT::i32);
903     RetVals.push_back(MVT::i32);
904     break;
905   }
906
907   std::vector<SDOperand> Ops;
908   Ops.push_back(Chain);
909   Ops.push_back(Callee);
910   Ops.push_back(DAG.getConstant(ArgOffset, getPointerTy()));
911   // Callee pops all arg values on the stack.
912   Ops.push_back(DAG.getConstant(ArgOffset, getPointerTy()));
913
914   // Pass register arguments as needed.
915   Ops.insert(Ops.end(), RegValuesToPass.begin(), RegValuesToPass.end());
916
917   SDOperand TheCall = DAG.getNode(isTailCall ? X86ISD::TAILCALL : X86ISD::CALL,
918                                   RetVals, Ops);
919   Chain = DAG.getNode(ISD::CALLSEQ_END, MVT::Other, TheCall);
920
921   SDOperand ResultVal;
922   switch (RetTyVT) {
923   case MVT::isVoid: break;
924   default:
925     ResultVal = TheCall.getValue(1);
926     break;
927   case MVT::i1:
928   case MVT::i8:
929   case MVT::i16:
930     ResultVal = DAG.getNode(ISD::TRUNCATE, RetTyVT, TheCall.getValue(1));
931     break;
932   case MVT::f32:
933     // FIXME: we would really like to remember that this FP_ROUND operation is
934     // okay to eliminate if we allow excess FP precision.
935     ResultVal = DAG.getNode(ISD::FP_ROUND, MVT::f32, TheCall.getValue(1));
936     break;
937   case MVT::i64:
938     ResultVal = DAG.getNode(ISD::BUILD_PAIR, MVT::i64, TheCall.getValue(1),
939                             TheCall.getValue(2));
940     break;
941   }
942
943   return std::make_pair(ResultVal, Chain);
944 }
945
946 SDOperand X86TargetLowering::getReturnAddressFrameIndex(SelectionDAG &DAG) {
947   if (ReturnAddrIndex == 0) {
948     // Set up a frame object for the return address.
949     MachineFunction &MF = DAG.getMachineFunction();
950     ReturnAddrIndex = MF.getFrameInfo()->CreateFixedObject(4, -4);
951   }
952
953   return DAG.getFrameIndex(ReturnAddrIndex, MVT::i32);
954 }
955
956
957
958 std::pair<SDOperand, SDOperand> X86TargetLowering::
959 LowerFrameReturnAddress(bool isFrameAddress, SDOperand Chain, unsigned Depth,
960                         SelectionDAG &DAG) {
961   SDOperand Result;
962   if (Depth)        // Depths > 0 not supported yet!
963     Result = DAG.getConstant(0, getPointerTy());
964   else {
965     SDOperand RetAddrFI = getReturnAddressFrameIndex(DAG);
966     if (!isFrameAddress)
967       // Just load the return address
968       Result = DAG.getLoad(MVT::i32, DAG.getEntryNode(), RetAddrFI,
969                            DAG.getSrcValue(NULL));
970     else
971       Result = DAG.getNode(ISD::SUB, MVT::i32, RetAddrFI,
972                            DAG.getConstant(4, MVT::i32));
973   }
974   return std::make_pair(Result, Chain);
975 }
976
977 //===----------------------------------------------------------------------===//
978 //                           X86 Custom Lowering Hooks
979 //===----------------------------------------------------------------------===//
980
981 /// LowerOperation - Provide custom lowering hooks for some operations.
982 ///
983 SDOperand X86TargetLowering::LowerOperation(SDOperand Op, SelectionDAG &DAG) {
984   switch (Op.getOpcode()) {
985   default: assert(0 && "Should not custom lower this!");
986   case ISD::SINT_TO_FP: {
987     assert(Op.getValueType() == MVT::f64 &&
988            Op.getOperand(0).getValueType() == MVT::i64 &&
989            "Unknown SINT_TO_FP to lower!");
990     // We lower sint64->FP into a store to a temporary stack slot, followed by a
991     // FILD64m node.
992     MachineFunction &MF = DAG.getMachineFunction();
993     int SSFI = MF.getFrameInfo()->CreateStackObject(8, 8);
994     SDOperand StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
995     SDOperand Store = DAG.getNode(ISD::STORE, MVT::Other, DAG.getEntryNode(),
996                            Op.getOperand(0), StackSlot, DAG.getSrcValue(NULL));
997     std::vector<MVT::ValueType> RTs;
998     RTs.push_back(MVT::f64);
999     RTs.push_back(MVT::Other);
1000     std::vector<SDOperand> Ops;
1001     Ops.push_back(Store);
1002     Ops.push_back(StackSlot);
1003     return DAG.getNode(X86ISD::FILD64m, RTs, Ops);
1004   }
1005   case ISD::FP_TO_SINT: {
1006     assert(Op.getValueType() <= MVT::i64 && Op.getValueType() >= MVT::i16 &&
1007            Op.getOperand(0).getValueType() == MVT::f64 &&
1008            "Unknown FP_TO_SINT to lower!");
1009     // We lower FP->sint64 into FISTP64, followed by a load, all to a temporary
1010     // stack slot.
1011     MachineFunction &MF = DAG.getMachineFunction();
1012     unsigned MemSize = MVT::getSizeInBits(Op.getValueType())/8;
1013     int SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize);
1014     SDOperand StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
1015
1016     unsigned Opc;
1017     switch (Op.getValueType()) {
1018     default: assert(0 && "Invalid FP_TO_SINT to lower!");
1019     case MVT::i16: Opc = X86ISD::FP_TO_INT16_IN_MEM; break;
1020     case MVT::i32: Opc = X86ISD::FP_TO_INT32_IN_MEM; break;
1021     case MVT::i64: Opc = X86ISD::FP_TO_INT64_IN_MEM; break;
1022     }
1023
1024     // Build the FP_TO_INT*_IN_MEM
1025     std::vector<SDOperand> Ops;
1026     Ops.push_back(DAG.getEntryNode());
1027     Ops.push_back(Op.getOperand(0));
1028     Ops.push_back(StackSlot);
1029     SDOperand FIST = DAG.getNode(Opc, MVT::Other, Ops);
1030
1031     // Load the result.
1032     return DAG.getLoad(Op.getValueType(), FIST, StackSlot,
1033                        DAG.getSrcValue(NULL));
1034   }
1035   }
1036 }
1037
1038
1039 //===----------------------------------------------------------------------===//
1040 //                      Pattern Matcher Implementation
1041 //===----------------------------------------------------------------------===//
1042
1043 namespace {
1044   /// X86ISelAddressMode - This corresponds to X86AddressMode, but uses
1045   /// SDOperand's instead of register numbers for the leaves of the matched
1046   /// tree.
1047   struct X86ISelAddressMode {
1048     enum {
1049       RegBase,
1050       FrameIndexBase,
1051     } BaseType;
1052
1053     struct {            // This is really a union, discriminated by BaseType!
1054       SDOperand Reg;
1055       int FrameIndex;
1056     } Base;
1057
1058     unsigned Scale;
1059     SDOperand IndexReg;
1060     unsigned Disp;
1061     GlobalValue *GV;
1062
1063     X86ISelAddressMode()
1064       : BaseType(RegBase), Scale(1), IndexReg(), Disp(), GV(0) {
1065     }
1066   };
1067 }
1068
1069
1070 namespace {
1071   Statistic<>
1072   NumFPKill("x86-codegen", "Number of FP_REG_KILL instructions added");
1073
1074   //===--------------------------------------------------------------------===//
1075   /// ISel - X86 specific code to select X86 machine instructions for
1076   /// SelectionDAG operations.
1077   ///
1078   class ISel : public SelectionDAGISel {
1079     /// ContainsFPCode - Every instruction we select that uses or defines a FP
1080     /// register should set this to true.
1081     bool ContainsFPCode;
1082
1083     /// X86Lowering - This object fully describes how to lower LLVM code to an
1084     /// X86-specific SelectionDAG.
1085     X86TargetLowering X86Lowering;
1086
1087     /// RegPressureMap - This keeps an approximate count of the number of
1088     /// registers required to evaluate each node in the graph.
1089     std::map<SDNode*, unsigned> RegPressureMap;
1090
1091     /// ExprMap - As shared expressions are codegen'd, we keep track of which
1092     /// vreg the value is produced in, so we only emit one copy of each compiled
1093     /// tree.
1094     std::map<SDOperand, unsigned> ExprMap;
1095
1096     /// TheDAG - The DAG being selected during Select* operations.
1097     SelectionDAG *TheDAG;
1098
1099     /// Subtarget - Keep a pointer to the X86Subtarget around so that we can
1100     /// make the right decision when generating code for different targets.
1101     const X86Subtarget *Subtarget;
1102   public:
1103     ISel(TargetMachine &TM) : SelectionDAGISel(X86Lowering), X86Lowering(TM) {
1104       Subtarget = &TM.getSubtarget<X86Subtarget>();
1105     }
1106
1107     virtual const char *getPassName() const {
1108       return "X86 Pattern Instruction Selection";
1109     }
1110
1111     unsigned getRegPressure(SDOperand O) {
1112       return RegPressureMap[O.Val];
1113     }
1114     unsigned ComputeRegPressure(SDOperand O);
1115
1116     /// InstructionSelectBasicBlock - This callback is invoked by
1117     /// SelectionDAGISel when it has created a SelectionDAG for us to codegen.
1118     virtual void InstructionSelectBasicBlock(SelectionDAG &DAG);
1119
1120     virtual void EmitFunctionEntryCode(Function &Fn, MachineFunction &MF);
1121
1122     bool isFoldableLoad(SDOperand Op, SDOperand OtherOp,
1123                         bool FloatPromoteOk = false);
1124     void EmitFoldedLoad(SDOperand Op, X86AddressMode &AM);
1125     bool TryToFoldLoadOpStore(SDNode *Node);
1126     bool EmitOrOpOp(SDOperand Op1, SDOperand Op2, unsigned DestReg);
1127     void EmitCMP(SDOperand LHS, SDOperand RHS, bool isOnlyUse);
1128     bool EmitBranchCC(MachineBasicBlock *Dest, SDOperand Chain, SDOperand Cond);
1129     void EmitSelectCC(SDOperand Cond, SDOperand True, SDOperand False, 
1130                       MVT::ValueType SVT, unsigned RDest);
1131     unsigned SelectExpr(SDOperand N);
1132
1133     X86AddressMode SelectAddrExprs(const X86ISelAddressMode &IAM);
1134     bool MatchAddress(SDOperand N, X86ISelAddressMode &AM);
1135     void SelectAddress(SDOperand N, X86AddressMode &AM);
1136     bool EmitPotentialTailCall(SDNode *Node);
1137     void EmitFastCCToFastCCTailCall(SDNode *TailCallNode);
1138     void Select(SDOperand N);
1139   };
1140 }
1141
1142 /// EmitSpecialCodeForMain - Emit any code that needs to be executed only in
1143 /// the main function.
1144 static void EmitSpecialCodeForMain(MachineBasicBlock *BB,
1145                                    MachineFrameInfo *MFI) {
1146   // Switch the FPU to 64-bit precision mode for better compatibility and speed.
1147   int CWFrameIdx = MFI->CreateStackObject(2, 2);
1148   addFrameReference(BuildMI(BB, X86::FNSTCW16m, 4), CWFrameIdx);
1149
1150   // Set the high part to be 64-bit precision.
1151   addFrameReference(BuildMI(BB, X86::MOV8mi, 5),
1152                     CWFrameIdx, 1).addImm(2);
1153
1154   // Reload the modified control word now.
1155   addFrameReference(BuildMI(BB, X86::FLDCW16m, 4), CWFrameIdx);
1156 }
1157
1158 void ISel::EmitFunctionEntryCode(Function &Fn, MachineFunction &MF) {
1159   // If this is main, emit special code for main.
1160   MachineBasicBlock *BB = MF.begin();
1161   if (Fn.hasExternalLinkage() && Fn.getName() == "main")
1162     EmitSpecialCodeForMain(BB, MF.getFrameInfo());
1163 }
1164
1165
1166 /// InstructionSelectBasicBlock - This callback is invoked by SelectionDAGISel
1167 /// when it has created a SelectionDAG for us to codegen.
1168 void ISel::InstructionSelectBasicBlock(SelectionDAG &DAG) {
1169   // While we're doing this, keep track of whether we see any FP code for
1170   // FP_REG_KILL insertion.
1171   ContainsFPCode = false;
1172   MachineFunction *MF = BB->getParent();
1173
1174   // Scan the PHI nodes that already are inserted into this basic block.  If any
1175   // of them is a PHI of a floating point value, we need to insert an
1176   // FP_REG_KILL.
1177   SSARegMap *RegMap = MF->getSSARegMap();
1178   if (BB != MF->begin())
1179     for (MachineBasicBlock::iterator I = BB->begin(), E = BB->end();
1180          I != E; ++I) {
1181       assert(I->getOpcode() == X86::PHI &&
1182              "Isn't just PHI nodes?");
1183       if (RegMap->getRegClass(I->getOperand(0).getReg()) ==
1184           X86::RFPRegisterClass) {
1185         ContainsFPCode = true;
1186         break;
1187       }
1188     }
1189
1190   // Compute the RegPressureMap, which is an approximation for the number of
1191   // registers required to compute each node.
1192   ComputeRegPressure(DAG.getRoot());
1193
1194   TheDAG = &DAG;
1195
1196   // Codegen the basic block.
1197   Select(DAG.getRoot());
1198
1199   TheDAG = 0;
1200
1201   // Finally, look at all of the successors of this block.  If any contain a PHI
1202   // node of FP type, we need to insert an FP_REG_KILL in this block.
1203   for (MachineBasicBlock::succ_iterator SI = BB->succ_begin(),
1204          E = BB->succ_end(); SI != E && !ContainsFPCode; ++SI)
1205     for (MachineBasicBlock::iterator I = (*SI)->begin(), E = (*SI)->end();
1206          I != E && I->getOpcode() == X86::PHI; ++I) {
1207       if (RegMap->getRegClass(I->getOperand(0).getReg()) ==
1208           X86::RFPRegisterClass) {
1209         ContainsFPCode = true;
1210         break;
1211       }
1212     }
1213
1214   // Final check, check LLVM BB's that are successors to the LLVM BB
1215   // corresponding to BB for FP PHI nodes.
1216   const BasicBlock *LLVMBB = BB->getBasicBlock();
1217   const PHINode *PN;
1218   if (!ContainsFPCode)
1219     for (succ_const_iterator SI = succ_begin(LLVMBB), E = succ_end(LLVMBB);
1220          SI != E && !ContainsFPCode; ++SI)
1221       for (BasicBlock::const_iterator II = SI->begin();
1222            (PN = dyn_cast<PHINode>(II)); ++II)
1223         if (PN->getType()->isFloatingPoint()) {
1224           ContainsFPCode = true;
1225           break;
1226         }
1227
1228
1229   // Insert FP_REG_KILL instructions into basic blocks that need them.  This
1230   // only occurs due to the floating point stackifier not being aggressive
1231   // enough to handle arbitrary global stackification.
1232   //
1233   // Currently we insert an FP_REG_KILL instruction into each block that uses or
1234   // defines a floating point virtual register.
1235   //
1236   // When the global register allocators (like linear scan) finally update live
1237   // variable analysis, we can keep floating point values in registers across
1238   // basic blocks.  This will be a huge win, but we are waiting on the global
1239   // allocators before we can do this.
1240   //
1241   if (ContainsFPCode) {
1242     BuildMI(*BB, BB->getFirstTerminator(), X86::FP_REG_KILL, 0);
1243     ++NumFPKill;
1244   }
1245
1246   // Clear state used for selection.
1247   ExprMap.clear();
1248   RegPressureMap.clear();
1249 }
1250
1251
1252 // ComputeRegPressure - Compute the RegPressureMap, which is an approximation
1253 // for the number of registers required to compute each node.  This is basically
1254 // computing a generalized form of the Sethi-Ullman number for each node.
1255 unsigned ISel::ComputeRegPressure(SDOperand O) {
1256   SDNode *N = O.Val;
1257   unsigned &Result = RegPressureMap[N];
1258   if (Result) return Result;
1259
1260   // FIXME: Should operations like CALL (which clobber lots o regs) have a
1261   // higher fixed cost??
1262
1263   if (N->getNumOperands() == 0) {
1264     Result = 1;
1265   } else {
1266     unsigned MaxRegUse = 0;
1267     unsigned NumExtraMaxRegUsers = 0;
1268     for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
1269       unsigned Regs;
1270       if (N->getOperand(i).getOpcode() == ISD::Constant)
1271         Regs = 0;
1272       else
1273         Regs = ComputeRegPressure(N->getOperand(i));
1274       if (Regs > MaxRegUse) {
1275         MaxRegUse = Regs;
1276         NumExtraMaxRegUsers = 0;
1277       } else if (Regs == MaxRegUse &&
1278                  N->getOperand(i).getValueType() != MVT::Other) {
1279         ++NumExtraMaxRegUsers;
1280       }
1281     }
1282
1283     if (O.getOpcode() != ISD::TokenFactor)
1284       Result = MaxRegUse+NumExtraMaxRegUsers;
1285     else
1286       Result = MaxRegUse == 1 ? 0 : MaxRegUse-1;
1287   }
1288
1289   //std::cerr << " WEIGHT: " << Result << " ";  N->dump(); std::cerr << "\n";
1290   return Result;
1291 }
1292
1293 /// NodeTransitivelyUsesValue - Return true if N or any of its uses uses Op.
1294 /// The DAG cannot have cycles in it, by definition, so the visited set is not
1295 /// needed to prevent infinite loops.  The DAG CAN, however, have unbounded
1296 /// reuse, so it prevents exponential cases.
1297 ///
1298 static bool NodeTransitivelyUsesValue(SDOperand N, SDOperand Op,
1299                                       std::set<SDNode*> &Visited) {
1300   if (N == Op) return true;                        // Found it.
1301   SDNode *Node = N.Val;
1302   if (Node->getNumOperands() == 0 ||      // Leaf?
1303       Node->getNodeDepth() <= Op.getNodeDepth()) return false; // Can't find it?
1304   if (!Visited.insert(Node).second) return false;  // Already visited?
1305
1306   // Recurse for the first N-1 operands.
1307   for (unsigned i = 1, e = Node->getNumOperands(); i != e; ++i)
1308     if (NodeTransitivelyUsesValue(Node->getOperand(i), Op, Visited))
1309       return true;
1310
1311   // Tail recurse for the last operand.
1312   return NodeTransitivelyUsesValue(Node->getOperand(0), Op, Visited);
1313 }
1314
1315 X86AddressMode ISel::SelectAddrExprs(const X86ISelAddressMode &IAM) {
1316   X86AddressMode Result;
1317
1318   // If we need to emit two register operands, emit the one with the highest
1319   // register pressure first.
1320   if (IAM.BaseType == X86ISelAddressMode::RegBase &&
1321       IAM.Base.Reg.Val && IAM.IndexReg.Val) {
1322     bool EmitBaseThenIndex;
1323     if (getRegPressure(IAM.Base.Reg) > getRegPressure(IAM.IndexReg)) {
1324       std::set<SDNode*> Visited;
1325       EmitBaseThenIndex = true;
1326       // If Base ends up pointing to Index, we must emit index first.  This is
1327       // because of the way we fold loads, we may end up doing bad things with
1328       // the folded add.
1329       if (NodeTransitivelyUsesValue(IAM.Base.Reg, IAM.IndexReg, Visited))
1330         EmitBaseThenIndex = false;
1331     } else {
1332       std::set<SDNode*> Visited;
1333       EmitBaseThenIndex = false;
1334       // If Base ends up pointing to Index, we must emit index first.  This is
1335       // because of the way we fold loads, we may end up doing bad things with
1336       // the folded add.
1337       if (NodeTransitivelyUsesValue(IAM.IndexReg, IAM.Base.Reg, Visited))
1338         EmitBaseThenIndex = true;
1339     }
1340
1341     if (EmitBaseThenIndex) {
1342       Result.Base.Reg = SelectExpr(IAM.Base.Reg);
1343       Result.IndexReg = SelectExpr(IAM.IndexReg);
1344     } else {
1345       Result.IndexReg = SelectExpr(IAM.IndexReg);
1346       Result.Base.Reg = SelectExpr(IAM.Base.Reg);
1347     }
1348
1349   } else if (IAM.BaseType == X86ISelAddressMode::RegBase && IAM.Base.Reg.Val) {
1350     Result.Base.Reg = SelectExpr(IAM.Base.Reg);
1351   } else if (IAM.IndexReg.Val) {
1352     Result.IndexReg = SelectExpr(IAM.IndexReg);
1353   }
1354
1355   switch (IAM.BaseType) {
1356   case X86ISelAddressMode::RegBase:
1357     Result.BaseType = X86AddressMode::RegBase;
1358     break;
1359   case X86ISelAddressMode::FrameIndexBase:
1360     Result.BaseType = X86AddressMode::FrameIndexBase;
1361     Result.Base.FrameIndex = IAM.Base.FrameIndex;
1362     break;
1363   default:
1364     assert(0 && "Unknown base type!");
1365     break;
1366   }
1367   Result.Scale = IAM.Scale;
1368   Result.Disp = IAM.Disp;
1369   Result.GV = IAM.GV;
1370   return Result;
1371 }
1372
1373 /// SelectAddress - Pattern match the maximal addressing mode for this node and
1374 /// emit all of the leaf registers.
1375 void ISel::SelectAddress(SDOperand N, X86AddressMode &AM) {
1376   X86ISelAddressMode IAM;
1377   MatchAddress(N, IAM);
1378   AM = SelectAddrExprs(IAM);
1379 }
1380
1381 /// MatchAddress - Add the specified node to the specified addressing mode,
1382 /// returning true if it cannot be done.  This just pattern matches for the
1383 /// addressing mode, it does not cause any code to be emitted.  For that, use
1384 /// SelectAddress.
1385 bool ISel::MatchAddress(SDOperand N, X86ISelAddressMode &AM) {
1386   switch (N.getOpcode()) {
1387   default: break;
1388   case ISD::FrameIndex:
1389     if (AM.BaseType == X86ISelAddressMode::RegBase && AM.Base.Reg.Val == 0) {
1390       AM.BaseType = X86ISelAddressMode::FrameIndexBase;
1391       AM.Base.FrameIndex = cast<FrameIndexSDNode>(N)->getIndex();
1392       return false;
1393     }
1394     break;
1395   case ISD::GlobalAddress:
1396     if (AM.GV == 0) {
1397       GlobalValue *GV = cast<GlobalAddressSDNode>(N)->getGlobal();
1398       // For Darwin, external and weak symbols are indirect, so we want to load
1399       // the value at address GV, not the value of GV itself.  This means that
1400       // the GlobalAddress must be in the base or index register of the address,
1401       // not the GV offset field.
1402       if (Subtarget->getIndirectExternAndWeakGlobals() &&
1403           (GV->hasWeakLinkage() || GV->isExternal())) {
1404         break;
1405       } else {
1406         AM.GV = GV;
1407         return false;
1408       }
1409     }
1410     break;
1411   case ISD::Constant:
1412     AM.Disp += cast<ConstantSDNode>(N)->getValue();
1413     return false;
1414   case ISD::SHL:
1415     // We might have folded the load into this shift, so don't regen the value
1416     // if so.
1417     if (ExprMap.count(N)) break;
1418
1419     if (AM.IndexReg.Val == 0 && AM.Scale == 1)
1420       if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N.Val->getOperand(1))) {
1421         unsigned Val = CN->getValue();
1422         if (Val == 1 || Val == 2 || Val == 3) {
1423           AM.Scale = 1 << Val;
1424           SDOperand ShVal = N.Val->getOperand(0);
1425
1426           // Okay, we know that we have a scale by now.  However, if the scaled
1427           // value is an add of something and a constant, we can fold the
1428           // constant into the disp field here.
1429           if (ShVal.Val->getOpcode() == ISD::ADD && ShVal.hasOneUse() &&
1430               isa<ConstantSDNode>(ShVal.Val->getOperand(1))) {
1431             AM.IndexReg = ShVal.Val->getOperand(0);
1432             ConstantSDNode *AddVal =
1433               cast<ConstantSDNode>(ShVal.Val->getOperand(1));
1434             AM.Disp += AddVal->getValue() << Val;
1435           } else {
1436             AM.IndexReg = ShVal;
1437           }
1438           return false;
1439         }
1440       }
1441     break;
1442   case ISD::MUL:
1443     // We might have folded the load into this mul, so don't regen the value if
1444     // so.
1445     if (ExprMap.count(N)) break;
1446
1447     // X*[3,5,9] -> X+X*[2,4,8]
1448     if (AM.IndexReg.Val == 0 && AM.BaseType == X86ISelAddressMode::RegBase &&
1449         AM.Base.Reg.Val == 0)
1450       if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N.Val->getOperand(1)))
1451         if (CN->getValue() == 3 || CN->getValue() == 5 || CN->getValue() == 9) {
1452           AM.Scale = unsigned(CN->getValue())-1;
1453
1454           SDOperand MulVal = N.Val->getOperand(0);
1455           SDOperand Reg;
1456
1457           // Okay, we know that we have a scale by now.  However, if the scaled
1458           // value is an add of something and a constant, we can fold the
1459           // constant into the disp field here.
1460           if (MulVal.Val->getOpcode() == ISD::ADD && MulVal.hasOneUse() &&
1461               isa<ConstantSDNode>(MulVal.Val->getOperand(1))) {
1462             Reg = MulVal.Val->getOperand(0);
1463             ConstantSDNode *AddVal =
1464               cast<ConstantSDNode>(MulVal.Val->getOperand(1));
1465             AM.Disp += AddVal->getValue() * CN->getValue();
1466           } else {
1467             Reg = N.Val->getOperand(0);
1468           }
1469
1470           AM.IndexReg = AM.Base.Reg = Reg;
1471           return false;
1472         }
1473     break;
1474
1475   case ISD::ADD: {
1476     // We might have folded the load into this mul, so don't regen the value if
1477     // so.
1478     if (ExprMap.count(N)) break;
1479
1480     X86ISelAddressMode Backup = AM;
1481     if (!MatchAddress(N.Val->getOperand(0), AM) &&
1482         !MatchAddress(N.Val->getOperand(1), AM))
1483       return false;
1484     AM = Backup;
1485     if (!MatchAddress(N.Val->getOperand(1), AM) &&
1486         !MatchAddress(N.Val->getOperand(0), AM))
1487       return false;
1488     AM = Backup;
1489     break;
1490   }
1491   }
1492
1493   // Is the base register already occupied?
1494   if (AM.BaseType != X86ISelAddressMode::RegBase || AM.Base.Reg.Val) {
1495     // If so, check to see if the scale index register is set.
1496     if (AM.IndexReg.Val == 0) {
1497       AM.IndexReg = N;
1498       AM.Scale = 1;
1499       return false;
1500     }
1501
1502     // Otherwise, we cannot select it.
1503     return true;
1504   }
1505
1506   // Default, generate it as a register.
1507   AM.BaseType = X86ISelAddressMode::RegBase;
1508   AM.Base.Reg = N;
1509   return false;
1510 }
1511
1512 /// Emit2SetCCsAndLogical - Emit the following sequence of instructions,
1513 /// assuming that the temporary registers are in the 8-bit register class.
1514 ///
1515 ///  Tmp1 = setcc1
1516 ///  Tmp2 = setcc2
1517 ///  DestReg = logicalop Tmp1, Tmp2
1518 ///
1519 static void Emit2SetCCsAndLogical(MachineBasicBlock *BB, unsigned SetCC1,
1520                                   unsigned SetCC2, unsigned LogicalOp,
1521                                   unsigned DestReg) {
1522   SSARegMap *RegMap = BB->getParent()->getSSARegMap();
1523   unsigned Tmp1 = RegMap->createVirtualRegister(X86::R8RegisterClass);
1524   unsigned Tmp2 = RegMap->createVirtualRegister(X86::R8RegisterClass);
1525   BuildMI(BB, SetCC1, 0, Tmp1);
1526   BuildMI(BB, SetCC2, 0, Tmp2);
1527   BuildMI(BB, LogicalOp, 2, DestReg).addReg(Tmp1).addReg(Tmp2);
1528 }
1529
1530 /// EmitSetCC - Emit the code to set the specified 8-bit register to 1 if the
1531 /// condition codes match the specified SetCCOpcode.  Note that some conditions
1532 /// require multiple instructions to generate the correct value.
1533 static void EmitSetCC(MachineBasicBlock *BB, unsigned DestReg,
1534                       ISD::CondCode SetCCOpcode, bool isFP) {
1535   unsigned Opc;
1536   if (!isFP) {
1537     switch (SetCCOpcode) {
1538     default: assert(0 && "Illegal integer SetCC!");
1539     case ISD::SETEQ: Opc = X86::SETEr; break;
1540     case ISD::SETGT: Opc = X86::SETGr; break;
1541     case ISD::SETGE: Opc = X86::SETGEr; break;
1542     case ISD::SETLT: Opc = X86::SETLr; break;
1543     case ISD::SETLE: Opc = X86::SETLEr; break;
1544     case ISD::SETNE: Opc = X86::SETNEr; break;
1545     case ISD::SETULT: Opc = X86::SETBr; break;
1546     case ISD::SETUGT: Opc = X86::SETAr; break;
1547     case ISD::SETULE: Opc = X86::SETBEr; break;
1548     case ISD::SETUGE: Opc = X86::SETAEr; break;
1549     }
1550   } else {
1551     // On a floating point condition, the flags are set as follows:
1552     // ZF  PF  CF   op
1553     //  0 | 0 | 0 | X > Y
1554     //  0 | 0 | 1 | X < Y
1555     //  1 | 0 | 0 | X == Y
1556     //  1 | 1 | 1 | unordered
1557     //
1558     switch (SetCCOpcode) {
1559     default: assert(0 && "Invalid FP setcc!");
1560     case ISD::SETUEQ:
1561     case ISD::SETEQ:
1562       Opc = X86::SETEr;    // True if ZF = 1
1563       break;
1564     case ISD::SETOGT:
1565     case ISD::SETGT:
1566       Opc = X86::SETAr;    // True if CF = 0 and ZF = 0
1567       break;
1568     case ISD::SETOGE:
1569     case ISD::SETGE:
1570       Opc = X86::SETAEr;   // True if CF = 0
1571       break;
1572     case ISD::SETULT:
1573     case ISD::SETLT:
1574       Opc = X86::SETBr;    // True if CF = 1
1575       break;
1576     case ISD::SETULE:
1577     case ISD::SETLE:
1578       Opc = X86::SETBEr;   // True if CF = 1 or ZF = 1
1579       break;
1580     case ISD::SETONE:
1581     case ISD::SETNE:
1582       Opc = X86::SETNEr;   // True if ZF = 0
1583       break;
1584     case ISD::SETUO:
1585       Opc = X86::SETPr;    // True if PF = 1
1586       break;
1587     case ISD::SETO:
1588       Opc = X86::SETNPr;   // True if PF = 0
1589       break;
1590     case ISD::SETOEQ:      // !PF & ZF
1591       Emit2SetCCsAndLogical(BB, X86::SETNPr, X86::SETEr, X86::AND8rr, DestReg);
1592       return;
1593     case ISD::SETOLT:      // !PF & CF
1594       Emit2SetCCsAndLogical(BB, X86::SETNPr, X86::SETBr, X86::AND8rr, DestReg);
1595       return;
1596     case ISD::SETOLE:      // !PF & (CF || ZF)
1597       Emit2SetCCsAndLogical(BB, X86::SETNPr, X86::SETBEr, X86::AND8rr, DestReg);
1598       return;
1599     case ISD::SETUGT:      // PF | (!ZF & !CF)
1600       Emit2SetCCsAndLogical(BB, X86::SETPr, X86::SETAr, X86::OR8rr, DestReg);
1601       return;
1602     case ISD::SETUGE:      // PF | !CF
1603       Emit2SetCCsAndLogical(BB, X86::SETPr, X86::SETAEr, X86::OR8rr, DestReg);
1604       return;
1605     case ISD::SETUNE:      // PF | !ZF
1606       Emit2SetCCsAndLogical(BB, X86::SETPr, X86::SETNEr, X86::OR8rr, DestReg);
1607       return;
1608     }
1609   }
1610   BuildMI(BB, Opc, 0, DestReg);
1611 }
1612
1613
1614 /// EmitBranchCC - Emit code into BB that arranges for control to transfer to
1615 /// the Dest block if the Cond condition is true.  If we cannot fold this
1616 /// condition into the branch, return true.
1617 ///
1618 bool ISel::EmitBranchCC(MachineBasicBlock *Dest, SDOperand Chain,
1619                         SDOperand Cond) {
1620   // FIXME: Evaluate whether it would be good to emit code like (X < Y) | (A >
1621   // B) using two conditional branches instead of one condbr, two setcc's, and
1622   // an or.
1623   if ((Cond.getOpcode() == ISD::OR ||
1624        Cond.getOpcode() == ISD::AND) && Cond.Val->hasOneUse()) {
1625     // And and or set the flags for us, so there is no need to emit a TST of the
1626     // result.  It is only safe to do this if there is only a single use of the
1627     // AND/OR though, otherwise we don't know it will be emitted here.
1628     Select(Chain);
1629     SelectExpr(Cond);
1630     BuildMI(BB, X86::JNE, 1).addMBB(Dest);
1631     return false;
1632   }
1633
1634   // Codegen br not C -> JE.
1635   if (Cond.getOpcode() == ISD::XOR)
1636     if (ConstantSDNode *NC = dyn_cast<ConstantSDNode>(Cond.Val->getOperand(1)))
1637       if (NC->isAllOnesValue()) {
1638         unsigned CondR;
1639         if (getRegPressure(Chain) > getRegPressure(Cond)) {
1640           Select(Chain);
1641           CondR = SelectExpr(Cond.Val->getOperand(0));
1642         } else {
1643           CondR = SelectExpr(Cond.Val->getOperand(0));
1644           Select(Chain);
1645         }
1646         BuildMI(BB, X86::TEST8rr, 2).addReg(CondR).addReg(CondR);
1647         BuildMI(BB, X86::JE, 1).addMBB(Dest);
1648         return false;
1649       }
1650
1651   if (Cond.getOpcode() != ISD::SETCC)
1652     return true;                       // Can only handle simple setcc's so far.
1653   ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
1654
1655   unsigned Opc;
1656
1657   // Handle integer conditions first.
1658   if (MVT::isInteger(Cond.getOperand(0).getValueType())) {
1659     switch (CC) {
1660     default: assert(0 && "Illegal integer SetCC!");
1661     case ISD::SETEQ: Opc = X86::JE; break;
1662     case ISD::SETGT: Opc = X86::JG; break;
1663     case ISD::SETGE: Opc = X86::JGE; break;
1664     case ISD::SETLT: Opc = X86::JL; break;
1665     case ISD::SETLE: Opc = X86::JLE; break;
1666     case ISD::SETNE: Opc = X86::JNE; break;
1667     case ISD::SETULT: Opc = X86::JB; break;
1668     case ISD::SETUGT: Opc = X86::JA; break;
1669     case ISD::SETULE: Opc = X86::JBE; break;
1670     case ISD::SETUGE: Opc = X86::JAE; break;
1671     }
1672     Select(Chain);
1673     EmitCMP(Cond.getOperand(0), Cond.getOperand(1), Cond.hasOneUse());
1674     BuildMI(BB, Opc, 1).addMBB(Dest);
1675     return false;
1676   }
1677
1678   unsigned Opc2 = 0;  // Second branch if needed.
1679
1680   // On a floating point condition, the flags are set as follows:
1681   // ZF  PF  CF   op
1682   //  0 | 0 | 0 | X > Y
1683   //  0 | 0 | 1 | X < Y
1684   //  1 | 0 | 0 | X == Y
1685   //  1 | 1 | 1 | unordered
1686   //
1687   switch (CC) {
1688   default: assert(0 && "Invalid FP setcc!");
1689   case ISD::SETUEQ:
1690   case ISD::SETEQ:   Opc = X86::JE;  break;     // True if ZF = 1
1691   case ISD::SETOGT:
1692   case ISD::SETGT:   Opc = X86::JA;  break;     // True if CF = 0 and ZF = 0
1693   case ISD::SETOGE:
1694   case ISD::SETGE:   Opc = X86::JAE; break;     // True if CF = 0
1695   case ISD::SETULT:
1696   case ISD::SETLT:   Opc = X86::JB;  break;     // True if CF = 1
1697   case ISD::SETULE:
1698   case ISD::SETLE:   Opc = X86::JBE; break;     // True if CF = 1 or ZF = 1
1699   case ISD::SETONE:
1700   case ISD::SETNE:   Opc = X86::JNE; break;     // True if ZF = 0
1701   case ISD::SETUO:   Opc = X86::JP;  break;     // True if PF = 1
1702   case ISD::SETO:    Opc = X86::JNP; break;     // True if PF = 0
1703   case ISD::SETUGT:      // PF = 1 | (ZF = 0 & CF = 0)
1704     Opc = X86::JA;       // ZF = 0 & CF = 0
1705     Opc2 = X86::JP;      // PF = 1
1706     break;
1707   case ISD::SETUGE:      // PF = 1 | CF = 0
1708     Opc = X86::JAE;      // CF = 0
1709     Opc2 = X86::JP;      // PF = 1
1710     break;
1711   case ISD::SETUNE:      // PF = 1 | ZF = 0
1712     Opc = X86::JNE;      // ZF = 0
1713     Opc2 = X86::JP;      // PF = 1
1714     break;
1715   case ISD::SETOEQ:      // PF = 0 & ZF = 1
1716     //X86::JNP, X86::JE
1717     //X86::AND8rr
1718     return true;    // FIXME: Emit more efficient code for this branch.
1719   case ISD::SETOLT:      // PF = 0 & CF = 1
1720     //X86::JNP, X86::JB
1721     //X86::AND8rr
1722     return true;    // FIXME: Emit more efficient code for this branch.
1723   case ISD::SETOLE:      // PF = 0 & (CF = 1 || ZF = 1)
1724     //X86::JNP, X86::JBE
1725     //X86::AND8rr
1726     return true;    // FIXME: Emit more efficient code for this branch.
1727   }
1728
1729   Select(Chain);
1730   EmitCMP(Cond.getOperand(0), Cond.getOperand(1), Cond.hasOneUse());
1731   BuildMI(BB, Opc, 1).addMBB(Dest);
1732   if (Opc2)
1733     BuildMI(BB, Opc2, 1).addMBB(Dest);
1734   return false;
1735 }
1736
1737 /// EmitSelectCC - Emit code into BB that performs a select operation between
1738 /// the two registers RTrue and RFalse, generating a result into RDest.
1739 ///
1740 void ISel::EmitSelectCC(SDOperand Cond, SDOperand True, SDOperand False,
1741                         MVT::ValueType SVT, unsigned RDest) {
1742   unsigned RTrue, RFalse;
1743   enum Condition {
1744     EQ, NE, LT, LE, GT, GE, B, BE, A, AE, P, NP,
1745     NOT_SET
1746   } CondCode = NOT_SET;
1747
1748   static const unsigned CMOVTAB16[] = {
1749     X86::CMOVE16rr,  X86::CMOVNE16rr, X86::CMOVL16rr,  X86::CMOVLE16rr,
1750     X86::CMOVG16rr,  X86::CMOVGE16rr, X86::CMOVB16rr,  X86::CMOVBE16rr,
1751     X86::CMOVA16rr,  X86::CMOVAE16rr, X86::CMOVP16rr,  X86::CMOVNP16rr,
1752   };
1753   static const unsigned CMOVTAB32[] = {
1754     X86::CMOVE32rr,  X86::CMOVNE32rr, X86::CMOVL32rr,  X86::CMOVLE32rr,
1755     X86::CMOVG32rr,  X86::CMOVGE32rr, X86::CMOVB32rr,  X86::CMOVBE32rr,
1756     X86::CMOVA32rr,  X86::CMOVAE32rr, X86::CMOVP32rr,  X86::CMOVNP32rr,
1757   };
1758   static const unsigned CMOVTABFP[] = {
1759     X86::FCMOVE ,  X86::FCMOVNE, /*missing*/0, /*missing*/0,
1760     /*missing*/0,  /*missing*/0, X86::FCMOVB , X86::FCMOVBE,
1761     X86::FCMOVA ,  X86::FCMOVAE, X86::FCMOVP , X86::FCMOVNP
1762   };
1763   static const int SSE_CMOVTAB[] = {
1764     /*CMPEQ*/   0, /*CMPNEQ*/   4, /*missing*/  0, /*missing*/  0,
1765     /*missing*/ 0, /*missing*/  0, /*CMPLT*/    1, /*CMPLE*/    2,
1766     /*CMPNLE*/  6, /*CMPNLT*/   5, /*CMPUNORD*/ 3, /*CMPORD*/   7
1767   };
1768   
1769   if (Cond.getOpcode() == ISD::SETCC) {
1770     ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
1771     if (MVT::isInteger(Cond.getOperand(0).getValueType())) {
1772       switch (CC) {
1773       default: assert(0 && "Unknown integer comparison!");
1774       case ISD::SETEQ:  CondCode = EQ; break;
1775       case ISD::SETGT:  CondCode = GT; break;
1776       case ISD::SETGE:  CondCode = GE; break;
1777       case ISD::SETLT:  CondCode = LT; break;
1778       case ISD::SETLE:  CondCode = LE; break;
1779       case ISD::SETNE:  CondCode = NE; break;
1780       case ISD::SETULT: CondCode = B; break;
1781       case ISD::SETUGT: CondCode = A; break;
1782       case ISD::SETULE: CondCode = BE; break;
1783       case ISD::SETUGE: CondCode = AE; break;
1784       }
1785     } else {
1786       // On a floating point condition, the flags are set as follows:
1787       // ZF  PF  CF   op
1788       //  0 | 0 | 0 | X > Y
1789       //  0 | 0 | 1 | X < Y
1790       //  1 | 0 | 0 | X == Y
1791       //  1 | 1 | 1 | unordered
1792       //
1793       switch (CC) {
1794       default: assert(0 && "Unknown FP comparison!");
1795       case ISD::SETUEQ:
1796       case ISD::SETEQ:  CondCode = EQ; break;     // True if ZF = 1
1797       case ISD::SETOGT:
1798       case ISD::SETGT:  CondCode = A;  break;     // True if CF = 0 and ZF = 0
1799       case ISD::SETOGE:
1800       case ISD::SETGE:  CondCode = AE; break;     // True if CF = 0
1801       case ISD::SETULT:
1802       case ISD::SETLT:  CondCode = B;  break;     // True if CF = 1
1803       case ISD::SETULE:
1804       case ISD::SETLE:  CondCode = BE; break;     // True if CF = 1 or ZF = 1
1805       case ISD::SETONE:
1806       case ISD::SETNE:  CondCode = NE; break;     // True if ZF = 0
1807       case ISD::SETUO:  CondCode = P;  break;     // True if PF = 1
1808       case ISD::SETO:   CondCode = NP; break;     // True if PF = 0
1809       case ISD::SETUGT:      // PF = 1 | (ZF = 0 & CF = 0)
1810       case ISD::SETUGE:      // PF = 1 | CF = 0
1811       case ISD::SETUNE:      // PF = 1 | ZF = 0
1812       case ISD::SETOEQ:      // PF = 0 & ZF = 1
1813       case ISD::SETOLT:      // PF = 0 & CF = 1
1814       case ISD::SETOLE:      // PF = 0 & (CF = 1 || ZF = 1)
1815         // We cannot emit this comparison as a single cmov.
1816         break;
1817       }
1818     }
1819   
1820
1821     // There's no SSE equivalent of FCMOVE.  For cases where we set a condition
1822     // code above and one of the results of the select is +0.0, then we can fake
1823     // it up through a clever AND with mask.  Otherwise, we will fall through to
1824     // the code below that will use a PHI node to select the right value.
1825     if (X86ScalarSSE && (SVT == MVT::f32 || SVT == MVT::f64)) {
1826       if (Cond.getOperand(0).getValueType() == SVT && 
1827           NOT_SET != CondCode) {
1828         ConstantFPSDNode *CT = dyn_cast<ConstantFPSDNode>(True);
1829         ConstantFPSDNode *CF = dyn_cast<ConstantFPSDNode>(False);
1830         bool TrueZero = CT && CT->isExactlyValue(0.0);
1831         bool FalseZero = CF && CF->isExactlyValue(0.0);
1832         if (TrueZero || FalseZero) {
1833           SDOperand LHS = Cond.getOperand(0);
1834           SDOperand RHS = Cond.getOperand(1);
1835           
1836           // Select the two halves of the condition
1837           unsigned RLHS, RRHS;
1838           if (getRegPressure(LHS) > getRegPressure(RHS)) {
1839             RLHS = SelectExpr(LHS);
1840             RRHS = SelectExpr(RHS);
1841           } else {
1842             RRHS = SelectExpr(RHS);
1843             RLHS = SelectExpr(LHS);
1844           }
1845           
1846           // Emit the comparison and generate a mask from it
1847           unsigned MaskReg = MakeReg(SVT);
1848           unsigned Opc = (SVT == MVT::f32) ? X86::CMPSSrr : X86::CMPSDrr;
1849           BuildMI(BB, Opc, 3, MaskReg).addReg(RLHS).addReg(RRHS)
1850             .addImm(SSE_CMOVTAB[CondCode]);
1851           
1852           if (TrueZero) {
1853             RFalse = SelectExpr(False);
1854             Opc = (SVT == MVT::f32) ? X86::ANDNPSrr : X86::ANDNPDrr;
1855             BuildMI(BB, Opc, 2, RDest).addReg(MaskReg).addReg(RFalse);
1856           } else {
1857             RTrue = SelectExpr(True);
1858             Opc = (SVT == MVT::f32) ? X86::ANDPSrr : X86::ANDPDrr;
1859             BuildMI(BB, Opc, 2, RDest).addReg(MaskReg).addReg(RTrue);
1860           }
1861           return;
1862         }
1863       }
1864     }
1865   }
1866     
1867   // Select the true and false values for use in both the SSE PHI case, and the
1868   // integer or x87 cmov cases below.
1869   if (getRegPressure(True) > getRegPressure(False)) {
1870     RTrue = SelectExpr(True);
1871     RFalse = SelectExpr(False);
1872   } else {
1873     RFalse = SelectExpr(False);
1874     RTrue = SelectExpr(True);
1875   }
1876
1877   // Since there's no SSE equivalent of FCMOVE, and we couldn't generate an
1878   // AND with mask, we'll have to do the normal RISC thing and generate a PHI
1879   // node to select between the true and false values.
1880   if (X86ScalarSSE && (SVT == MVT::f32 || SVT == MVT::f64)) {
1881     // FIXME: emit a direct compare and branch rather than setting a cond reg
1882     //        and testing it.
1883     unsigned CondReg = SelectExpr(Cond);
1884     BuildMI(BB, X86::TEST8rr, 2).addReg(CondReg).addReg(CondReg);
1885     
1886     // Create an iterator with which to insert the MBB for copying the false
1887     // value and the MBB to hold the PHI instruction for this SetCC.
1888     MachineBasicBlock *thisMBB = BB;
1889     const BasicBlock *LLVM_BB = BB->getBasicBlock();
1890     ilist<MachineBasicBlock>::iterator It = BB;
1891     ++It;
1892     
1893     //  thisMBB:
1894     //  ...
1895     //   TrueVal = ...
1896     //   cmpTY ccX, r1, r2
1897     //   bCC sinkMBB
1898     //   fallthrough --> copy0MBB
1899     MachineBasicBlock *copy0MBB = new MachineBasicBlock(LLVM_BB);
1900     MachineBasicBlock *sinkMBB = new MachineBasicBlock(LLVM_BB);
1901     BuildMI(BB, X86::JNE, 1).addMBB(sinkMBB);
1902     MachineFunction *F = BB->getParent();
1903     F->getBasicBlockList().insert(It, copy0MBB);
1904     F->getBasicBlockList().insert(It, sinkMBB);
1905     // Update machine-CFG edges
1906     BB->addSuccessor(copy0MBB);
1907     BB->addSuccessor(sinkMBB);
1908     
1909     //  copy0MBB:
1910     //   %FalseValue = ...
1911     //   # fallthrough to sinkMBB
1912     BB = copy0MBB;
1913     // Update machine-CFG edges
1914     BB->addSuccessor(sinkMBB);
1915     
1916     //  sinkMBB:
1917     //   %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
1918     //  ...
1919     BB = sinkMBB;
1920     BuildMI(BB, X86::PHI, 4, RDest).addReg(RFalse)
1921       .addMBB(copy0MBB).addReg(RTrue).addMBB(thisMBB);
1922     return;
1923   }
1924
1925   unsigned Opc = 0;
1926   if (CondCode != NOT_SET) {
1927     switch (SVT) {
1928     default: assert(0 && "Cannot select this type!");
1929     case MVT::i16: Opc = CMOVTAB16[CondCode]; break;
1930     case MVT::i32: Opc = CMOVTAB32[CondCode]; break;
1931     case MVT::f64: Opc = CMOVTABFP[CondCode]; break;
1932     }
1933   }
1934
1935   // Finally, if we weren't able to fold this, just emit the condition and test
1936   // it.
1937   if (CondCode == NOT_SET || Opc == 0) {
1938     // Get the condition into the zero flag.
1939     unsigned CondReg = SelectExpr(Cond);
1940     BuildMI(BB, X86::TEST8rr, 2).addReg(CondReg).addReg(CondReg);
1941
1942     switch (SVT) {
1943     default: assert(0 && "Cannot select this type!");
1944     case MVT::i16: Opc = X86::CMOVE16rr; break;
1945     case MVT::i32: Opc = X86::CMOVE32rr; break;
1946     case MVT::f64: Opc = X86::FCMOVE; break;
1947     }
1948   } else {
1949     // FIXME: CMP R, 0 -> TEST R, R
1950     EmitCMP(Cond.getOperand(0), Cond.getOperand(1), Cond.Val->hasOneUse());
1951     std::swap(RTrue, RFalse);
1952   }
1953   BuildMI(BB, Opc, 2, RDest).addReg(RTrue).addReg(RFalse);
1954 }
1955
1956 void ISel::EmitCMP(SDOperand LHS, SDOperand RHS, bool HasOneUse) {
1957   unsigned Opc;
1958   if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(RHS)) {
1959     Opc = 0;
1960     if (HasOneUse && isFoldableLoad(LHS, RHS)) {
1961       switch (RHS.getValueType()) {
1962       default: break;
1963       case MVT::i1:
1964       case MVT::i8:  Opc = X86::CMP8mi;  break;
1965       case MVT::i16: Opc = X86::CMP16mi; break;
1966       case MVT::i32: Opc = X86::CMP32mi; break;
1967       }
1968       if (Opc) {
1969         X86AddressMode AM;
1970         EmitFoldedLoad(LHS, AM);
1971         addFullAddress(BuildMI(BB, Opc, 5), AM).addImm(CN->getValue());
1972         return;
1973       }
1974     }
1975
1976     switch (RHS.getValueType()) {
1977     default: break;
1978     case MVT::i1:
1979     case MVT::i8:  Opc = X86::CMP8ri;  break;
1980     case MVT::i16: Opc = X86::CMP16ri; break;
1981     case MVT::i32: Opc = X86::CMP32ri; break;
1982     }
1983     if (Opc) {
1984       unsigned Tmp1 = SelectExpr(LHS);
1985       BuildMI(BB, Opc, 2).addReg(Tmp1).addImm(CN->getValue());
1986       return;
1987     }
1988   } else if (ConstantFPSDNode *CN = dyn_cast<ConstantFPSDNode>(RHS)) {
1989     if (!X86ScalarSSE && (CN->isExactlyValue(+0.0) ||
1990                           CN->isExactlyValue(-0.0))) {
1991       unsigned Reg = SelectExpr(LHS);
1992       BuildMI(BB, X86::FTST, 1).addReg(Reg);
1993       BuildMI(BB, X86::FNSTSW8r, 0);
1994       BuildMI(BB, X86::SAHF, 1);
1995       return;
1996     }
1997   }
1998
1999   Opc = 0;
2000   if (HasOneUse && isFoldableLoad(LHS, RHS)) {
2001     switch (RHS.getValueType()) {
2002     default: break;
2003     case MVT::i1:
2004     case MVT::i8:  Opc = X86::CMP8mr;  break;
2005     case MVT::i16: Opc = X86::CMP16mr; break;
2006     case MVT::i32: Opc = X86::CMP32mr; break;
2007     }
2008     if (Opc) {
2009       X86AddressMode AM;
2010       EmitFoldedLoad(LHS, AM);
2011       unsigned Reg = SelectExpr(RHS);
2012       addFullAddress(BuildMI(BB, Opc, 5), AM).addReg(Reg);
2013       return;
2014     }
2015   }
2016
2017   switch (LHS.getValueType()) {
2018   default: assert(0 && "Cannot compare this value!");
2019   case MVT::i1:
2020   case MVT::i8:  Opc = X86::CMP8rr;  break;
2021   case MVT::i16: Opc = X86::CMP16rr; break;
2022   case MVT::i32: Opc = X86::CMP32rr; break;
2023   case MVT::f32: Opc = X86::UCOMISSrr; break;
2024   case MVT::f64: Opc = X86ScalarSSE ? X86::UCOMISDrr : X86::FUCOMIr; break;
2025   }
2026   unsigned Tmp1, Tmp2;
2027   if (getRegPressure(LHS) > getRegPressure(RHS)) {
2028     Tmp1 = SelectExpr(LHS);
2029     Tmp2 = SelectExpr(RHS);
2030   } else {
2031     Tmp2 = SelectExpr(RHS);
2032     Tmp1 = SelectExpr(LHS);
2033   }
2034   BuildMI(BB, Opc, 2).addReg(Tmp1).addReg(Tmp2);
2035 }
2036
2037 /// isFoldableLoad - Return true if this is a load instruction that can safely
2038 /// be folded into an operation that uses it.
2039 bool ISel::isFoldableLoad(SDOperand Op, SDOperand OtherOp, bool FloatPromoteOk){
2040   if (Op.getOpcode() == ISD::LOAD) {
2041     // FIXME: currently can't fold constant pool indexes.
2042     if (isa<ConstantPoolSDNode>(Op.getOperand(1)))
2043       return false;
2044   } else if (FloatPromoteOk && Op.getOpcode() == ISD::EXTLOAD &&
2045              cast<VTSDNode>(Op.getOperand(3))->getVT() == MVT::f32) {
2046     // FIXME: currently can't fold constant pool indexes.
2047     if (isa<ConstantPoolSDNode>(Op.getOperand(1)))
2048       return false;
2049   } else {
2050     return false;
2051   }
2052
2053   // If this load has already been emitted, we clearly can't fold it.
2054   assert(Op.ResNo == 0 && "Not a use of the value of the load?");
2055   if (ExprMap.count(Op.getValue(1))) return false;
2056   assert(!ExprMap.count(Op.getValue(0)) && "Value in map but not token chain?");
2057   assert(!ExprMap.count(Op.getValue(1))&&"Token lowered but value not in map?");
2058
2059   // If there is not just one use of its value, we cannot fold.
2060   if (!Op.Val->hasNUsesOfValue(1, 0)) return false;
2061
2062   // Finally, we cannot fold the load into the operation if this would induce a
2063   // cycle into the resultant dag.  To check for this, see if OtherOp (the other
2064   // operand of the operation we are folding the load into) can possible use the
2065   // chain node defined by the load.
2066   if (OtherOp.Val && !Op.Val->hasNUsesOfValue(0, 1)) { // Has uses of chain?
2067     std::set<SDNode*> Visited;
2068     if (NodeTransitivelyUsesValue(OtherOp, Op.getValue(1), Visited))
2069       return false;
2070   }
2071   return true;
2072 }
2073
2074
2075 /// EmitFoldedLoad - Ensure that the arguments of the load are code generated,
2076 /// and compute the address being loaded into AM.
2077 void ISel::EmitFoldedLoad(SDOperand Op, X86AddressMode &AM) {
2078   SDOperand Chain   = Op.getOperand(0);
2079   SDOperand Address = Op.getOperand(1);
2080
2081   if (getRegPressure(Chain) > getRegPressure(Address)) {
2082     Select(Chain);
2083     SelectAddress(Address, AM);
2084   } else {
2085     SelectAddress(Address, AM);
2086     Select(Chain);
2087   }
2088
2089   // The chain for this load is now lowered.
2090   assert(ExprMap.count(SDOperand(Op.Val, 1)) == 0 &&
2091          "Load emitted more than once?");
2092   if (!ExprMap.insert(std::make_pair(Op.getValue(1), 1)).second)
2093     assert(0 && "Load emitted more than once!");
2094 }
2095
2096 // EmitOrOpOp - Pattern match the expression (Op1|Op2), where we know that op1
2097 // and op2 are i8/i16/i32 values with one use each (the or).  If we can form a
2098 // SHLD or SHRD, emit the instruction (generating the value into DestReg) and
2099 // return true.
2100 bool ISel::EmitOrOpOp(SDOperand Op1, SDOperand Op2, unsigned DestReg) {
2101   if (Op1.getOpcode() == ISD::SHL && Op2.getOpcode() == ISD::SRL) {
2102     // good!
2103   } else if (Op2.getOpcode() == ISD::SHL && Op1.getOpcode() == ISD::SRL) {
2104     std::swap(Op1, Op2);  // Op1 is the SHL now.
2105   } else {
2106     return false;  // No match
2107   }
2108
2109   SDOperand ShlVal = Op1.getOperand(0);
2110   SDOperand ShlAmt = Op1.getOperand(1);
2111   SDOperand ShrVal = Op2.getOperand(0);
2112   SDOperand ShrAmt = Op2.getOperand(1);
2113
2114   unsigned RegSize = MVT::getSizeInBits(Op1.getValueType());
2115
2116   // Find out if ShrAmt = 32-ShlAmt  or  ShlAmt = 32-ShrAmt.
2117   if (ShlAmt.getOpcode() == ISD::SUB && ShlAmt.getOperand(1) == ShrAmt)
2118     if (ConstantSDNode *SubCST = dyn_cast<ConstantSDNode>(ShlAmt.getOperand(0)))
2119       if (SubCST->getValue() == RegSize) {
2120         // (A >> ShrAmt) | (A << (32-ShrAmt)) ==> ROR A, ShrAmt
2121         // (A >> ShrAmt) | (B << (32-ShrAmt)) ==> SHRD A, B, ShrAmt
2122         if (ShrVal == ShlVal) {
2123           unsigned Reg, ShAmt;
2124           if (getRegPressure(ShrVal) > getRegPressure(ShrAmt)) {
2125             Reg = SelectExpr(ShrVal);
2126             ShAmt = SelectExpr(ShrAmt);
2127           } else {
2128             ShAmt = SelectExpr(ShrAmt);
2129             Reg = SelectExpr(ShrVal);
2130           }
2131           BuildMI(BB, X86::MOV8rr, 1, X86::CL).addReg(ShAmt);
2132           unsigned Opc = RegSize == 8 ? X86::ROR8rCL :
2133                         (RegSize == 16 ? X86::ROR16rCL : X86::ROR32rCL);
2134           BuildMI(BB, Opc, 1, DestReg).addReg(Reg);
2135           return true;
2136         } else if (RegSize != 8) {
2137           unsigned AReg, BReg;
2138           if (getRegPressure(ShlVal) > getRegPressure(ShrVal)) {
2139             BReg = SelectExpr(ShlVal);
2140             AReg = SelectExpr(ShrVal);
2141           } else {
2142             AReg = SelectExpr(ShrVal);
2143             BReg = SelectExpr(ShlVal);
2144           }
2145           unsigned ShAmt = SelectExpr(ShrAmt);
2146           BuildMI(BB, X86::MOV8rr, 1, X86::CL).addReg(ShAmt);
2147           unsigned Opc = RegSize == 16 ? X86::SHRD16rrCL : X86::SHRD32rrCL;
2148           BuildMI(BB, Opc, 2, DestReg).addReg(AReg).addReg(BReg);
2149           return true;
2150         }
2151       }
2152
2153   if (ShrAmt.getOpcode() == ISD::SUB && ShrAmt.getOperand(1) == ShlAmt)
2154     if (ConstantSDNode *SubCST = dyn_cast<ConstantSDNode>(ShrAmt.getOperand(0)))
2155       if (SubCST->getValue() == RegSize) {
2156         // (A << ShlAmt) | (A >> (32-ShlAmt)) ==> ROL A, ShrAmt
2157         // (A << ShlAmt) | (B >> (32-ShlAmt)) ==> SHLD A, B, ShrAmt
2158         if (ShrVal == ShlVal) {
2159           unsigned Reg, ShAmt;
2160           if (getRegPressure(ShrVal) > getRegPressure(ShlAmt)) {
2161             Reg = SelectExpr(ShrVal);
2162             ShAmt = SelectExpr(ShlAmt);
2163           } else {
2164             ShAmt = SelectExpr(ShlAmt);
2165             Reg = SelectExpr(ShrVal);
2166           }
2167           BuildMI(BB, X86::MOV8rr, 1, X86::CL).addReg(ShAmt);
2168           unsigned Opc = RegSize == 8 ? X86::ROL8rCL :
2169                         (RegSize == 16 ? X86::ROL16rCL : X86::ROL32rCL);
2170           BuildMI(BB, Opc, 1, DestReg).addReg(Reg);
2171           return true;
2172         } else if (RegSize != 8) {
2173           unsigned AReg, BReg;
2174           if (getRegPressure(ShlVal) > getRegPressure(ShrVal)) {
2175             AReg = SelectExpr(ShlVal);
2176             BReg = SelectExpr(ShrVal);
2177           } else {
2178             BReg = SelectExpr(ShrVal);
2179             AReg = SelectExpr(ShlVal);
2180           }
2181           unsigned ShAmt = SelectExpr(ShlAmt);
2182           BuildMI(BB, X86::MOV8rr, 1, X86::CL).addReg(ShAmt);
2183           unsigned Opc = RegSize == 16 ? X86::SHLD16rrCL : X86::SHLD32rrCL;
2184           BuildMI(BB, Opc, 2, DestReg).addReg(AReg).addReg(BReg);
2185           return true;
2186         }
2187       }
2188
2189   if (ConstantSDNode *ShrCst = dyn_cast<ConstantSDNode>(ShrAmt))
2190     if (ConstantSDNode *ShlCst = dyn_cast<ConstantSDNode>(ShlAmt))
2191       if (ShrCst->getValue() < RegSize && ShlCst->getValue() < RegSize)
2192         if (ShrCst->getValue() == RegSize-ShlCst->getValue()) {
2193           // (A >> 5) | (A << 27) --> ROR A, 5
2194           // (A >> 5) | (B << 27) --> SHRD A, B, 5
2195           if (ShrVal == ShlVal) {
2196             unsigned Reg = SelectExpr(ShrVal);
2197             unsigned Opc = RegSize == 8 ? X86::ROR8ri :
2198               (RegSize == 16 ? X86::ROR16ri : X86::ROR32ri);
2199             BuildMI(BB, Opc, 2, DestReg).addReg(Reg).addImm(ShrCst->getValue());
2200             return true;
2201           } else if (RegSize != 8) {
2202             unsigned AReg, BReg;
2203             if (getRegPressure(ShlVal) > getRegPressure(ShrVal)) {
2204               BReg = SelectExpr(ShlVal);
2205               AReg = SelectExpr(ShrVal);
2206             } else {
2207               AReg = SelectExpr(ShrVal);
2208               BReg = SelectExpr(ShlVal);
2209             }
2210             unsigned Opc = RegSize == 16 ? X86::SHRD16rri8 : X86::SHRD32rri8;
2211             BuildMI(BB, Opc, 3, DestReg).addReg(AReg).addReg(BReg)
2212               .addImm(ShrCst->getValue());
2213             return true;
2214           }
2215         }
2216
2217   return false;
2218 }
2219
2220 unsigned ISel::SelectExpr(SDOperand N) {
2221   unsigned Result;
2222   unsigned Tmp1, Tmp2, Tmp3;
2223   unsigned Opc = 0;
2224   SDNode *Node = N.Val;
2225   SDOperand Op0, Op1;
2226
2227   if (Node->getOpcode() == ISD::CopyFromReg) {
2228     unsigned Reg = cast<RegisterSDNode>(Node->getOperand(1))->getReg();
2229     // Just use the specified register as our input if we can.
2230     if (MRegisterInfo::isVirtualRegister(Reg) || Reg == X86::ESP)
2231       return Reg;
2232   }
2233
2234   unsigned &Reg = ExprMap[N];
2235   if (Reg) return Reg;
2236
2237   switch (N.getOpcode()) {
2238   default:
2239     Reg = Result = (N.getValueType() != MVT::Other) ?
2240                             MakeReg(N.getValueType()) : 1;
2241     break;
2242   case X86ISD::TAILCALL:
2243   case X86ISD::CALL:
2244     // If this is a call instruction, make sure to prepare ALL of the result
2245     // values as well as the chain.
2246     ExprMap[N.getValue(0)] = 1;
2247     if (Node->getNumValues() > 1) {
2248       Result = MakeReg(Node->getValueType(1));
2249       ExprMap[N.getValue(1)] = Result;
2250       for (unsigned i = 2, e = Node->getNumValues(); i != e; ++i)
2251         ExprMap[N.getValue(i)] = MakeReg(Node->getValueType(i));
2252     } else {
2253       Result = 1;
2254     }
2255     break;
2256   case ISD::ADD_PARTS:
2257   case ISD::SUB_PARTS:
2258   case ISD::SHL_PARTS:
2259   case ISD::SRL_PARTS:
2260   case ISD::SRA_PARTS:
2261     Result = MakeReg(Node->getValueType(0));
2262     ExprMap[N.getValue(0)] = Result;
2263     for (unsigned i = 1, e = N.Val->getNumValues(); i != e; ++i)
2264       ExprMap[N.getValue(i)] = MakeReg(Node->getValueType(i));
2265     break;
2266   }
2267
2268   switch (N.getOpcode()) {
2269   default:
2270     Node->dump();
2271     assert(0 && "Node not handled!\n");
2272   case ISD::FP_EXTEND:
2273     assert(X86ScalarSSE && "Scalar SSE FP must be enabled to use f32");
2274     Tmp1 = SelectExpr(N.getOperand(0));
2275     BuildMI(BB, X86::CVTSS2SDrr, 1, Result).addReg(Tmp1);
2276     return Result;
2277   case ISD::FP_ROUND:
2278     assert(X86ScalarSSE && "Scalar SSE FP must be enabled to use f32");
2279     Tmp1 = SelectExpr(N.getOperand(0));
2280     BuildMI(BB, X86::CVTSD2SSrr, 1, Result).addReg(Tmp1);
2281     return Result;
2282   case ISD::CopyFromReg:
2283     Select(N.getOperand(0));
2284     if (Result == 1) {
2285       Reg = Result = ExprMap[N.getValue(0)] =
2286         MakeReg(N.getValue(0).getValueType());
2287     }
2288     Tmp1 = cast<RegisterSDNode>(Node->getOperand(1))->getReg();
2289     switch (Node->getValueType(0)) {
2290     default: assert(0 && "Cannot CopyFromReg this!");
2291     case MVT::i1:
2292     case MVT::i8:
2293       BuildMI(BB, X86::MOV8rr, 1, Result).addReg(Tmp1);
2294       return Result;
2295     case MVT::i16:
2296       BuildMI(BB, X86::MOV16rr, 1, Result).addReg(Tmp1);
2297       return Result;
2298     case MVT::i32:
2299       BuildMI(BB, X86::MOV32rr, 1, Result).addReg(Tmp1);
2300       return Result;
2301     }
2302
2303   case ISD::FrameIndex:
2304     Tmp1 = cast<FrameIndexSDNode>(N)->getIndex();
2305     addFrameReference(BuildMI(BB, X86::LEA32r, 4, Result), (int)Tmp1);
2306     return Result;
2307   case ISD::ConstantPool:
2308     Tmp1 = BB->getParent()->getConstantPool()->
2309          getConstantPoolIndex(cast<ConstantPoolSDNode>(N)->get());
2310     addConstantPoolReference(BuildMI(BB, X86::LEA32r, 4, Result), Tmp1);
2311     return Result;
2312   case ISD::ConstantFP:
2313     if (X86ScalarSSE) {
2314       assert(cast<ConstantFPSDNode>(N)->isExactlyValue(+0.0) &&
2315              "SSE only supports +0.0");
2316       Opc = (N.getValueType() == MVT::f32) ? X86::FLD0SS : X86::FLD0SD;
2317       BuildMI(BB, Opc, 0, Result);
2318       return Result;
2319     }
2320     ContainsFPCode = true;
2321     Tmp1 = Result;   // Intermediate Register
2322     if (cast<ConstantFPSDNode>(N)->getValue() < 0.0 ||
2323         cast<ConstantFPSDNode>(N)->isExactlyValue(-0.0))
2324       Tmp1 = MakeReg(MVT::f64);
2325
2326     if (cast<ConstantFPSDNode>(N)->isExactlyValue(+0.0) ||
2327         cast<ConstantFPSDNode>(N)->isExactlyValue(-0.0))
2328       BuildMI(BB, X86::FLD0, 0, Tmp1);
2329     else if (cast<ConstantFPSDNode>(N)->isExactlyValue(+1.0) ||
2330              cast<ConstantFPSDNode>(N)->isExactlyValue(-1.0))
2331       BuildMI(BB, X86::FLD1, 0, Tmp1);
2332     else
2333       assert(0 && "Unexpected constant!");
2334     if (Tmp1 != Result)
2335       BuildMI(BB, X86::FCHS, 1, Result).addReg(Tmp1);
2336     return Result;
2337   case ISD::Constant:
2338     switch (N.getValueType()) {
2339     default: assert(0 && "Cannot use constants of this type!");
2340     case MVT::i1:
2341     case MVT::i8:  Opc = X86::MOV8ri;  break;
2342     case MVT::i16: Opc = X86::MOV16ri; break;
2343     case MVT::i32: Opc = X86::MOV32ri; break;
2344     }
2345     BuildMI(BB, Opc, 1,Result).addImm(cast<ConstantSDNode>(N)->getValue());
2346     return Result;
2347   case ISD::UNDEF:
2348     if (Node->getValueType(0) == MVT::f64) {
2349       // FIXME: SHOULD TEACH STACKIFIER ABOUT UNDEF VALUES!
2350       BuildMI(BB, X86::FLD0, 0, Result);
2351     } else {
2352       BuildMI(BB, X86::IMPLICIT_DEF, 0, Result);
2353     }
2354     return Result;
2355   case ISD::GlobalAddress: {
2356     GlobalValue *GV = cast<GlobalAddressSDNode>(N)->getGlobal();
2357     // For Darwin, external and weak symbols are indirect, so we want to load
2358     // the value at address GV, not the value of GV itself.
2359     if (Subtarget->getIndirectExternAndWeakGlobals() &&
2360         (GV->hasWeakLinkage() || GV->isExternal())) {
2361       BuildMI(BB, X86::MOV32rm, 4, Result).addReg(0).addZImm(1).addReg(0)
2362         .addGlobalAddress(GV, false, 0);
2363     } else {
2364       BuildMI(BB, X86::MOV32ri, 1, Result).addGlobalAddress(GV);
2365     }
2366     return Result;
2367   }
2368   case ISD::ExternalSymbol: {
2369     const char *Sym = cast<ExternalSymbolSDNode>(N)->getSymbol();
2370     BuildMI(BB, X86::MOV32ri, 1, Result).addExternalSymbol(Sym);
2371     return Result;
2372   }
2373   case ISD::ANY_EXTEND:   // treat any extend like zext
2374   case ISD::ZERO_EXTEND: {
2375     int DestIs16 = N.getValueType() == MVT::i16;
2376     int SrcIs16  = N.getOperand(0).getValueType() == MVT::i16;
2377
2378     // FIXME: This hack is here for zero extension casts from bool to i8.  This
2379     // would not be needed if bools were promoted by Legalize.
2380     if (N.getValueType() == MVT::i8) {
2381       Tmp1 = SelectExpr(N.getOperand(0));
2382       BuildMI(BB, X86::MOV8rr, 1, Result).addReg(Tmp1);
2383       return Result;
2384     }
2385
2386     if (isFoldableLoad(N.getOperand(0), SDOperand())) {
2387       static const unsigned Opc[3] = {
2388         X86::MOVZX32rm8, X86::MOVZX32rm16, X86::MOVZX16rm8
2389       };
2390
2391       X86AddressMode AM;
2392       EmitFoldedLoad(N.getOperand(0), AM);
2393       addFullAddress(BuildMI(BB, Opc[SrcIs16+DestIs16*2], 4, Result), AM);
2394
2395       return Result;
2396     }
2397
2398     static const unsigned Opc[3] = {
2399       X86::MOVZX32rr8, X86::MOVZX32rr16, X86::MOVZX16rr8
2400     };
2401     Tmp1 = SelectExpr(N.getOperand(0));
2402     BuildMI(BB, Opc[SrcIs16+DestIs16*2], 1, Result).addReg(Tmp1);
2403     return Result;
2404   }
2405   case ISD::SIGN_EXTEND: {
2406     int DestIs16 = N.getValueType() == MVT::i16;
2407     int SrcIs16  = N.getOperand(0).getValueType() == MVT::i16;
2408
2409     // FIXME: Legalize should promote bools to i8!
2410     assert(N.getOperand(0).getValueType() != MVT::i1 &&
2411            "Sign extend from bool not implemented!");
2412
2413     if (isFoldableLoad(N.getOperand(0), SDOperand())) {
2414       static const unsigned Opc[3] = {
2415         X86::MOVSX32rm8, X86::MOVSX32rm16, X86::MOVSX16rm8
2416       };
2417
2418       X86AddressMode AM;
2419       EmitFoldedLoad(N.getOperand(0), AM);
2420       addFullAddress(BuildMI(BB, Opc[SrcIs16+DestIs16*2], 4, Result), AM);
2421       return Result;
2422     }
2423
2424     static const unsigned Opc[3] = {
2425       X86::MOVSX32rr8, X86::MOVSX32rr16, X86::MOVSX16rr8
2426     };
2427     Tmp1 = SelectExpr(N.getOperand(0));
2428     BuildMI(BB, Opc[SrcIs16+DestIs16*2], 1, Result).addReg(Tmp1);
2429     return Result;
2430   }
2431   case ISD::TRUNCATE:
2432     // Fold TRUNCATE (LOAD P) into a smaller load from P.
2433     // FIXME: This should be performed by the DAGCombiner.
2434     if (isFoldableLoad(N.getOperand(0), SDOperand())) {
2435       switch (N.getValueType()) {
2436       default: assert(0 && "Unknown truncate!");
2437       case MVT::i1:
2438       case MVT::i8:  Opc = X86::MOV8rm;  break;
2439       case MVT::i16: Opc = X86::MOV16rm; break;
2440       }
2441       X86AddressMode AM;
2442       EmitFoldedLoad(N.getOperand(0), AM);
2443       addFullAddress(BuildMI(BB, Opc, 4, Result), AM);
2444       return Result;
2445     }
2446
2447     // Handle cast of LARGER int to SMALLER int using a move to EAX followed by
2448     // a move out of AX or AL.
2449     switch (N.getOperand(0).getValueType()) {
2450     default: assert(0 && "Unknown truncate!");
2451     case MVT::i8:  Tmp2 = X86::AL;  Opc = X86::MOV8rr;  break;
2452     case MVT::i16: Tmp2 = X86::AX;  Opc = X86::MOV16rr; break;
2453     case MVT::i32: Tmp2 = X86::EAX; Opc = X86::MOV32rr; break;
2454     }
2455     Tmp1 = SelectExpr(N.getOperand(0));
2456     BuildMI(BB, Opc, 1, Tmp2).addReg(Tmp1);
2457
2458     switch (N.getValueType()) {
2459     default: assert(0 && "Unknown truncate!");
2460     case MVT::i1:
2461     case MVT::i8:  Tmp2 = X86::AL;  Opc = X86::MOV8rr;  break;
2462     case MVT::i16: Tmp2 = X86::AX;  Opc = X86::MOV16rr; break;
2463     }
2464     BuildMI(BB, Opc, 1, Result).addReg(Tmp2);
2465     return Result;
2466
2467   case ISD::SINT_TO_FP: {
2468     Tmp1 = SelectExpr(N.getOperand(0));  // Get the operand register
2469     unsigned PromoteOpcode = 0;
2470
2471     // We can handle any sint to fp with the direct sse conversion instructions.
2472     if (X86ScalarSSE) {
2473       Opc = (N.getValueType() == MVT::f64) ? X86::CVTSI2SDrr : X86::CVTSI2SSrr;
2474       BuildMI(BB, Opc, 1, Result).addReg(Tmp1);
2475       return Result;
2476     }
2477
2478     ContainsFPCode = true;
2479
2480     // Spill the integer to memory and reload it from there.
2481     MVT::ValueType SrcTy = N.getOperand(0).getValueType();
2482     unsigned Size = MVT::getSizeInBits(SrcTy)/8;
2483     MachineFunction *F = BB->getParent();
2484     int FrameIdx = F->getFrameInfo()->CreateStackObject(Size, Size);
2485
2486     switch (SrcTy) {
2487     case MVT::i32:
2488       addFrameReference(BuildMI(BB, X86::MOV32mr, 5), FrameIdx).addReg(Tmp1);
2489       addFrameReference(BuildMI(BB, X86::FILD32m, 5, Result), FrameIdx);
2490       break;
2491     case MVT::i16:
2492       addFrameReference(BuildMI(BB, X86::MOV16mr, 5), FrameIdx).addReg(Tmp1);
2493       addFrameReference(BuildMI(BB, X86::FILD16m, 5, Result), FrameIdx);
2494       break;
2495     default: break; // No promotion required.
2496     }
2497     return Result;
2498   }
2499   case ISD::FP_TO_SINT:
2500     Tmp1 = SelectExpr(N.getOperand(0));  // Get the operand register
2501
2502     // If the target supports SSE2 and is performing FP operations in SSE regs
2503     // instead of the FP stack, then we can use the efficient CVTSS2SI and
2504     // CVTSD2SI instructions.
2505     assert(X86ScalarSSE);
2506     if (MVT::f32 == N.getOperand(0).getValueType()) {
2507       BuildMI(BB, X86::CVTTSS2SIrr, 1, Result).addReg(Tmp1);
2508     } else if (MVT::f64 == N.getOperand(0).getValueType()) {
2509       BuildMI(BB, X86::CVTTSD2SIrr, 1, Result).addReg(Tmp1);
2510     } else {
2511       assert(0 && "Not an f32 or f64?");
2512       abort();
2513     }
2514     return Result;
2515
2516   case ISD::FADD:
2517   case ISD::ADD:
2518     Op0 = N.getOperand(0);
2519     Op1 = N.getOperand(1);
2520
2521     if (isFoldableLoad(Op0, Op1, true)) {
2522       std::swap(Op0, Op1);
2523       goto FoldAdd;
2524     }
2525
2526     if (isFoldableLoad(Op1, Op0, true)) {
2527     FoldAdd:
2528       switch (N.getValueType()) {
2529       default: assert(0 && "Cannot add this type!");
2530       case MVT::i1:
2531       case MVT::i8:  Opc = X86::ADD8rm;  break;
2532       case MVT::i16: Opc = X86::ADD16rm; break;
2533       case MVT::i32: Opc = X86::ADD32rm; break;
2534       case MVT::f32: Opc = X86::ADDSSrm; break;
2535       case MVT::f64:
2536         // For F64, handle promoted load operations (from F32) as well!
2537         if (X86ScalarSSE) {
2538           assert(Op1.getOpcode() == ISD::LOAD && "SSE load not promoted");
2539           Opc = X86::ADDSDrm;
2540         } else {
2541           Opc = Op1.getOpcode() == ISD::LOAD ? X86::FADD64m : X86::FADD32m;
2542         }
2543         break;
2544       }
2545       X86AddressMode AM;
2546       EmitFoldedLoad(Op1, AM);
2547       Tmp1 = SelectExpr(Op0);
2548       addFullAddress(BuildMI(BB, Opc, 5, Result).addReg(Tmp1), AM);
2549       return Result;
2550     }
2551
2552     // See if we can codegen this as an LEA to fold operations together.
2553     if (N.getValueType() == MVT::i32) {
2554       ExprMap.erase(N);
2555       X86ISelAddressMode AM;
2556       MatchAddress(N, AM);
2557       ExprMap[N] = Result;
2558
2559       // If this is not just an add, emit the LEA.  For a simple add (like
2560       // reg+reg or reg+imm), we just emit an add.  It might be a good idea to
2561       // leave this as LEA, then peephole it to 'ADD' after two address elim
2562       // happens.
2563       if (AM.Scale != 1 || AM.BaseType == X86ISelAddressMode::FrameIndexBase||
2564           AM.GV || (AM.Base.Reg.Val && AM.IndexReg.Val && AM.Disp)) {
2565         X86AddressMode XAM = SelectAddrExprs(AM);
2566         addFullAddress(BuildMI(BB, X86::LEA32r, 4, Result), XAM);
2567         return Result;
2568       }
2569     }
2570
2571     if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(Op1)) {
2572       Opc = 0;
2573       if (CN->getValue() == 1) {   // add X, 1 -> inc X
2574         switch (N.getValueType()) {
2575         default: assert(0 && "Cannot integer add this type!");
2576         case MVT::i8:  Opc = X86::INC8r; break;
2577         case MVT::i16: Opc = X86::INC16r; break;
2578         case MVT::i32: Opc = X86::INC32r; break;
2579         }
2580       } else if (CN->isAllOnesValue()) { // add X, -1 -> dec X
2581         switch (N.getValueType()) {
2582         default: assert(0 && "Cannot integer add this type!");
2583         case MVT::i8:  Opc = X86::DEC8r; break;
2584         case MVT::i16: Opc = X86::DEC16r; break;
2585         case MVT::i32: Opc = X86::DEC32r; break;
2586         }
2587       }
2588
2589       if (Opc) {
2590         Tmp1 = SelectExpr(Op0);
2591         BuildMI(BB, Opc, 1, Result).addReg(Tmp1);
2592         return Result;
2593       }
2594
2595       switch (N.getValueType()) {
2596       default: assert(0 && "Cannot add this type!");
2597       case MVT::i8:  Opc = X86::ADD8ri; break;
2598       case MVT::i16: Opc = X86::ADD16ri; break;
2599       case MVT::i32: Opc = X86::ADD32ri; break;
2600       }
2601       if (Opc) {
2602         Tmp1 = SelectExpr(Op0);
2603         BuildMI(BB, Opc, 2, Result).addReg(Tmp1).addImm(CN->getValue());
2604         return Result;
2605       }
2606     }
2607
2608     switch (N.getValueType()) {
2609     default: assert(0 && "Cannot add this type!");
2610     case MVT::i8:  Opc = X86::ADD8rr; break;
2611     case MVT::i16: Opc = X86::ADD16rr; break;
2612     case MVT::i32: Opc = X86::ADD32rr; break;
2613     case MVT::f32: Opc = X86::ADDSSrr; break;
2614     case MVT::f64: Opc = X86ScalarSSE ? X86::ADDSDrr : X86::FpADD; break;
2615     }
2616
2617     if (getRegPressure(Op0) > getRegPressure(Op1)) {
2618       Tmp1 = SelectExpr(Op0);
2619       Tmp2 = SelectExpr(Op1);
2620     } else {
2621       Tmp2 = SelectExpr(Op1);
2622       Tmp1 = SelectExpr(Op0);
2623     }
2624
2625     BuildMI(BB, Opc, 2, Result).addReg(Tmp1).addReg(Tmp2);
2626     return Result;
2627
2628   case ISD::FSQRT:
2629     Tmp1 = SelectExpr(Node->getOperand(0));
2630     if (X86ScalarSSE) {
2631       Opc = (N.getValueType() == MVT::f32) ? X86::SQRTSSrr : X86::SQRTSDrr;
2632       BuildMI(BB, Opc, 1, Result).addReg(Tmp1);
2633     } else {
2634       BuildMI(BB, X86::FSQRT, 1, Result).addReg(Tmp1);
2635     }
2636     return Result;
2637
2638   // FIXME:
2639   // Once we can spill 16 byte constants into the constant pool, we can
2640   // implement SSE equivalents of FABS and FCHS.
2641   case ISD::FABS:
2642   case ISD::FNEG:
2643   case ISD::FSIN:
2644   case ISD::FCOS:
2645     assert(N.getValueType()==MVT::f64 && "Illegal type for this operation");
2646     Tmp1 = SelectExpr(Node->getOperand(0));
2647     switch (N.getOpcode()) {
2648     default: assert(0 && "Unreachable!");
2649     case ISD::FABS: BuildMI(BB, X86::FABS, 1, Result).addReg(Tmp1); break;
2650     case ISD::FNEG: BuildMI(BB, X86::FCHS, 1, Result).addReg(Tmp1); break;
2651     case ISD::FSIN: BuildMI(BB, X86::FSIN, 1, Result).addReg(Tmp1); break;
2652     case ISD::FCOS: BuildMI(BB, X86::FCOS, 1, Result).addReg(Tmp1); break;
2653     }
2654     return Result;
2655
2656   case ISD::MULHU:
2657     switch (N.getValueType()) {
2658     default: assert(0 && "Unsupported VT!");
2659     case MVT::i8:  Tmp2 = X86::MUL8r;  break;
2660     case MVT::i16: Tmp2 = X86::MUL16r;  break;
2661     case MVT::i32: Tmp2 = X86::MUL32r;  break;
2662     }
2663     // FALL THROUGH
2664   case ISD::MULHS: {
2665     unsigned MovOpc, LowReg, HiReg;
2666     switch (N.getValueType()) {
2667     default: assert(0 && "Unsupported VT!");
2668     case MVT::i8:
2669       MovOpc = X86::MOV8rr;
2670       LowReg = X86::AL;
2671       HiReg = X86::AH;
2672       Opc = X86::IMUL8r;
2673       break;
2674     case MVT::i16:
2675       MovOpc = X86::MOV16rr;
2676       LowReg = X86::AX;
2677       HiReg = X86::DX;
2678       Opc = X86::IMUL16r;
2679       break;
2680     case MVT::i32:
2681       MovOpc = X86::MOV32rr;
2682       LowReg = X86::EAX;
2683       HiReg = X86::EDX;
2684       Opc = X86::IMUL32r;
2685       break;
2686     }
2687     if (Node->getOpcode() != ISD::MULHS)
2688       Opc = Tmp2;  // Get the MULHU opcode.
2689
2690     Op0 = Node->getOperand(0);
2691     Op1 = Node->getOperand(1);
2692     if (getRegPressure(Op0) > getRegPressure(Op1)) {
2693       Tmp1 = SelectExpr(Op0);
2694       Tmp2 = SelectExpr(Op1);
2695     } else {
2696       Tmp2 = SelectExpr(Op1);
2697       Tmp1 = SelectExpr(Op0);
2698     }
2699
2700     // FIXME: Implement folding of loads into the memory operands here!
2701     BuildMI(BB, MovOpc, 1, LowReg).addReg(Tmp1);
2702     BuildMI(BB, Opc, 1).addReg(Tmp2);
2703     BuildMI(BB, MovOpc, 1, Result).addReg(HiReg);
2704     return Result;
2705   }
2706
2707   case ISD::FSUB:
2708   case ISD::FMUL:
2709   case ISD::SUB:
2710   case ISD::MUL:
2711   case ISD::AND:
2712   case ISD::OR:
2713   case ISD::XOR: {
2714     static const unsigned SUBTab[] = {
2715       X86::SUB8ri, X86::SUB16ri, X86::SUB32ri, 0, 0,
2716       X86::SUB8rm, X86::SUB16rm, X86::SUB32rm, X86::FSUB32m, X86::FSUB64m,
2717       X86::SUB8rr, X86::SUB16rr, X86::SUB32rr, X86::FpSUB  , X86::FpSUB,
2718     };
2719     static const unsigned SSE_SUBTab[] = {
2720       X86::SUB8ri, X86::SUB16ri, X86::SUB32ri, 0, 0,
2721       X86::SUB8rm, X86::SUB16rm, X86::SUB32rm, X86::SUBSSrm, X86::SUBSDrm,
2722       X86::SUB8rr, X86::SUB16rr, X86::SUB32rr, X86::SUBSSrr, X86::SUBSDrr,
2723     };
2724     static const unsigned MULTab[] = {
2725       0, X86::IMUL16rri, X86::IMUL32rri, 0, 0,
2726       0, X86::IMUL16rm , X86::IMUL32rm, X86::FMUL32m, X86::FMUL64m,
2727       0, X86::IMUL16rr , X86::IMUL32rr, X86::FpMUL  , X86::FpMUL,
2728     };
2729     static const unsigned SSE_MULTab[] = {
2730       0, X86::IMUL16rri, X86::IMUL32rri, 0, 0,
2731       0, X86::IMUL16rm , X86::IMUL32rm, X86::MULSSrm, X86::MULSDrm,
2732       0, X86::IMUL16rr , X86::IMUL32rr, X86::MULSSrr, X86::MULSDrr,
2733     };
2734     static const unsigned ANDTab[] = {
2735       X86::AND8ri, X86::AND16ri, X86::AND32ri, 0, 0,
2736       X86::AND8rm, X86::AND16rm, X86::AND32rm, 0, 0,
2737       X86::AND8rr, X86::AND16rr, X86::AND32rr, 0, 0,
2738     };
2739     static const unsigned ORTab[] = {
2740       X86::OR8ri, X86::OR16ri, X86::OR32ri, 0, 0,
2741       X86::OR8rm, X86::OR16rm, X86::OR32rm, 0, 0,
2742       X86::OR8rr, X86::OR16rr, X86::OR32rr, 0, 0,
2743     };
2744     static const unsigned XORTab[] = {
2745       X86::XOR8ri, X86::XOR16ri, X86::XOR32ri, 0, 0,
2746       X86::XOR8rm, X86::XOR16rm, X86::XOR32rm, 0, 0,
2747       X86::XOR8rr, X86::XOR16rr, X86::XOR32rr, 0, 0,
2748     };
2749
2750     Op0 = Node->getOperand(0);
2751     Op1 = Node->getOperand(1);
2752
2753     if (Node->getOpcode() == ISD::OR && Op0.hasOneUse() && Op1.hasOneUse())
2754       if (EmitOrOpOp(Op0, Op1, Result)) // Match SHLD, SHRD, and rotates.
2755         return Result;
2756
2757     if (Node->getOpcode() == ISD::SUB)
2758       if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N.getOperand(0)))
2759         if (CN->isNullValue()) {   // 0 - N -> neg N
2760           switch (N.getValueType()) {
2761           default: assert(0 && "Cannot sub this type!");
2762           case MVT::i1:
2763           case MVT::i8:  Opc = X86::NEG8r;  break;
2764           case MVT::i16: Opc = X86::NEG16r; break;
2765           case MVT::i32: Opc = X86::NEG32r; break;
2766           }
2767           Tmp1 = SelectExpr(N.getOperand(1));
2768           BuildMI(BB, Opc, 1, Result).addReg(Tmp1);
2769           return Result;
2770         }
2771
2772     if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(Op1)) {
2773       if (CN->isAllOnesValue() && Node->getOpcode() == ISD::XOR) {
2774         Opc = 0;
2775         switch (N.getValueType()) {
2776         default: assert(0 && "Cannot add this type!");
2777         case MVT::i1:  break;  // Not supported, don't invert upper bits!
2778         case MVT::i8:  Opc = X86::NOT8r;  break;
2779         case MVT::i16: Opc = X86::NOT16r; break;
2780         case MVT::i32: Opc = X86::NOT32r; break;
2781         }
2782         if (Opc) {
2783           Tmp1 = SelectExpr(Op0);
2784           BuildMI(BB, Opc, 1, Result).addReg(Tmp1);
2785           return Result;
2786         }
2787       }
2788
2789       // Fold common multiplies into LEA instructions.
2790       if (Node->getOpcode() == ISD::MUL && N.getValueType() == MVT::i32) {
2791         switch ((int)CN->getValue()) {
2792         default: break;
2793         case 3:
2794         case 5:
2795         case 9:
2796           // Remove N from exprmap so SelectAddress doesn't get confused.
2797           ExprMap.erase(N);
2798           X86AddressMode AM;
2799           SelectAddress(N, AM);
2800           // Restore it to the map.
2801           ExprMap[N] = Result;
2802           addFullAddress(BuildMI(BB, X86::LEA32r, 4, Result), AM);
2803           return Result;
2804         }
2805       }
2806
2807       switch (N.getValueType()) {
2808       default: assert(0 && "Cannot xor this type!");
2809       case MVT::i1:
2810       case MVT::i8:  Opc = 0; break;
2811       case MVT::i16: Opc = 1; break;
2812       case MVT::i32: Opc = 2; break;
2813       }
2814       switch (Node->getOpcode()) {
2815       default: assert(0 && "Unreachable!");
2816       case ISD::FSUB:
2817       case ISD::SUB: Opc = X86ScalarSSE ? SSE_SUBTab[Opc] : SUBTab[Opc]; break;
2818       case ISD::FMUL:
2819       case ISD::MUL: Opc = X86ScalarSSE ? SSE_MULTab[Opc] : MULTab[Opc]; break;
2820       case ISD::AND: Opc = ANDTab[Opc]; break;
2821       case ISD::OR:  Opc =  ORTab[Opc]; break;
2822       case ISD::XOR: Opc = XORTab[Opc]; break;
2823       }
2824       if (Opc) {  // Can't fold MUL:i8 R, imm
2825         Tmp1 = SelectExpr(Op0);
2826         BuildMI(BB, Opc, 2, Result).addReg(Tmp1).addImm(CN->getValue());
2827         return Result;
2828       }
2829     }
2830
2831     if (isFoldableLoad(Op0, Op1, true))
2832       if (Node->getOpcode() != ISD::SUB && Node->getOpcode() != ISD::FSUB) {
2833         std::swap(Op0, Op1);
2834         goto FoldOps;
2835       } else {
2836         // For FP, emit 'reverse' subract, with a memory operand.
2837         if (N.getValueType() == MVT::f64 && !X86ScalarSSE) {
2838           if (Op0.getOpcode() == ISD::EXTLOAD)
2839             Opc = X86::FSUBR32m;
2840           else
2841             Opc = X86::FSUBR64m;
2842
2843           X86AddressMode AM;
2844           EmitFoldedLoad(Op0, AM);
2845           Tmp1 = SelectExpr(Op1);
2846           addFullAddress(BuildMI(BB, Opc, 5, Result).addReg(Tmp1), AM);
2847           return Result;
2848         }
2849       }
2850
2851     if (isFoldableLoad(Op1, Op0, true)) {
2852     FoldOps:
2853       switch (N.getValueType()) {
2854       default: assert(0 && "Cannot operate on this type!");
2855       case MVT::i1:
2856       case MVT::i8:  Opc = 5; break;
2857       case MVT::i16: Opc = 6; break;
2858       case MVT::i32: Opc = 7; break;
2859       case MVT::f32: Opc = 8; break;
2860         // For F64, handle promoted load operations (from F32) as well!
2861       case MVT::f64:
2862         assert((!X86ScalarSSE || Op1.getOpcode() == ISD::LOAD) &&
2863                "SSE load should have been promoted");
2864         Opc = Op1.getOpcode() == ISD::LOAD ? 9 : 8; break;
2865       }
2866       switch (Node->getOpcode()) {
2867       default: assert(0 && "Unreachable!");
2868       case ISD::FSUB:
2869       case ISD::SUB: Opc = X86ScalarSSE ? SSE_SUBTab[Opc] : SUBTab[Opc]; break;
2870       case ISD::FMUL:
2871       case ISD::MUL: Opc = X86ScalarSSE ? SSE_MULTab[Opc] : MULTab[Opc]; break;
2872       case ISD::AND: Opc = ANDTab[Opc]; break;
2873       case ISD::OR:  Opc =  ORTab[Opc]; break;
2874       case ISD::XOR: Opc = XORTab[Opc]; break;
2875       }
2876
2877       X86AddressMode AM;
2878       EmitFoldedLoad(Op1, AM);
2879       Tmp1 = SelectExpr(Op0);
2880       if (Opc) {
2881         addFullAddress(BuildMI(BB, Opc, 5, Result).addReg(Tmp1), AM);
2882       } else {
2883         assert(Node->getOpcode() == ISD::MUL &&
2884                N.getValueType() == MVT::i8 && "Unexpected situation!");
2885         // Must use the MUL instruction, which forces use of AL.
2886         BuildMI(BB, X86::MOV8rr, 1, X86::AL).addReg(Tmp1);
2887         addFullAddress(BuildMI(BB, X86::MUL8m, 1), AM);
2888         BuildMI(BB, X86::MOV8rr, 1, Result).addReg(X86::AL);
2889       }
2890       return Result;
2891     }
2892
2893     if (getRegPressure(Op0) > getRegPressure(Op1)) {
2894       Tmp1 = SelectExpr(Op0);
2895       Tmp2 = SelectExpr(Op1);
2896     } else {
2897       Tmp2 = SelectExpr(Op1);
2898       Tmp1 = SelectExpr(Op0);
2899     }
2900
2901     switch (N.getValueType()) {
2902     default: assert(0 && "Cannot add this type!");
2903     case MVT::i1:
2904     case MVT::i8:  Opc = 10; break;
2905     case MVT::i16: Opc = 11; break;
2906     case MVT::i32: Opc = 12; break;
2907     case MVT::f32: Opc = 13; break;
2908     case MVT::f64: Opc = 14; break;
2909     }
2910     switch (Node->getOpcode()) {
2911     default: assert(0 && "Unreachable!");
2912     case ISD::FSUB:
2913     case ISD::SUB: Opc = X86ScalarSSE ? SSE_SUBTab[Opc] : SUBTab[Opc]; break;
2914     case ISD::FMUL:
2915     case ISD::MUL: Opc = X86ScalarSSE ? SSE_MULTab[Opc] : MULTab[Opc]; break;
2916     case ISD::AND: Opc = ANDTab[Opc]; break;
2917     case ISD::OR:  Opc =  ORTab[Opc]; break;
2918     case ISD::XOR: Opc = XORTab[Opc]; break;
2919     }
2920     if (Opc) {
2921       BuildMI(BB, Opc, 2, Result).addReg(Tmp1).addReg(Tmp2);
2922     } else {
2923       assert(Node->getOpcode() == ISD::MUL &&
2924              N.getValueType() == MVT::i8 && "Unexpected situation!");
2925       // Must use the MUL instruction, which forces use of AL.
2926       BuildMI(BB, X86::MOV8rr, 1, X86::AL).addReg(Tmp1);
2927       BuildMI(BB, X86::MUL8r, 1).addReg(Tmp2);
2928       BuildMI(BB, X86::MOV8rr, 1, Result).addReg(X86::AL);
2929     }
2930     return Result;
2931   }
2932   case ISD::ADD_PARTS:
2933   case ISD::SUB_PARTS: {
2934     assert(N.getNumOperands() == 4 && N.getValueType() == MVT::i32 &&
2935            "Not an i64 add/sub!");
2936     // Emit all of the operands.
2937     std::vector<unsigned> InVals;
2938     for (unsigned i = 0, e = N.getNumOperands(); i != e; ++i)
2939       InVals.push_back(SelectExpr(N.getOperand(i)));
2940     if (N.getOpcode() == ISD::ADD_PARTS) {
2941       BuildMI(BB, X86::ADD32rr, 2, Result).addReg(InVals[0]).addReg(InVals[2]);
2942       BuildMI(BB, X86::ADC32rr,2,Result+1).addReg(InVals[1]).addReg(InVals[3]);
2943     } else {
2944       BuildMI(BB, X86::SUB32rr, 2, Result).addReg(InVals[0]).addReg(InVals[2]);
2945       BuildMI(BB, X86::SBB32rr, 2,Result+1).addReg(InVals[1]).addReg(InVals[3]);
2946     }
2947     return Result+N.ResNo;
2948   }
2949
2950   case ISD::SHL_PARTS:
2951   case ISD::SRA_PARTS:
2952   case ISD::SRL_PARTS: {
2953     assert(N.getNumOperands() == 3 && N.getValueType() == MVT::i32 &&
2954            "Not an i64 shift!");
2955     unsigned ShiftOpLo = SelectExpr(N.getOperand(0));
2956     unsigned ShiftOpHi = SelectExpr(N.getOperand(1));
2957     unsigned TmpReg = MakeReg(MVT::i32);
2958     if (N.getOpcode() == ISD::SRA_PARTS) {
2959       // If this is a SHR of a Long, then we need to do funny sign extension
2960       // stuff.  TmpReg gets the value to use as the high-part if we are
2961       // shifting more than 32 bits.
2962       BuildMI(BB, X86::SAR32ri, 2, TmpReg).addReg(ShiftOpHi).addImm(31);
2963     } else {
2964       // Other shifts use a fixed zero value if the shift is more than 32 bits.
2965       BuildMI(BB, X86::MOV32ri, 1, TmpReg).addImm(0);
2966     }
2967
2968     // Initialize CL with the shift amount.
2969     unsigned ShiftAmountReg = SelectExpr(N.getOperand(2));
2970     BuildMI(BB, X86::MOV8rr, 1, X86::CL).addReg(ShiftAmountReg);
2971
2972     unsigned TmpReg2 = MakeReg(MVT::i32);
2973     unsigned TmpReg3 = MakeReg(MVT::i32);
2974     if (N.getOpcode() == ISD::SHL_PARTS) {
2975       // TmpReg2 = shld inHi, inLo
2976       BuildMI(BB, X86::SHLD32rrCL, 2,TmpReg2).addReg(ShiftOpHi)
2977         .addReg(ShiftOpLo);
2978       // TmpReg3 = shl  inLo, CL
2979       BuildMI(BB, X86::SHL32rCL, 1, TmpReg3).addReg(ShiftOpLo);
2980
2981       // Set the flags to indicate whether the shift was by more than 32 bits.
2982       BuildMI(BB, X86::TEST8ri, 2).addReg(X86::CL).addImm(32);
2983
2984       // DestHi = (>32) ? TmpReg3 : TmpReg2;
2985       BuildMI(BB, X86::CMOVNE32rr, 2,
2986               Result+1).addReg(TmpReg2).addReg(TmpReg3);
2987       // DestLo = (>32) ? TmpReg : TmpReg3;
2988       BuildMI(BB, X86::CMOVNE32rr, 2,
2989               Result).addReg(TmpReg3).addReg(TmpReg);
2990     } else {
2991       // TmpReg2 = shrd inLo, inHi
2992       BuildMI(BB, X86::SHRD32rrCL,2,TmpReg2).addReg(ShiftOpLo)
2993         .addReg(ShiftOpHi);
2994       // TmpReg3 = s[ah]r  inHi, CL
2995       BuildMI(BB, N.getOpcode() == ISD::SRA_PARTS ? X86::SAR32rCL
2996                                                   : X86::SHR32rCL, 1, TmpReg3)
2997         .addReg(ShiftOpHi);
2998
2999       // Set the flags to indicate whether the shift was by more than 32 bits.
3000       BuildMI(BB, X86::TEST8ri, 2).addReg(X86::CL).addImm(32);
3001
3002       // DestLo = (>32) ? TmpReg3 : TmpReg2;
3003       BuildMI(BB, X86::CMOVNE32rr, 2,
3004               Result).addReg(TmpReg2).addReg(TmpReg3);
3005
3006       // DestHi = (>32) ? TmpReg : TmpReg3;
3007       BuildMI(BB, X86::CMOVNE32rr, 2,
3008               Result+1).addReg(TmpReg3).addReg(TmpReg);
3009     }
3010     return Result+N.ResNo;
3011   }
3012
3013   case ISD::SELECT:
3014     EmitSelectCC(N.getOperand(0), N.getOperand(1), N.getOperand(2),
3015                  N.getValueType(), Result);
3016     return Result;
3017
3018   case ISD::FDIV:
3019   case ISD::FREM:
3020   case ISD::SDIV:
3021   case ISD::UDIV:
3022   case ISD::SREM:
3023   case ISD::UREM: {
3024     assert((N.getOpcode() != ISD::SREM || MVT::isInteger(N.getValueType())) &&
3025            "We don't support this operator!");
3026
3027     if (N.getOpcode() == ISD::SDIV || N.getOpcode() == ISD::FDIV) {
3028       // We can fold loads into FpDIVs, but not really into any others.
3029       if (N.getValueType() == MVT::f64 && !X86ScalarSSE) {
3030         // Check for reversed and unreversed DIV.
3031         if (isFoldableLoad(N.getOperand(0), N.getOperand(1), true)) {
3032           if (N.getOperand(0).getOpcode() == ISD::EXTLOAD)
3033             Opc = X86::FDIVR32m;
3034           else
3035             Opc = X86::FDIVR64m;
3036           X86AddressMode AM;
3037           EmitFoldedLoad(N.getOperand(0), AM);
3038           Tmp1 = SelectExpr(N.getOperand(1));
3039           addFullAddress(BuildMI(BB, Opc, 5, Result).addReg(Tmp1), AM);
3040           return Result;
3041         } else if (isFoldableLoad(N.getOperand(1), N.getOperand(0), true) &&
3042                    N.getOperand(1).getOpcode() == ISD::LOAD) {
3043           if (N.getOperand(1).getOpcode() == ISD::EXTLOAD)
3044             Opc = X86::FDIV32m;
3045           else
3046             Opc = X86::FDIV64m;
3047           X86AddressMode AM;
3048           EmitFoldedLoad(N.getOperand(1), AM);
3049           Tmp1 = SelectExpr(N.getOperand(0));
3050           addFullAddress(BuildMI(BB, Opc, 5, Result).addReg(Tmp1), AM);
3051           return Result;
3052         }
3053       }
3054
3055       if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N.getOperand(1))) {
3056         // FIXME: These special cases should be handled by the lowering impl!
3057         unsigned RHS = CN->getValue();
3058         bool isNeg = false;
3059         if ((int)RHS < 0) {
3060           isNeg = true;
3061           RHS = -RHS;
3062         }
3063         if (RHS && (RHS & (RHS-1)) == 0) {   // Signed division by power of 2?
3064           unsigned Log = Log2_32(RHS);
3065           unsigned SAROpc, SHROpc, ADDOpc, NEGOpc;
3066           switch (N.getValueType()) {
3067           default: assert("Unknown type to signed divide!");
3068           case MVT::i8:
3069             SAROpc = X86::SAR8ri;
3070             SHROpc = X86::SHR8ri;
3071             ADDOpc = X86::ADD8rr;
3072             NEGOpc = X86::NEG8r;
3073             break;
3074           case MVT::i16:
3075             SAROpc = X86::SAR16ri;
3076             SHROpc = X86::SHR16ri;
3077             ADDOpc = X86::ADD16rr;
3078             NEGOpc = X86::NEG16r;
3079             break;
3080           case MVT::i32:
3081             SAROpc = X86::SAR32ri;
3082             SHROpc = X86::SHR32ri;
3083             ADDOpc = X86::ADD32rr;
3084             NEGOpc = X86::NEG32r;
3085             break;
3086           }
3087           unsigned RegSize = MVT::getSizeInBits(N.getValueType());
3088           Tmp1 = SelectExpr(N.getOperand(0));
3089           unsigned TmpReg;
3090           if (Log != 1) {
3091             TmpReg = MakeReg(N.getValueType());
3092             BuildMI(BB, SAROpc, 2, TmpReg).addReg(Tmp1).addImm(Log-1);
3093           } else {
3094             TmpReg = Tmp1;
3095           }
3096           unsigned TmpReg2 = MakeReg(N.getValueType());
3097           BuildMI(BB, SHROpc, 2, TmpReg2).addReg(TmpReg).addImm(RegSize-Log);
3098           unsigned TmpReg3 = MakeReg(N.getValueType());
3099           BuildMI(BB, ADDOpc, 2, TmpReg3).addReg(Tmp1).addReg(TmpReg2);
3100
3101           unsigned TmpReg4 = isNeg ? MakeReg(N.getValueType()) : Result;
3102           BuildMI(BB, SAROpc, 2, TmpReg4).addReg(TmpReg3).addImm(Log);
3103           if (isNeg)
3104             BuildMI(BB, NEGOpc, 1, Result).addReg(TmpReg4);
3105           return Result;
3106         }
3107       }
3108     }
3109
3110     if (getRegPressure(N.getOperand(0)) > getRegPressure(N.getOperand(1))) {
3111       Tmp1 = SelectExpr(N.getOperand(0));
3112       Tmp2 = SelectExpr(N.getOperand(1));
3113     } else {
3114       Tmp2 = SelectExpr(N.getOperand(1));
3115       Tmp1 = SelectExpr(N.getOperand(0));
3116     }
3117
3118     bool isSigned = N.getOpcode() == ISD::SDIV || N.getOpcode() == ISD::SREM;
3119     bool isDiv    = N.getOpcode() == ISD::SDIV || N.getOpcode() == ISD::UDIV;
3120     unsigned LoReg, HiReg, DivOpcode, MovOpcode, ClrOpcode, SExtOpcode;
3121     switch (N.getValueType()) {
3122     default: assert(0 && "Cannot sdiv this type!");
3123     case MVT::i8:
3124       DivOpcode = isSigned ? X86::IDIV8r : X86::DIV8r;
3125       LoReg = X86::AL;
3126       HiReg = X86::AH;
3127       MovOpcode = X86::MOV8rr;
3128       ClrOpcode = X86::MOV8ri;
3129       SExtOpcode = X86::CBW;
3130       break;
3131     case MVT::i16:
3132       DivOpcode = isSigned ? X86::IDIV16r : X86::DIV16r;
3133       LoReg = X86::AX;
3134       HiReg = X86::DX;
3135       MovOpcode = X86::MOV16rr;
3136       ClrOpcode = X86::MOV16ri;
3137       SExtOpcode = X86::CWD;
3138       break;
3139     case MVT::i32:
3140       DivOpcode = isSigned ? X86::IDIV32r : X86::DIV32r;
3141       LoReg = X86::EAX;
3142       HiReg = X86::EDX;
3143       MovOpcode = X86::MOV32rr;
3144       ClrOpcode = X86::MOV32ri;
3145       SExtOpcode = X86::CDQ;
3146       break;
3147     case MVT::f32:
3148       BuildMI(BB, X86::DIVSSrr, 2, Result).addReg(Tmp1).addReg(Tmp2);
3149       return Result;
3150     case MVT::f64:
3151       Opc = X86ScalarSSE ? X86::DIVSDrr : X86::FpDIV;
3152       BuildMI(BB, Opc, 2, Result).addReg(Tmp1).addReg(Tmp2);
3153       return Result;
3154     }
3155
3156     // Set up the low part.
3157     BuildMI(BB, MovOpcode, 1, LoReg).addReg(Tmp1);
3158
3159     if (isSigned) {
3160       // Sign extend the low part into the high part.
3161       BuildMI(BB, SExtOpcode, 0);
3162     } else {
3163       // Zero out the high part, effectively zero extending the input.
3164       BuildMI(BB, ClrOpcode, 1, HiReg).addImm(0);
3165     }
3166
3167     // Emit the DIV/IDIV instruction.
3168     BuildMI(BB, DivOpcode, 1).addReg(Tmp2);
3169
3170     // Get the result of the divide or rem.
3171     BuildMI(BB, MovOpcode, 1, Result).addReg(isDiv ? LoReg : HiReg);
3172     return Result;
3173   }
3174
3175   case ISD::SHL:
3176     if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N.getOperand(1))) {
3177       if (CN->getValue() == 1) {   // X = SHL Y, 1  -> X = ADD Y, Y
3178         switch (N.getValueType()) {
3179         default: assert(0 && "Cannot shift this type!");
3180         case MVT::i8:  Opc = X86::ADD8rr; break;
3181         case MVT::i16: Opc = X86::ADD16rr; break;
3182         case MVT::i32: Opc = X86::ADD32rr; break;
3183         }
3184         Tmp1 = SelectExpr(N.getOperand(0));
3185         BuildMI(BB, Opc, 2, Result).addReg(Tmp1).addReg(Tmp1);
3186         return Result;
3187       }
3188
3189       switch (N.getValueType()) {
3190       default: assert(0 && "Cannot shift this type!");
3191       case MVT::i8:  Opc = X86::SHL8ri; break;
3192       case MVT::i16: Opc = X86::SHL16ri; break;
3193       case MVT::i32: Opc = X86::SHL32ri; break;
3194       }
3195       Tmp1 = SelectExpr(N.getOperand(0));
3196       BuildMI(BB, Opc, 2, Result).addReg(Tmp1).addImm(CN->getValue());
3197       return Result;
3198     }
3199
3200     if (getRegPressure(N.getOperand(0)) > getRegPressure(N.getOperand(1))) {
3201       Tmp1 = SelectExpr(N.getOperand(0));
3202       Tmp2 = SelectExpr(N.getOperand(1));
3203     } else {
3204       Tmp2 = SelectExpr(N.getOperand(1));
3205       Tmp1 = SelectExpr(N.getOperand(0));
3206     }
3207
3208     switch (N.getValueType()) {
3209     default: assert(0 && "Cannot shift this type!");
3210     case MVT::i8 : Opc = X86::SHL8rCL; break;
3211     case MVT::i16: Opc = X86::SHL16rCL; break;
3212     case MVT::i32: Opc = X86::SHL32rCL; break;
3213     }
3214     BuildMI(BB, X86::MOV8rr, 1, X86::CL).addReg(Tmp2);
3215     BuildMI(BB, Opc, 1, Result).addReg(Tmp1);
3216     return Result;
3217   case ISD::SRL:
3218     if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N.getOperand(1))) {
3219       switch (N.getValueType()) {
3220       default: assert(0 && "Cannot shift this type!");
3221       case MVT::i8:  Opc = X86::SHR8ri; break;
3222       case MVT::i16: Opc = X86::SHR16ri; break;
3223       case MVT::i32: Opc = X86::SHR32ri; break;
3224       }
3225       Tmp1 = SelectExpr(N.getOperand(0));
3226       BuildMI(BB, Opc, 2, Result).addReg(Tmp1).addImm(CN->getValue());
3227       return Result;
3228     }
3229
3230     if (getRegPressure(N.getOperand(0)) > getRegPressure(N.getOperand(1))) {
3231       Tmp1 = SelectExpr(N.getOperand(0));
3232       Tmp2 = SelectExpr(N.getOperand(1));
3233     } else {
3234       Tmp2 = SelectExpr(N.getOperand(1));
3235       Tmp1 = SelectExpr(N.getOperand(0));
3236     }
3237
3238     switch (N.getValueType()) {
3239     default: assert(0 && "Cannot shift this type!");
3240     case MVT::i8 : Opc = X86::SHR8rCL; break;
3241     case MVT::i16: Opc = X86::SHR16rCL; break;
3242     case MVT::i32: Opc = X86::SHR32rCL; break;
3243     }
3244     BuildMI(BB, X86::MOV8rr, 1, X86::CL).addReg(Tmp2);
3245     BuildMI(BB, Opc, 1, Result).addReg(Tmp1);
3246     return Result;
3247   case ISD::SRA:
3248     if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N.getOperand(1))) {
3249       switch (N.getValueType()) {
3250       default: assert(0 && "Cannot shift this type!");
3251       case MVT::i8:  Opc = X86::SAR8ri; break;
3252       case MVT::i16: Opc = X86::SAR16ri; break;
3253       case MVT::i32: Opc = X86::SAR32ri; break;
3254       }
3255       Tmp1 = SelectExpr(N.getOperand(0));
3256       BuildMI(BB, Opc, 2, Result).addReg(Tmp1).addImm(CN->getValue());
3257       return Result;
3258     }
3259
3260     if (getRegPressure(N.getOperand(0)) > getRegPressure(N.getOperand(1))) {
3261       Tmp1 = SelectExpr(N.getOperand(0));
3262       Tmp2 = SelectExpr(N.getOperand(1));
3263     } else {
3264       Tmp2 = SelectExpr(N.getOperand(1));
3265       Tmp1 = SelectExpr(N.getOperand(0));
3266     }
3267
3268     switch (N.getValueType()) {
3269     default: assert(0 && "Cannot shift this type!");
3270     case MVT::i8 : Opc = X86::SAR8rCL; break;
3271     case MVT::i16: Opc = X86::SAR16rCL; break;
3272     case MVT::i32: Opc = X86::SAR32rCL; break;
3273     }
3274     BuildMI(BB, X86::MOV8rr, 1, X86::CL).addReg(Tmp2);
3275     BuildMI(BB, Opc, 1, Result).addReg(Tmp1);
3276     return Result;
3277
3278   case ISD::SETCC:
3279     EmitCMP(N.getOperand(0), N.getOperand(1), Node->hasOneUse());
3280     EmitSetCC(BB, Result, cast<CondCodeSDNode>(N.getOperand(2))->get(),
3281               MVT::isFloatingPoint(N.getOperand(1).getValueType()));
3282     return Result;
3283   case ISD::LOAD:
3284     // Make sure we generate both values.
3285     if (Result != 1) {  // Generate the token
3286       if (!ExprMap.insert(std::make_pair(N.getValue(1), 1)).second)
3287         assert(0 && "Load already emitted!?");
3288     } else
3289       Result = ExprMap[N.getValue(0)] = MakeReg(N.getValue(0).getValueType());
3290
3291     switch (Node->getValueType(0)) {
3292     default: assert(0 && "Cannot load this type!");
3293     case MVT::i1:
3294     case MVT::i8:  Opc = X86::MOV8rm; break;
3295     case MVT::i16: Opc = X86::MOV16rm; break;
3296     case MVT::i32: Opc = X86::MOV32rm; break;
3297     case MVT::f32: Opc = X86::MOVSSrm; break;
3298     case MVT::f64:
3299       if (X86ScalarSSE) {
3300         Opc = X86::MOVSDrm;
3301       } else {
3302         Opc = X86::FLD64m;
3303         ContainsFPCode = true;
3304       }
3305       break;
3306     }
3307
3308     if (ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(N.getOperand(1))){
3309       unsigned CPIdx = BB->getParent()->getConstantPool()->
3310          getConstantPoolIndex(CP->get());
3311       Select(N.getOperand(0));
3312       addConstantPoolReference(BuildMI(BB, Opc, 4, Result), CPIdx);
3313     } else {
3314       X86AddressMode AM;
3315
3316       SDOperand Chain   = N.getOperand(0);
3317       SDOperand Address = N.getOperand(1);
3318       if (getRegPressure(Chain) > getRegPressure(Address)) {
3319         Select(Chain);
3320         SelectAddress(Address, AM);
3321       } else {
3322         SelectAddress(Address, AM);
3323         Select(Chain);
3324       }
3325
3326       addFullAddress(BuildMI(BB, Opc, 4, Result), AM);
3327     }
3328     return Result;
3329   case X86ISD::FILD64m:
3330     // Make sure we generate both values.
3331     assert(Result != 1 && N.getValueType() == MVT::f64);
3332     if (!ExprMap.insert(std::make_pair(N.getValue(1), 1)).second)
3333       assert(0 && "Load already emitted!?");
3334
3335     {
3336       X86AddressMode AM;
3337
3338       SDOperand Chain   = N.getOperand(0);
3339       SDOperand Address = N.getOperand(1);
3340       if (getRegPressure(Chain) > getRegPressure(Address)) {
3341         Select(Chain);
3342         SelectAddress(Address, AM);
3343       } else {
3344         SelectAddress(Address, AM);
3345         Select(Chain);
3346       }
3347
3348       addFullAddress(BuildMI(BB, X86::FILD64m, 4, Result), AM);
3349     }
3350     return Result;
3351
3352   case ISD::EXTLOAD:          // Arbitrarily codegen extloads as MOVZX*
3353   case ISD::ZEXTLOAD: {
3354     // Make sure we generate both values.
3355     if (Result != 1)
3356       ExprMap[N.getValue(1)] = 1;   // Generate the token
3357     else
3358       Result = ExprMap[N.getValue(0)] = MakeReg(N.getValue(0).getValueType());
3359
3360     if (ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(N.getOperand(1)))
3361       if (Node->getValueType(0) == MVT::f64) {
3362         assert(cast<VTSDNode>(Node->getOperand(3))->getVT() == MVT::f32 &&
3363                "Bad EXTLOAD!");
3364         unsigned CPIdx = BB->getParent()->getConstantPool()->
3365           getConstantPoolIndex(CP->get());
3366
3367         addConstantPoolReference(BuildMI(BB, X86::FLD32m, 4, Result), CPIdx);
3368         return Result;
3369       }
3370
3371     X86AddressMode AM;
3372     if (getRegPressure(Node->getOperand(0)) >
3373            getRegPressure(Node->getOperand(1))) {
3374       Select(Node->getOperand(0)); // chain
3375       SelectAddress(Node->getOperand(1), AM);
3376     } else {
3377       SelectAddress(Node->getOperand(1), AM);
3378       Select(Node->getOperand(0)); // chain
3379     }
3380
3381     switch (Node->getValueType(0)) {
3382     default: assert(0 && "Unknown type to sign extend to.");
3383     case MVT::f64:
3384       assert(cast<VTSDNode>(Node->getOperand(3))->getVT() == MVT::f32 &&
3385              "Bad EXTLOAD!");
3386       addFullAddress(BuildMI(BB, X86::FLD32m, 5, Result), AM);
3387       break;
3388     case MVT::i32:
3389       switch (cast<VTSDNode>(Node->getOperand(3))->getVT()) {
3390       default:
3391         assert(0 && "Bad zero extend!");
3392       case MVT::i1:
3393       case MVT::i8:
3394         addFullAddress(BuildMI(BB, X86::MOVZX32rm8, 5, Result), AM);
3395         break;
3396       case MVT::i16:
3397         addFullAddress(BuildMI(BB, X86::MOVZX32rm16, 5, Result), AM);
3398         break;
3399       }
3400       break;
3401     case MVT::i16:
3402       assert(cast<VTSDNode>(Node->getOperand(3))->getVT() <= MVT::i8 &&
3403              "Bad zero extend!");
3404       addFullAddress(BuildMI(BB, X86::MOVSX16rm8, 5, Result), AM);
3405       break;
3406     case MVT::i8:
3407       assert(cast<VTSDNode>(Node->getOperand(3))->getVT() == MVT::i1 &&
3408              "Bad zero extend!");
3409       addFullAddress(BuildMI(BB, X86::MOV8rm, 5, Result), AM);
3410       break;
3411     }
3412     return Result;
3413   }
3414   case ISD::SEXTLOAD: {
3415     // Make sure we generate both values.
3416     if (Result != 1)
3417       ExprMap[N.getValue(1)] = 1;   // Generate the token
3418     else
3419       Result = ExprMap[N.getValue(0)] = MakeReg(N.getValue(0).getValueType());
3420
3421     X86AddressMode AM;
3422     if (getRegPressure(Node->getOperand(0)) >
3423            getRegPressure(Node->getOperand(1))) {
3424       Select(Node->getOperand(0)); // chain
3425       SelectAddress(Node->getOperand(1), AM);
3426     } else {
3427       SelectAddress(Node->getOperand(1), AM);
3428       Select(Node->getOperand(0)); // chain
3429     }
3430
3431     switch (Node->getValueType(0)) {
3432     case MVT::i8: assert(0 && "Cannot sign extend from bool!");
3433     default: assert(0 && "Unknown type to sign extend to.");
3434     case MVT::i32:
3435       switch (cast<VTSDNode>(Node->getOperand(3))->getVT()) {
3436       default:
3437       case MVT::i1: assert(0 && "Cannot sign extend from bool!");
3438       case MVT::i8:
3439         addFullAddress(BuildMI(BB, X86::MOVSX32rm8, 5, Result), AM);
3440         break;
3441       case MVT::i16:
3442         addFullAddress(BuildMI(BB, X86::MOVSX32rm16, 5, Result), AM);
3443         break;
3444       }
3445       break;
3446     case MVT::i16:
3447       assert(cast<VTSDNode>(Node->getOperand(3))->getVT() == MVT::i8 &&
3448              "Cannot sign extend from bool!");
3449       addFullAddress(BuildMI(BB, X86::MOVSX16rm8, 5, Result), AM);
3450       break;
3451     }
3452     return Result;
3453   }
3454
3455   case ISD::DYNAMIC_STACKALLOC:
3456     // Generate both result values.
3457     if (Result != 1)
3458       ExprMap[N.getValue(1)] = 1;   // Generate the token
3459     else
3460       Result = ExprMap[N.getValue(0)] = MakeReg(N.getValue(0).getValueType());
3461
3462     // FIXME: We are currently ignoring the requested alignment for handling
3463     // greater than the stack alignment.  This will need to be revisited at some
3464     // point.  Align = N.getOperand(2);
3465
3466     if (!isa<ConstantSDNode>(N.getOperand(2)) ||
3467         cast<ConstantSDNode>(N.getOperand(2))->getValue() != 0) {
3468       std::cerr << "Cannot allocate stack object with greater alignment than"
3469                 << " the stack alignment yet!";
3470       abort();
3471     }
3472
3473     if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N.getOperand(1))) {
3474       Select(N.getOperand(0));
3475       BuildMI(BB, X86::SUB32ri, 2, X86::ESP).addReg(X86::ESP)
3476         .addImm(CN->getValue());
3477     } else {
3478       if (getRegPressure(N.getOperand(0)) > getRegPressure(N.getOperand(1))) {
3479         Select(N.getOperand(0));
3480         Tmp1 = SelectExpr(N.getOperand(1));
3481       } else {
3482         Tmp1 = SelectExpr(N.getOperand(1));
3483         Select(N.getOperand(0));
3484       }
3485
3486       // Subtract size from stack pointer, thereby allocating some space.
3487       BuildMI(BB, X86::SUB32rr, 2, X86::ESP).addReg(X86::ESP).addReg(Tmp1);
3488     }
3489
3490     // Put a pointer to the space into the result register, by copying the stack
3491     // pointer.
3492     BuildMI(BB, X86::MOV32rr, 1, Result).addReg(X86::ESP);
3493     return Result;
3494
3495   case X86ISD::TAILCALL:
3496   case X86ISD::CALL: {
3497     // The chain for this call is now lowered.
3498     ExprMap.insert(std::make_pair(N.getValue(0), 1));
3499
3500     bool isDirect = isa<GlobalAddressSDNode>(N.getOperand(1)) ||
3501                     isa<ExternalSymbolSDNode>(N.getOperand(1));
3502     unsigned Callee = 0;
3503     if (isDirect) {
3504       Select(N.getOperand(0));
3505     } else {
3506       if (getRegPressure(N.getOperand(0)) > getRegPressure(N.getOperand(1))) {
3507         Select(N.getOperand(0));
3508         Callee = SelectExpr(N.getOperand(1));
3509       } else {
3510         Callee = SelectExpr(N.getOperand(1));
3511         Select(N.getOperand(0));
3512       }
3513     }
3514
3515     // If this call has values to pass in registers, do so now.
3516     if (Node->getNumOperands() > 4) {
3517       // The first value is passed in (a part of) EAX, the second in EDX.
3518       unsigned RegOp1 = SelectExpr(N.getOperand(4));
3519       unsigned RegOp2 =
3520         Node->getNumOperands() > 5 ? SelectExpr(N.getOperand(5)) : 0;
3521
3522       switch (N.getOperand(4).getValueType()) {
3523       default: assert(0 && "Bad thing to pass in regs");
3524       case MVT::i1:
3525       case MVT::i8:  BuildMI(BB, X86::MOV8rr , 1,X86::AL).addReg(RegOp1); break;
3526       case MVT::i16: BuildMI(BB, X86::MOV16rr, 1,X86::AX).addReg(RegOp1); break;
3527       case MVT::i32: BuildMI(BB, X86::MOV32rr, 1,X86::EAX).addReg(RegOp1);break;
3528       }
3529       if (RegOp2)
3530         switch (N.getOperand(5).getValueType()) {
3531         default: assert(0 && "Bad thing to pass in regs");
3532         case MVT::i1:
3533         case MVT::i8:
3534           BuildMI(BB, X86::MOV8rr , 1, X86::DL).addReg(RegOp2);
3535           break;
3536         case MVT::i16:
3537           BuildMI(BB, X86::MOV16rr, 1, X86::DX).addReg(RegOp2);
3538           break;
3539         case MVT::i32:
3540           BuildMI(BB, X86::MOV32rr, 1, X86::EDX).addReg(RegOp2);
3541           break;
3542         }
3543     }
3544
3545     if (GlobalAddressSDNode *GASD =
3546                dyn_cast<GlobalAddressSDNode>(N.getOperand(1))) {
3547       BuildMI(BB, X86::CALLpcrel32, 1).addGlobalAddress(GASD->getGlobal(),true);
3548     } else if (ExternalSymbolSDNode *ESSDN =
3549                dyn_cast<ExternalSymbolSDNode>(N.getOperand(1))) {
3550       BuildMI(BB, X86::CALLpcrel32,
3551               1).addExternalSymbol(ESSDN->getSymbol(), true);
3552     } else {
3553       if (getRegPressure(N.getOperand(0)) > getRegPressure(N.getOperand(1))) {
3554         Select(N.getOperand(0));
3555         Tmp1 = SelectExpr(N.getOperand(1));
3556       } else {
3557         Tmp1 = SelectExpr(N.getOperand(1));
3558         Select(N.getOperand(0));
3559       }
3560
3561       BuildMI(BB, X86::CALL32r, 1).addReg(Tmp1);
3562     }
3563
3564     // Get caller stack amount and amount the callee added to the stack pointer.
3565     Tmp1 = cast<ConstantSDNode>(N.getOperand(2))->getValue();
3566     Tmp2 = cast<ConstantSDNode>(N.getOperand(3))->getValue();
3567     BuildMI(BB, X86::ADJCALLSTACKUP, 2).addImm(Tmp1).addImm(Tmp2);
3568
3569     if (Node->getNumValues() != 1)
3570       switch (Node->getValueType(1)) {
3571       default: assert(0 && "Unknown value type for call result!");
3572       case MVT::Other: return 1;
3573       case MVT::i1:
3574       case MVT::i8:
3575         BuildMI(BB, X86::MOV8rr, 1, Result).addReg(X86::AL);
3576         break;
3577       case MVT::i16:
3578         BuildMI(BB, X86::MOV16rr, 1, Result).addReg(X86::AX);
3579         break;
3580       case MVT::i32:
3581         BuildMI(BB, X86::MOV32rr, 1, Result).addReg(X86::EAX);
3582         if (Node->getNumValues() == 3 && Node->getValueType(2) == MVT::i32)
3583           BuildMI(BB, X86::MOV32rr, 1, Result+1).addReg(X86::EDX);
3584         break;
3585       case MVT::f64:     // Floating-point return values live in %ST(0)
3586         if (X86ScalarSSE) {
3587           ContainsFPCode = true;
3588           BuildMI(BB, X86::FpGETRESULT, 1, X86::FP0);
3589
3590           unsigned Size = MVT::getSizeInBits(MVT::f64)/8;
3591           MachineFunction *F = BB->getParent();
3592           int FrameIdx = F->getFrameInfo()->CreateStackObject(Size, Size);
3593           addFrameReference(BuildMI(BB, X86::FST64m, 5), FrameIdx).addReg(X86::FP0);
3594           addFrameReference(BuildMI(BB, X86::MOVSDrm, 4, Result), FrameIdx);
3595           break;
3596         } else {
3597           ContainsFPCode = true;
3598           BuildMI(BB, X86::FpGETRESULT, 1, Result);
3599           break;
3600         }
3601       }
3602     return Result+N.ResNo-1;
3603   }
3604   case ISD::READPORT:
3605     // First, determine that the size of the operand falls within the acceptable
3606     // range for this architecture.
3607     //
3608     if (Node->getOperand(1).getValueType() != MVT::i16) {
3609       std::cerr << "llvm.readport: Address size is not 16 bits\n";
3610       exit(1);
3611     }
3612
3613     // Make sure we generate both values.
3614     if (Result != 1) {  // Generate the token
3615       if (!ExprMap.insert(std::make_pair(N.getValue(1), 1)).second)
3616         assert(0 && "readport already emitted!?");
3617     } else
3618       Result = ExprMap[N.getValue(0)] = MakeReg(N.getValue(0).getValueType());
3619
3620     Select(Node->getOperand(0));  // Select the chain.
3621
3622     // If the port is a single-byte constant, use the immediate form.
3623     if (ConstantSDNode *Port = dyn_cast<ConstantSDNode>(Node->getOperand(1)))
3624       if ((Port->getValue() & 255) == Port->getValue()) {
3625         switch (Node->getValueType(0)) {
3626         case MVT::i8:
3627           BuildMI(BB, X86::IN8ri, 1).addImm(Port->getValue());
3628           BuildMI(BB, X86::MOV8rr, 1, Result).addReg(X86::AL);
3629           return Result;
3630         case MVT::i16:
3631           BuildMI(BB, X86::IN16ri, 1).addImm(Port->getValue());
3632           BuildMI(BB, X86::MOV16rr, 1, Result).addReg(X86::AX);
3633           return Result;
3634         case MVT::i32:
3635           BuildMI(BB, X86::IN32ri, 1).addImm(Port->getValue());
3636           BuildMI(BB, X86::MOV32rr, 1, Result).addReg(X86::EAX);
3637           return Result;
3638         default: break;
3639         }
3640       }
3641
3642     // Now, move the I/O port address into the DX register and use the IN
3643     // instruction to get the input data.
3644     //
3645     Tmp1 = SelectExpr(Node->getOperand(1));
3646     BuildMI(BB, X86::MOV16rr, 1, X86::DX).addReg(Tmp1);
3647     switch (Node->getValueType(0)) {
3648     case MVT::i8:
3649       BuildMI(BB, X86::IN8rr, 0);
3650       BuildMI(BB, X86::MOV8rr, 1, Result).addReg(X86::AL);
3651       return Result;
3652     case MVT::i16:
3653       BuildMI(BB, X86::IN16rr, 0);
3654       BuildMI(BB, X86::MOV16rr, 1, Result).addReg(X86::AX);
3655       return Result;
3656     case MVT::i32:
3657       BuildMI(BB, X86::IN32rr, 0);
3658       BuildMI(BB, X86::MOV32rr, 1, Result).addReg(X86::EAX);
3659       return Result;
3660     default:
3661       std::cerr << "Cannot do input on this data type";
3662       exit(1);
3663     }
3664
3665   }
3666
3667   return 0;
3668 }
3669
3670 /// TryToFoldLoadOpStore - Given a store node, try to fold together a
3671 /// load/op/store instruction.  If successful return true.
3672 bool ISel::TryToFoldLoadOpStore(SDNode *Node) {
3673   assert(Node->getOpcode() == ISD::STORE && "Can only do this for stores!");
3674   SDOperand Chain  = Node->getOperand(0);
3675   SDOperand StVal  = Node->getOperand(1);
3676   SDOperand StPtr  = Node->getOperand(2);
3677
3678   // The chain has to be a load, the stored value must be an integer binary
3679   // operation with one use.
3680   if (!StVal.Val->hasOneUse() || StVal.Val->getNumOperands() != 2 ||
3681       MVT::isFloatingPoint(StVal.getValueType()))
3682     return false;
3683
3684   // Token chain must either be a factor node or the load to fold.
3685   if (Chain.getOpcode() != ISD::LOAD && Chain.getOpcode() != ISD::TokenFactor)
3686     return false;
3687
3688   SDOperand TheLoad;
3689
3690   // Check to see if there is a load from the same pointer that we're storing
3691   // to in either operand of the binop.
3692   if (StVal.getOperand(0).getOpcode() == ISD::LOAD &&
3693       StVal.getOperand(0).getOperand(1) == StPtr)
3694     TheLoad = StVal.getOperand(0);
3695   else if (StVal.getOperand(1).getOpcode() == ISD::LOAD &&
3696            StVal.getOperand(1).getOperand(1) == StPtr)
3697     TheLoad = StVal.getOperand(1);
3698   else
3699     return false;  // No matching load operand.
3700
3701   // We can only fold the load if there are no intervening side-effecting
3702   // operations.  This means that the store uses the load as its token chain, or
3703   // there are only token factor nodes in between the store and load.
3704   if (Chain != TheLoad.getValue(1)) {
3705     // Okay, the other option is that we have a store referring to (possibly
3706     // nested) token factor nodes.  For now, just try peeking through one level
3707     // of token factors to see if this is the case.
3708     bool ChainOk = false;
3709     if (Chain.getOpcode() == ISD::TokenFactor) {
3710       for (unsigned i = 0, e = Chain.getNumOperands(); i != e; ++i)
3711         if (Chain.getOperand(i) == TheLoad.getValue(1)) {
3712           ChainOk = true;
3713           break;
3714         }
3715     }
3716
3717     if (!ChainOk) return false;
3718   }
3719
3720   if (TheLoad.getOperand(1) != StPtr)
3721     return false;
3722
3723   // Make sure that one of the operands of the binop is the load, and that the
3724   // load folds into the binop.
3725   if (((StVal.getOperand(0) != TheLoad ||
3726         !isFoldableLoad(TheLoad, StVal.getOperand(1))) &&
3727        (StVal.getOperand(1) != TheLoad ||
3728         !isFoldableLoad(TheLoad, StVal.getOperand(0)))))
3729     return false;
3730
3731   // Finally, check to see if this is one of the ops we can handle!
3732   static const unsigned ADDTAB[] = {
3733     X86::ADD8mi, X86::ADD16mi, X86::ADD32mi,
3734     X86::ADD8mr, X86::ADD16mr, X86::ADD32mr,
3735   };
3736   static const unsigned SUBTAB[] = {
3737     X86::SUB8mi, X86::SUB16mi, X86::SUB32mi,
3738     X86::SUB8mr, X86::SUB16mr, X86::SUB32mr,
3739   };
3740   static const unsigned ANDTAB[] = {
3741     X86::AND8mi, X86::AND16mi, X86::AND32mi,
3742     X86::AND8mr, X86::AND16mr, X86::AND32mr,
3743   };
3744   static const unsigned ORTAB[] = {
3745     X86::OR8mi, X86::OR16mi, X86::OR32mi,
3746     X86::OR8mr, X86::OR16mr, X86::OR32mr,
3747   };
3748   static const unsigned XORTAB[] = {
3749     X86::XOR8mi, X86::XOR16mi, X86::XOR32mi,
3750     X86::XOR8mr, X86::XOR16mr, X86::XOR32mr,
3751   };
3752   static const unsigned SHLTAB[] = {
3753     X86::SHL8mi, X86::SHL16mi, X86::SHL32mi,
3754     /*Have to put the reg in CL*/0, 0, 0,
3755   };
3756   static const unsigned SARTAB[] = {
3757     X86::SAR8mi, X86::SAR16mi, X86::SAR32mi,
3758     /*Have to put the reg in CL*/0, 0, 0,
3759   };
3760   static const unsigned SHRTAB[] = {
3761     X86::SHR8mi, X86::SHR16mi, X86::SHR32mi,
3762     /*Have to put the reg in CL*/0, 0, 0,
3763   };
3764
3765   const unsigned *TabPtr = 0;
3766   switch (StVal.getOpcode()) {
3767   default:
3768     std::cerr << "CANNOT [mem] op= val: ";
3769     StVal.Val->dump(); std::cerr << "\n";
3770   case ISD::FMUL:
3771   case ISD::MUL:
3772   case ISD::FDIV:
3773   case ISD::SDIV:
3774   case ISD::UDIV:
3775   case ISD::FREM:
3776   case ISD::SREM:
3777   case ISD::UREM: return false;
3778
3779   case ISD::ADD: TabPtr = ADDTAB; break;
3780   case ISD::SUB: TabPtr = SUBTAB; break;
3781   case ISD::AND: TabPtr = ANDTAB; break;
3782   case ISD:: OR: TabPtr =  ORTAB; break;
3783   case ISD::XOR: TabPtr = XORTAB; break;
3784   case ISD::SHL: TabPtr = SHLTAB; break;
3785   case ISD::SRA: TabPtr = SARTAB; break;
3786   case ISD::SRL: TabPtr = SHRTAB; break;
3787   }
3788
3789   // Handle: [mem] op= CST
3790   SDOperand Op0 = StVal.getOperand(0);
3791   SDOperand Op1 = StVal.getOperand(1);
3792   unsigned Opc = 0;
3793   if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(Op1)) {
3794     switch (Op0.getValueType()) { // Use Op0's type because of shifts.
3795     default: break;
3796     case MVT::i1:
3797     case MVT::i8:  Opc = TabPtr[0]; break;
3798     case MVT::i16: Opc = TabPtr[1]; break;
3799     case MVT::i32: Opc = TabPtr[2]; break;
3800     }
3801
3802     if (Opc) {
3803       if (!ExprMap.insert(std::make_pair(TheLoad.getValue(1), 1)).second)
3804         assert(0 && "Already emitted?");
3805       Select(Chain);
3806
3807       X86AddressMode AM;
3808       if (getRegPressure(TheLoad.getOperand(0)) >
3809           getRegPressure(TheLoad.getOperand(1))) {
3810         Select(TheLoad.getOperand(0));
3811         SelectAddress(TheLoad.getOperand(1), AM);
3812       } else {
3813         SelectAddress(TheLoad.getOperand(1), AM);
3814         Select(TheLoad.getOperand(0));
3815       }
3816
3817       if (StVal.getOpcode() == ISD::ADD) {
3818         if (CN->getValue() == 1) {
3819           switch (Op0.getValueType()) {
3820           default: break;
3821           case MVT::i8:
3822             addFullAddress(BuildMI(BB, X86::INC8m, 4), AM);
3823             return true;
3824           case MVT::i16: Opc = TabPtr[1];
3825             addFullAddress(BuildMI(BB, X86::INC16m, 4), AM);
3826             return true;
3827           case MVT::i32: Opc = TabPtr[2];
3828             addFullAddress(BuildMI(BB, X86::INC32m, 4), AM);
3829             return true;
3830           }
3831         } else if (CN->getValue()+1 == 0) {   // [X] += -1 -> DEC [X]
3832           switch (Op0.getValueType()) {
3833           default: break;
3834           case MVT::i8:
3835             addFullAddress(BuildMI(BB, X86::DEC8m, 4), AM);
3836             return true;
3837           case MVT::i16: Opc = TabPtr[1];
3838             addFullAddress(BuildMI(BB, X86::DEC16m, 4), AM);
3839             return true;
3840           case MVT::i32: Opc = TabPtr[2];
3841             addFullAddress(BuildMI(BB, X86::DEC32m, 4), AM);
3842             return true;
3843           }
3844         }
3845       }
3846
3847       addFullAddress(BuildMI(BB, Opc, 4+1),AM).addImm(CN->getValue());
3848       return true;
3849     }
3850   }
3851
3852   // If we have [mem] = V op [mem], try to turn it into:
3853   // [mem] = [mem] op V.
3854   if (Op1 == TheLoad && 
3855       StVal.getOpcode() != ISD::SUB && StVal.getOpcode() != ISD::FSUB &&
3856       StVal.getOpcode() != ISD::SHL && StVal.getOpcode() != ISD::SRA &&
3857       StVal.getOpcode() != ISD::SRL)
3858     std::swap(Op0, Op1);
3859
3860   if (Op0 != TheLoad) return false;
3861
3862   switch (Op0.getValueType()) {
3863   default: return false;
3864   case MVT::i1:
3865   case MVT::i8:  Opc = TabPtr[3]; break;
3866   case MVT::i16: Opc = TabPtr[4]; break;
3867   case MVT::i32: Opc = TabPtr[5]; break;
3868   }
3869
3870   // Table entry doesn't exist?
3871   if (Opc == 0) return false;
3872
3873   if (!ExprMap.insert(std::make_pair(TheLoad.getValue(1), 1)).second)
3874     assert(0 && "Already emitted?");
3875   Select(Chain);
3876   Select(TheLoad.getOperand(0));
3877
3878   X86AddressMode AM;
3879   SelectAddress(TheLoad.getOperand(1), AM);
3880   unsigned Reg = SelectExpr(Op1);
3881   addFullAddress(BuildMI(BB, Opc, 4+1), AM).addReg(Reg);
3882   return true;
3883 }
3884
3885 /// If node is a ret(tailcall) node, emit the specified tail call and return
3886 /// true, otherwise return false.
3887 ///
3888 /// FIXME: This whole thing should be a post-legalize optimization pass which
3889 /// recognizes and transforms the dag.  We don't want the selection phase doing
3890 /// this stuff!!
3891 ///
3892 bool ISel::EmitPotentialTailCall(SDNode *RetNode) {
3893   assert(RetNode->getOpcode() == ISD::RET && "Not a return");
3894
3895   SDOperand Chain = RetNode->getOperand(0);
3896
3897   // If this is a token factor node where one operand is a call, dig into it.
3898   SDOperand TokFactor;
3899   unsigned TokFactorOperand = 0;
3900   if (Chain.getOpcode() == ISD::TokenFactor) {
3901     for (unsigned i = 0, e = Chain.getNumOperands(); i != e; ++i)
3902       if (Chain.getOperand(i).getOpcode() == ISD::CALLSEQ_END ||
3903           Chain.getOperand(i).getOpcode() == X86ISD::TAILCALL) {
3904         TokFactorOperand = i;
3905         TokFactor = Chain;
3906         Chain = Chain.getOperand(i);
3907         break;
3908       }
3909     if (TokFactor.Val == 0) return false;  // No call operand.
3910   }
3911
3912   // Skip the CALLSEQ_END node if present.
3913   if (Chain.getOpcode() == ISD::CALLSEQ_END)
3914     Chain = Chain.getOperand(0);
3915
3916   // Is a tailcall the last control operation that occurs before the return?
3917   if (Chain.getOpcode() != X86ISD::TAILCALL)
3918     return false;
3919
3920   // If we return a value, is it the value produced by the call?
3921   if (RetNode->getNumOperands() > 1) {
3922     // Not returning the ret val of the call?
3923     if (Chain.Val->getNumValues() == 1 ||
3924         RetNode->getOperand(1) != Chain.getValue(1))
3925       return false;
3926
3927     if (RetNode->getNumOperands() > 2) {
3928       if (Chain.Val->getNumValues() == 2 ||
3929           RetNode->getOperand(2) != Chain.getValue(2))
3930         return false;
3931     }
3932     assert(RetNode->getNumOperands() <= 3);
3933   }
3934
3935   // CalleeCallArgAmt - The total number of bytes used for the callee arg area.
3936   // For FastCC, this will always be > 0.
3937   unsigned CalleeCallArgAmt =
3938     cast<ConstantSDNode>(Chain.getOperand(2))->getValue();
3939
3940   // CalleeCallArgPopAmt - The number of bytes in the call area popped by the
3941   // callee.  For FastCC this will always be > 0, for CCC this is always 0.
3942   unsigned CalleeCallArgPopAmt =
3943     cast<ConstantSDNode>(Chain.getOperand(3))->getValue();
3944
3945   // There are several cases we can handle here.  First, if the caller and
3946   // callee are both CCC functions, we can tailcall if the callee takes <= the
3947   // number of argument bytes that the caller does.
3948   if (CalleeCallArgPopAmt == 0 &&                  // Callee is C CallingConv?
3949       X86Lowering.getBytesToPopOnReturn() == 0) {  // Caller is C CallingConv?
3950     // Check to see if caller arg area size >= callee arg area size.
3951     if (X86Lowering.getBytesCallerReserves() >= CalleeCallArgAmt) {
3952       //std::cerr << "CCC TAILCALL UNIMP!\n";
3953       // If TokFactor is non-null, emit all operands.
3954
3955       //EmitCCCToCCCTailCall(Chain.Val);
3956       //return true;
3957     }
3958     return false;
3959   }
3960
3961   // Second, if both are FastCC functions, we can always perform the tail call.
3962   if (CalleeCallArgPopAmt && X86Lowering.getBytesToPopOnReturn()) {
3963     // If TokFactor is non-null, emit all operands before the call.
3964     if (TokFactor.Val) {
3965       for (unsigned i = 0, e = TokFactor.getNumOperands(); i != e; ++i)
3966         if (i != TokFactorOperand)
3967           Select(TokFactor.getOperand(i));
3968     }
3969
3970     EmitFastCCToFastCCTailCall(Chain.Val);
3971     return true;
3972   }
3973
3974   // We don't support mixed calls, due to issues with alignment.  We could in
3975   // theory handle some mixed calls from CCC -> FastCC if the stack is properly
3976   // aligned (which depends on the number of arguments to the callee).  TODO.
3977   return false;
3978 }
3979
3980 static SDOperand GetAdjustedArgumentStores(SDOperand Chain, int Offset,
3981                                            SelectionDAG &DAG) {
3982   MVT::ValueType StoreVT;
3983   switch (Chain.getOpcode()) {
3984   default: assert(0 && "Unexpected node!");
3985   case ISD::CALLSEQ_START:
3986     // If we found the start of the call sequence, we're done.  We actually
3987     // strip off the CALLSEQ_START node, to avoid generating the
3988     // ADJCALLSTACKDOWN marker for the tail call.
3989     return Chain.getOperand(0);
3990   case ISD::TokenFactor: {
3991     std::vector<SDOperand> Ops;
3992     Ops.reserve(Chain.getNumOperands());
3993     for (unsigned i = 0, e = Chain.getNumOperands(); i != e; ++i)
3994       Ops.push_back(GetAdjustedArgumentStores(Chain.getOperand(i), Offset,DAG));
3995     return DAG.getNode(ISD::TokenFactor, MVT::Other, Ops);
3996   }
3997   case ISD::STORE:       // Normal store
3998     StoreVT = Chain.getOperand(1).getValueType();
3999     break;
4000   case ISD::TRUNCSTORE:  // FLOAT store
4001     StoreVT = cast<VTSDNode>(Chain.getOperand(4))->getVT();
4002     break;
4003   }
4004
4005   SDOperand OrigDest = Chain.getOperand(2);
4006   unsigned OrigOffset;
4007
4008   if (OrigDest.getOpcode() == ISD::CopyFromReg) {
4009     OrigOffset = 0;
4010     assert(cast<RegisterSDNode>(OrigDest.getOperand(1))->getReg() == X86::ESP);
4011   } else {
4012     // We expect only (ESP+C)
4013     assert(OrigDest.getOpcode() == ISD::ADD &&
4014            isa<ConstantSDNode>(OrigDest.getOperand(1)) &&
4015            OrigDest.getOperand(0).getOpcode() == ISD::CopyFromReg &&
4016            cast<RegisterSDNode>(OrigDest.getOperand(0).getOperand(1))->getReg()
4017                  == X86::ESP);
4018     OrigOffset = cast<ConstantSDNode>(OrigDest.getOperand(1))->getValue();
4019   }
4020
4021   // Compute the new offset from the incoming ESP value we wish to use.
4022   unsigned NewOffset = OrigOffset + Offset;
4023
4024   unsigned OpSize = (MVT::getSizeInBits(StoreVT)+7)/8;  // Bits -> Bytes
4025   MachineFunction &MF = DAG.getMachineFunction();
4026   int FI = MF.getFrameInfo()->CreateFixedObject(OpSize, NewOffset);
4027   SDOperand FIN = DAG.getFrameIndex(FI, MVT::i32);
4028
4029   SDOperand InChain = GetAdjustedArgumentStores(Chain.getOperand(0), Offset,
4030                                                 DAG);
4031   if (Chain.getOpcode() == ISD::STORE)
4032     return DAG.getNode(ISD::STORE, MVT::Other, InChain, Chain.getOperand(1),
4033                        FIN);
4034   assert(Chain.getOpcode() == ISD::TRUNCSTORE);
4035   return DAG.getNode(ISD::TRUNCSTORE, MVT::Other, InChain, Chain.getOperand(1),
4036                      FIN, DAG.getSrcValue(NULL), DAG.getValueType(StoreVT));
4037 }
4038
4039
4040 /// EmitFastCCToFastCCTailCall - Given a tailcall in the tail position to a
4041 /// fastcc function from a fastcc function, emit the code to emit a 'proper'
4042 /// tail call.
4043 void ISel::EmitFastCCToFastCCTailCall(SDNode *TailCallNode) {
4044   unsigned CalleeCallArgSize =
4045     cast<ConstantSDNode>(TailCallNode->getOperand(2))->getValue();
4046   unsigned CallerArgSize = X86Lowering.getBytesToPopOnReturn();
4047
4048   //std::cerr << "****\n*** EMITTING TAIL CALL!\n****\n";
4049
4050   // Adjust argument stores.  Instead of storing to [ESP], f.e., store to frame
4051   // indexes that are relative to the incoming ESP.  If the incoming and
4052   // outgoing arg sizes are the same we will store to [InESP] instead of
4053   // [CurESP] and the ESP referenced will be relative to the incoming function
4054   // ESP.
4055   int ESPOffset = CallerArgSize-CalleeCallArgSize;
4056   SDOperand AdjustedArgStores =
4057     GetAdjustedArgumentStores(TailCallNode->getOperand(0), ESPOffset, *TheDAG);
4058
4059   // Copy the return address of the caller into a virtual register so we don't
4060   // clobber it.
4061   SDOperand RetVal;
4062   if (ESPOffset) {
4063     SDOperand RetValAddr = X86Lowering.getReturnAddressFrameIndex(*TheDAG);
4064     RetVal = TheDAG->getLoad(MVT::i32, TheDAG->getEntryNode(),
4065                                        RetValAddr, TheDAG->getSrcValue(NULL));
4066     SelectExpr(RetVal);
4067   }
4068
4069   // Codegen all of the argument stores.
4070   Select(AdjustedArgStores);
4071
4072   if (RetVal.Val) {
4073     // Emit a store of the saved ret value to the new location.
4074     MachineFunction &MF = TheDAG->getMachineFunction();
4075     int ReturnAddrFI = MF.getFrameInfo()->CreateFixedObject(4, ESPOffset-4);
4076     SDOperand RetValAddr = TheDAG->getFrameIndex(ReturnAddrFI, MVT::i32);
4077     Select(TheDAG->getNode(ISD::STORE, MVT::Other, TheDAG->getEntryNode(),
4078                            RetVal, RetValAddr));
4079   }
4080
4081   // Get the destination value.
4082   SDOperand Callee = TailCallNode->getOperand(1);
4083   bool isDirect = isa<GlobalAddressSDNode>(Callee) ||
4084                   isa<ExternalSymbolSDNode>(Callee);
4085   unsigned CalleeReg = 0;
4086   if (!isDirect) CalleeReg = SelectExpr(Callee);
4087
4088   unsigned RegOp1 = 0;
4089   unsigned RegOp2 = 0;
4090
4091   if (TailCallNode->getNumOperands() > 4) {
4092     // The first value is passed in (a part of) EAX, the second in EDX.
4093     RegOp1 = SelectExpr(TailCallNode->getOperand(4));
4094     if (TailCallNode->getNumOperands() > 5)
4095       RegOp2 = SelectExpr(TailCallNode->getOperand(5));
4096
4097     switch (TailCallNode->getOperand(4).getValueType()) {
4098     default: assert(0 && "Bad thing to pass in regs");
4099     case MVT::i1:
4100     case MVT::i8:
4101       BuildMI(BB, X86::MOV8rr, 1, X86::AL).addReg(RegOp1);
4102       RegOp1 = X86::AL;
4103       break;
4104     case MVT::i16:
4105       BuildMI(BB, X86::MOV16rr, 1,X86::AX).addReg(RegOp1);
4106       RegOp1 = X86::AX;
4107       break;
4108     case MVT::i32:
4109       BuildMI(BB, X86::MOV32rr, 1,X86::EAX).addReg(RegOp1);
4110       RegOp1 = X86::EAX;
4111       break;
4112     }
4113     if (RegOp2)
4114       switch (TailCallNode->getOperand(5).getValueType()) {
4115       default: assert(0 && "Bad thing to pass in regs");
4116       case MVT::i1:
4117       case MVT::i8:
4118         BuildMI(BB, X86::MOV8rr, 1, X86::DL).addReg(RegOp2);
4119         RegOp2 = X86::DL;
4120         break;
4121       case MVT::i16:
4122         BuildMI(BB, X86::MOV16rr, 1, X86::DX).addReg(RegOp2);
4123         RegOp2 = X86::DX;
4124         break;
4125       case MVT::i32:
4126         BuildMI(BB, X86::MOV32rr, 1, X86::EDX).addReg(RegOp2);
4127         RegOp2 = X86::EDX;
4128         break;
4129       }
4130   }
4131
4132   // Adjust ESP.
4133   if (ESPOffset)
4134     BuildMI(BB, X86::ADJSTACKPTRri, 2,
4135             X86::ESP).addReg(X86::ESP).addImm(ESPOffset);
4136
4137   // TODO: handle jmp [mem]
4138   if (!isDirect) {
4139     BuildMI(BB, X86::TAILJMPr, 1).addReg(CalleeReg);
4140   } else if (GlobalAddressSDNode *GASD = dyn_cast<GlobalAddressSDNode>(Callee)){
4141     BuildMI(BB, X86::TAILJMPd, 1).addGlobalAddress(GASD->getGlobal(), true);
4142   } else {
4143     ExternalSymbolSDNode *ESSDN = cast<ExternalSymbolSDNode>(Callee);
4144     BuildMI(BB, X86::TAILJMPd, 1).addExternalSymbol(ESSDN->getSymbol(), true);
4145   }
4146   // ADD IMPLICIT USE RegOp1/RegOp2's
4147 }
4148
4149
4150 void ISel::Select(SDOperand N) {
4151   unsigned Tmp1, Tmp2, Opc;
4152
4153   if (!ExprMap.insert(std::make_pair(N, 1)).second)
4154     return;  // Already selected.
4155
4156   SDNode *Node = N.Val;
4157
4158   switch (Node->getOpcode()) {
4159   default:
4160     Node->dump(); std::cerr << "\n";
4161     assert(0 && "Node not handled yet!");
4162   case ISD::EntryToken: return;  // Noop
4163   case ISD::TokenFactor:
4164     if (Node->getNumOperands() == 2) {
4165       bool OneFirst =
4166         getRegPressure(Node->getOperand(1))>getRegPressure(Node->getOperand(0));
4167       Select(Node->getOperand(OneFirst));
4168       Select(Node->getOperand(!OneFirst));
4169     } else {
4170       std::vector<std::pair<unsigned, unsigned> > OpsP;
4171       for (unsigned i = 0, e = Node->getNumOperands(); i != e; ++i)
4172         OpsP.push_back(std::make_pair(getRegPressure(Node->getOperand(i)), i));
4173       std::sort(OpsP.begin(), OpsP.end());
4174       std::reverse(OpsP.begin(), OpsP.end());
4175       for (unsigned i = 0, e = Node->getNumOperands(); i != e; ++i)
4176         Select(Node->getOperand(OpsP[i].second));
4177     }
4178     return;
4179   case ISD::CopyToReg:
4180     if (getRegPressure(N.getOperand(0)) > getRegPressure(N.getOperand(2))) {
4181       Select(N.getOperand(0));
4182       Tmp1 = SelectExpr(N.getOperand(2));
4183     } else {
4184       Tmp1 = SelectExpr(N.getOperand(2));
4185       Select(N.getOperand(0));
4186     }
4187     Tmp2 = cast<RegisterSDNode>(N.getOperand(1))->getReg();
4188
4189     if (Tmp1 != Tmp2) {
4190       switch (N.getOperand(2).getValueType()) {
4191       default: assert(0 && "Invalid type for operation!");
4192       case MVT::i1:
4193       case MVT::i8:  Opc = X86::MOV8rr; break;
4194       case MVT::i16: Opc = X86::MOV16rr; break;
4195       case MVT::i32: Opc = X86::MOV32rr; break;
4196       case MVT::f32: Opc = X86::MOVAPSrr; break;
4197       case MVT::f64:
4198         if (X86ScalarSSE) {
4199           Opc = X86::MOVAPDrr;
4200         } else {
4201           Opc = X86::FpMOV;
4202           ContainsFPCode = true;
4203         }
4204         break;
4205       }
4206       BuildMI(BB, Opc, 1, Tmp2).addReg(Tmp1);
4207     }
4208     return;
4209   case ISD::RET:
4210     if (N.getOperand(0).getOpcode() == ISD::CALLSEQ_END ||
4211         N.getOperand(0).getOpcode() == X86ISD::TAILCALL ||
4212         N.getOperand(0).getOpcode() == ISD::TokenFactor)
4213       if (EmitPotentialTailCall(Node))
4214         return;
4215
4216     switch (N.getNumOperands()) {
4217     default:
4218       assert(0 && "Unknown return instruction!");
4219     case 3:
4220       assert(N.getOperand(1).getValueType() == MVT::i32 &&
4221              N.getOperand(2).getValueType() == MVT::i32 &&
4222              "Unknown two-register value!");
4223       if (getRegPressure(N.getOperand(1)) > getRegPressure(N.getOperand(2))) {
4224         Tmp1 = SelectExpr(N.getOperand(1));
4225         Tmp2 = SelectExpr(N.getOperand(2));
4226       } else {
4227         Tmp2 = SelectExpr(N.getOperand(2));
4228         Tmp1 = SelectExpr(N.getOperand(1));
4229       }
4230       Select(N.getOperand(0));
4231
4232       BuildMI(BB, X86::MOV32rr, 1, X86::EAX).addReg(Tmp1);
4233       BuildMI(BB, X86::MOV32rr, 1, X86::EDX).addReg(Tmp2);
4234       break;
4235     case 2:
4236       if (getRegPressure(N.getOperand(0)) > getRegPressure(N.getOperand(1))) {
4237         Select(N.getOperand(0));
4238         Tmp1 = SelectExpr(N.getOperand(1));
4239       } else {
4240         Tmp1 = SelectExpr(N.getOperand(1));
4241         Select(N.getOperand(0));
4242       }
4243       switch (N.getOperand(1).getValueType()) {
4244       default: assert(0 && "All other types should have been promoted!!");
4245       case MVT::f32:
4246         if (X86ScalarSSE) {
4247           // Spill the value to memory and reload it into top of stack.
4248           unsigned Size = MVT::getSizeInBits(MVT::f32)/8;
4249           MachineFunction *F = BB->getParent();
4250           int FrameIdx = F->getFrameInfo()->CreateStackObject(Size, Size);
4251           addFrameReference(BuildMI(BB, X86::MOVSSmr, 5), FrameIdx).addReg(Tmp1);
4252           addFrameReference(BuildMI(BB, X86::FLD32m, 4, X86::FP0), FrameIdx);
4253           BuildMI(BB, X86::FpSETRESULT, 1).addReg(X86::FP0);
4254           ContainsFPCode = true;
4255         } else {
4256           assert(0 && "MVT::f32 only legal with scalar sse fp");
4257           abort();
4258         }
4259         break;
4260       case MVT::f64:
4261         if (X86ScalarSSE) {
4262           // Spill the value to memory and reload it into top of stack.
4263           unsigned Size = MVT::getSizeInBits(MVT::f64)/8;
4264           MachineFunction *F = BB->getParent();
4265           int FrameIdx = F->getFrameInfo()->CreateStackObject(Size, Size);
4266           addFrameReference(BuildMI(BB, X86::MOVSDmr, 5), FrameIdx).addReg(Tmp1);
4267           addFrameReference(BuildMI(BB, X86::FLD64m, 4, X86::FP0), FrameIdx);
4268           BuildMI(BB, X86::FpSETRESULT, 1).addReg(X86::FP0);
4269           ContainsFPCode = true;
4270         } else {
4271           BuildMI(BB, X86::FpSETRESULT, 1).addReg(Tmp1);
4272         }
4273         break;
4274       case MVT::i32:
4275         BuildMI(BB, X86::MOV32rr, 1, X86::EAX).addReg(Tmp1);
4276         break;
4277       }
4278       break;
4279     case 1:
4280       Select(N.getOperand(0));
4281       break;
4282     }
4283     if (X86Lowering.getBytesToPopOnReturn() == 0)
4284       BuildMI(BB, X86::RET, 0); // Just emit a 'ret' instruction
4285     else
4286       BuildMI(BB, X86::RETI, 1).addImm(X86Lowering.getBytesToPopOnReturn());
4287     return;
4288   case ISD::BR: {
4289     Select(N.getOperand(0));
4290     MachineBasicBlock *Dest =
4291       cast<BasicBlockSDNode>(N.getOperand(1))->getBasicBlock();
4292     BuildMI(BB, X86::JMP, 1).addMBB(Dest);
4293     return;
4294   }
4295
4296   case ISD::BRCOND: {
4297     MachineBasicBlock *Dest =
4298       cast<BasicBlockSDNode>(N.getOperand(2))->getBasicBlock();
4299
4300     // Try to fold a setcc into the branch.  If this fails, emit a test/jne
4301     // pair.
4302     if (EmitBranchCC(Dest, N.getOperand(0), N.getOperand(1))) {
4303       if (getRegPressure(N.getOperand(0)) > getRegPressure(N.getOperand(1))) {
4304         Select(N.getOperand(0));
4305         Tmp1 = SelectExpr(N.getOperand(1));
4306       } else {
4307         Tmp1 = SelectExpr(N.getOperand(1));
4308         Select(N.getOperand(0));
4309       }
4310       BuildMI(BB, X86::TEST8rr, 2).addReg(Tmp1).addReg(Tmp1);
4311       BuildMI(BB, X86::JNE, 1).addMBB(Dest);
4312     }
4313
4314     return;
4315   }
4316
4317   case ISD::LOAD:
4318     // If this load could be folded into the only using instruction, and if it
4319     // is safe to emit the instruction here, try to do so now.
4320     if (Node->hasNUsesOfValue(1, 0)) {
4321       SDOperand TheVal = N.getValue(0);
4322       SDNode *User = 0;
4323       for (SDNode::use_iterator UI = Node->use_begin(); ; ++UI) {
4324         assert(UI != Node->use_end() && "Didn't find use!");
4325         SDNode *UN = *UI;
4326         for (unsigned i = 0, e = UN->getNumOperands(); i != e; ++i)
4327           if (UN->getOperand(i) == TheVal) {
4328             User = UN;
4329             goto FoundIt;
4330           }
4331       }
4332     FoundIt:
4333       // Only handle unary operators right now.
4334       if (User->getNumOperands() == 1) {
4335         ExprMap.erase(N);
4336         SelectExpr(SDOperand(User, 0));
4337         return;
4338       }
4339     }
4340     ExprMap.erase(N);
4341     SelectExpr(N);
4342     return;
4343   case ISD::READPORT:
4344   case ISD::EXTLOAD:
4345   case ISD::SEXTLOAD:
4346   case ISD::ZEXTLOAD:
4347   case ISD::DYNAMIC_STACKALLOC:
4348   case X86ISD::TAILCALL:
4349   case X86ISD::CALL:
4350     ExprMap.erase(N);
4351     SelectExpr(N);
4352     return;
4353   case ISD::CopyFromReg:
4354   case X86ISD::FILD64m:
4355     ExprMap.erase(N);
4356     SelectExpr(N.getValue(0));
4357     return;
4358
4359   case X86ISD::FP_TO_INT16_IN_MEM:
4360   case X86ISD::FP_TO_INT32_IN_MEM:
4361   case X86ISD::FP_TO_INT64_IN_MEM: {
4362     assert(N.getOperand(1).getValueType() == MVT::f64);
4363     X86AddressMode AM;
4364     Select(N.getOperand(0));   // Select the token chain
4365
4366     unsigned ValReg;
4367     if (getRegPressure(N.getOperand(1)) > getRegPressure(N.getOperand(2))) {
4368       ValReg = SelectExpr(N.getOperand(1));
4369       SelectAddress(N.getOperand(2), AM);
4370      } else {
4371        SelectAddress(N.getOperand(2), AM);
4372        ValReg = SelectExpr(N.getOperand(1));
4373      }
4374
4375     // Change the floating point control register to use "round towards zero"
4376     // mode when truncating to an integer value.
4377     //
4378     MachineFunction *F = BB->getParent();
4379     int CWFrameIdx = F->getFrameInfo()->CreateStackObject(2, 2);
4380     addFrameReference(BuildMI(BB, X86::FNSTCW16m, 4), CWFrameIdx);
4381
4382     // Load the old value of the high byte of the control word...
4383     unsigned OldCW = MakeReg(MVT::i16);
4384     addFrameReference(BuildMI(BB, X86::MOV16rm, 4, OldCW), CWFrameIdx);
4385
4386     // Set the high part to be round to zero...
4387     addFrameReference(BuildMI(BB, X86::MOV16mi, 5), CWFrameIdx).addImm(0xC7F);
4388
4389     // Reload the modified control word now...
4390     addFrameReference(BuildMI(BB, X86::FLDCW16m, 4), CWFrameIdx);
4391
4392     // Restore the memory image of control word to original value
4393     addFrameReference(BuildMI(BB, X86::MOV16mr, 5), CWFrameIdx).addReg(OldCW);
4394
4395     // Get the X86 opcode to use.
4396     switch (N.getOpcode()) {
4397     case X86ISD::FP_TO_INT16_IN_MEM: Tmp1 = X86::FIST16m; break;
4398     case X86ISD::FP_TO_INT32_IN_MEM: Tmp1 = X86::FIST32m; break;
4399     case X86ISD::FP_TO_INT64_IN_MEM: Tmp1 = X86::FISTP64m; break;
4400     }
4401
4402     addFullAddress(BuildMI(BB, Tmp1, 5), AM).addReg(ValReg);
4403
4404     // Reload the original control word now.
4405     addFrameReference(BuildMI(BB, X86::FLDCW16m, 4), CWFrameIdx);
4406     return;
4407   }
4408
4409   case ISD::TRUNCSTORE: {  // truncstore chain, val, ptr, SRCVALUE, storety
4410     X86AddressMode AM;
4411     MVT::ValueType StoredTy = cast<VTSDNode>(N.getOperand(4))->getVT();
4412     assert((StoredTy == MVT::i1 || StoredTy == MVT::f32 ||
4413             StoredTy == MVT::i16 /*FIXME: THIS IS JUST FOR TESTING!*/)
4414            && "Unsupported TRUNCSTORE for this target!");
4415
4416     if (StoredTy == MVT::i16) {
4417       // FIXME: This is here just to allow testing.  X86 doesn't really have a
4418       // TRUNCSTORE i16 operation, but this is required for targets that do not
4419       // have 16-bit integer registers.  We occasionally disable 16-bit integer
4420       // registers to test the promotion code.
4421       Select(N.getOperand(0));
4422       Tmp1 = SelectExpr(N.getOperand(1));
4423       SelectAddress(N.getOperand(2), AM);
4424
4425       BuildMI(BB, X86::MOV32rr, 1, X86::EAX).addReg(Tmp1);
4426       addFullAddress(BuildMI(BB, X86::MOV16mr, 5), AM).addReg(X86::AX);
4427       return;
4428     }
4429
4430     // Store of constant bool?
4431     if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N.getOperand(1))) {
4432       if (getRegPressure(N.getOperand(0)) > getRegPressure(N.getOperand(2))) {
4433         Select(N.getOperand(0));
4434         SelectAddress(N.getOperand(2), AM);
4435       } else {
4436         SelectAddress(N.getOperand(2), AM);
4437         Select(N.getOperand(0));
4438       }
4439       addFullAddress(BuildMI(BB, X86::MOV8mi, 5), AM).addImm(CN->getValue());
4440       return;
4441     }
4442
4443     switch (StoredTy) {
4444     default: assert(0 && "Cannot truncstore this type!");
4445     case MVT::i1: Opc = X86::MOV8mr; break;
4446     case MVT::f32:
4447       assert(!X86ScalarSSE && "Cannot truncstore scalar SSE regs");
4448       Opc = X86::FST32m; break;
4449     }
4450
4451     std::vector<std::pair<unsigned, unsigned> > RP;
4452     RP.push_back(std::make_pair(getRegPressure(N.getOperand(0)), 0));
4453     RP.push_back(std::make_pair(getRegPressure(N.getOperand(1)), 1));
4454     RP.push_back(std::make_pair(getRegPressure(N.getOperand(2)), 2));
4455     std::sort(RP.begin(), RP.end());
4456
4457     Tmp1 = 0;   // Silence a warning.
4458     for (unsigned i = 0; i != 3; ++i)
4459       switch (RP[2-i].second) {
4460       default: assert(0 && "Unknown operand number!");
4461       case 0: Select(N.getOperand(0)); break;
4462       case 1: Tmp1 = SelectExpr(N.getOperand(1)); break;
4463       case 2: SelectAddress(N.getOperand(2), AM); break;
4464       }
4465
4466     addFullAddress(BuildMI(BB, Opc, 4+1), AM).addReg(Tmp1);
4467     return;
4468   }
4469   case ISD::STORE: {
4470     X86AddressMode AM;
4471
4472     if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N.getOperand(1))) {
4473       Opc = 0;
4474       switch (CN->getValueType(0)) {
4475       default: assert(0 && "Invalid type for operation!");
4476       case MVT::i1:
4477       case MVT::i8:  Opc = X86::MOV8mi; break;
4478       case MVT::i16: Opc = X86::MOV16mi; break;
4479       case MVT::i32: Opc = X86::MOV32mi; break;
4480       }
4481       if (Opc) {
4482         if (getRegPressure(N.getOperand(0)) > getRegPressure(N.getOperand(2))) {
4483           Select(N.getOperand(0));
4484           SelectAddress(N.getOperand(2), AM);
4485         } else {
4486           SelectAddress(N.getOperand(2), AM);
4487           Select(N.getOperand(0));
4488         }
4489         addFullAddress(BuildMI(BB, Opc, 4+1), AM).addImm(CN->getValue());
4490         return;
4491       }
4492     } else if (GlobalAddressSDNode *GA =
4493                       dyn_cast<GlobalAddressSDNode>(N.getOperand(1))) {
4494       assert(GA->getValueType(0) == MVT::i32 && "Bad pointer operand");
4495
4496       if (getRegPressure(N.getOperand(0)) > getRegPressure(N.getOperand(2))) {
4497         Select(N.getOperand(0));
4498         SelectAddress(N.getOperand(2), AM);
4499       } else {
4500         SelectAddress(N.getOperand(2), AM);
4501         Select(N.getOperand(0));
4502       }
4503       GlobalValue *GV = GA->getGlobal();
4504       // For Darwin, external and weak symbols are indirect, so we want to load
4505       // the value at address GV, not the value of GV itself.
4506       if (Subtarget->getIndirectExternAndWeakGlobals() &&
4507           (GV->hasWeakLinkage() || GV->isExternal())) {
4508         Tmp1 = MakeReg(MVT::i32);
4509         BuildMI(BB, X86::MOV32rm, 4, Tmp1).addReg(0).addZImm(1).addReg(0)
4510           .addGlobalAddress(GV, false, 0);
4511         addFullAddress(BuildMI(BB, X86::MOV32mr, 4+1),AM).addReg(Tmp1);
4512       } else {
4513         addFullAddress(BuildMI(BB, X86::MOV32mi, 4+1),AM).addGlobalAddress(GV);
4514       }
4515       return;
4516     }
4517
4518     // Check to see if this is a load/op/store combination.
4519     if (TryToFoldLoadOpStore(Node))
4520       return;
4521
4522     switch (N.getOperand(1).getValueType()) {
4523     default: assert(0 && "Cannot store this type!");
4524     case MVT::i1:
4525     case MVT::i8:  Opc = X86::MOV8mr; break;
4526     case MVT::i16: Opc = X86::MOV16mr; break;
4527     case MVT::i32: Opc = X86::MOV32mr; break;
4528     case MVT::f32: Opc = X86::MOVSSmr; break;
4529     case MVT::f64: Opc = X86ScalarSSE ? X86::MOVSDmr : X86::FST64m; break;
4530     }
4531
4532     std::vector<std::pair<unsigned, unsigned> > RP;
4533     RP.push_back(std::make_pair(getRegPressure(N.getOperand(0)), 0));
4534     RP.push_back(std::make_pair(getRegPressure(N.getOperand(1)), 1));
4535     RP.push_back(std::make_pair(getRegPressure(N.getOperand(2)), 2));
4536     std::sort(RP.begin(), RP.end());
4537
4538     Tmp1 = 0; // Silence a warning.
4539     for (unsigned i = 0; i != 3; ++i)
4540       switch (RP[2-i].second) {
4541       default: assert(0 && "Unknown operand number!");
4542       case 0: Select(N.getOperand(0)); break;
4543       case 1: Tmp1 = SelectExpr(N.getOperand(1)); break;
4544       case 2: SelectAddress(N.getOperand(2), AM); break;
4545       }
4546
4547     addFullAddress(BuildMI(BB, Opc, 4+1), AM).addReg(Tmp1);
4548     return;
4549   }
4550   case ISD::CALLSEQ_START:
4551     Select(N.getOperand(0));
4552     // Stack amount
4553     Tmp1 = cast<ConstantSDNode>(N.getOperand(1))->getValue();
4554     BuildMI(BB, X86::ADJCALLSTACKDOWN, 1).addImm(Tmp1);
4555     return;
4556   case ISD::CALLSEQ_END:
4557     Select(N.getOperand(0));
4558     return;
4559   case ISD::MEMSET: {
4560     Select(N.getOperand(0));  // Select the chain.
4561     unsigned Align =
4562       (unsigned)cast<ConstantSDNode>(Node->getOperand(4))->getValue();
4563     if (Align == 0) Align = 1;
4564
4565     // Turn the byte code into # iterations
4566     unsigned CountReg;
4567     unsigned Opcode;
4568     if (ConstantSDNode *ValC = dyn_cast<ConstantSDNode>(Node->getOperand(2))) {
4569       unsigned Val = ValC->getValue() & 255;
4570
4571       // If the value is a constant, then we can potentially use larger sets.
4572       switch (Align & 3) {
4573       case 2:   // WORD aligned
4574         CountReg = MakeReg(MVT::i32);
4575         if (ConstantSDNode *I = dyn_cast<ConstantSDNode>(Node->getOperand(3))) {
4576           BuildMI(BB, X86::MOV32ri, 1, CountReg).addImm(I->getValue()/2);
4577         } else {
4578           unsigned ByteReg = SelectExpr(Node->getOperand(3));
4579           BuildMI(BB, X86::SHR32ri, 2, CountReg).addReg(ByteReg).addImm(1);
4580         }
4581         BuildMI(BB, X86::MOV16ri, 1, X86::AX).addImm((Val << 8) | Val);
4582         Opcode = X86::REP_STOSW;
4583         break;
4584       case 0:   // DWORD aligned
4585         CountReg = MakeReg(MVT::i32);
4586         if (ConstantSDNode *I = dyn_cast<ConstantSDNode>(Node->getOperand(3))) {
4587           BuildMI(BB, X86::MOV32ri, 1, CountReg).addImm(I->getValue()/4);
4588         } else {
4589           unsigned ByteReg = SelectExpr(Node->getOperand(3));
4590           BuildMI(BB, X86::SHR32ri, 2, CountReg).addReg(ByteReg).addImm(2);
4591         }
4592         Val = (Val << 8) | Val;
4593         BuildMI(BB, X86::MOV32ri, 1, X86::EAX).addImm((Val << 16) | Val);
4594         Opcode = X86::REP_STOSD;
4595         break;
4596       default:  // BYTE aligned
4597         CountReg = SelectExpr(Node->getOperand(3));
4598         BuildMI(BB, X86::MOV8ri, 1, X86::AL).addImm(Val);
4599         Opcode = X86::REP_STOSB;
4600         break;
4601       }
4602     } else {
4603       // If it's not a constant value we are storing, just fall back.  We could
4604       // try to be clever to form 16 bit and 32 bit values, but we don't yet.
4605       unsigned ValReg = SelectExpr(Node->getOperand(2));
4606       BuildMI(BB, X86::MOV8rr, 1, X86::AL).addReg(ValReg);
4607       CountReg = SelectExpr(Node->getOperand(3));
4608       Opcode = X86::REP_STOSB;
4609     }
4610
4611     // No matter what the alignment is, we put the source in ESI, the
4612     // destination in EDI, and the count in ECX.
4613     unsigned TmpReg1 = SelectExpr(Node->getOperand(1));
4614     BuildMI(BB, X86::MOV32rr, 1, X86::ECX).addReg(CountReg);
4615     BuildMI(BB, X86::MOV32rr, 1, X86::EDI).addReg(TmpReg1);
4616     BuildMI(BB, Opcode, 0);
4617     return;
4618   }
4619   case ISD::MEMCPY: {
4620     Select(N.getOperand(0));  // Select the chain.
4621     unsigned Align =
4622       (unsigned)cast<ConstantSDNode>(Node->getOperand(4))->getValue();
4623     if (Align == 0) Align = 1;
4624
4625     // Turn the byte code into # iterations
4626     unsigned CountReg;
4627     unsigned Opcode;
4628     switch (Align & 3) {
4629     case 2:   // WORD aligned
4630       CountReg = MakeReg(MVT::i32);
4631       if (ConstantSDNode *I = dyn_cast<ConstantSDNode>(Node->getOperand(3))) {
4632         BuildMI(BB, X86::MOV32ri, 1, CountReg).addImm(I->getValue()/2);
4633       } else {
4634         unsigned ByteReg = SelectExpr(Node->getOperand(3));
4635         BuildMI(BB, X86::SHR32ri, 2, CountReg).addReg(ByteReg).addImm(1);
4636       }
4637       Opcode = X86::REP_MOVSW;
4638       break;
4639     case 0:   // DWORD aligned
4640       CountReg = MakeReg(MVT::i32);
4641       if (ConstantSDNode *I = dyn_cast<ConstantSDNode>(Node->getOperand(3))) {
4642         BuildMI(BB, X86::MOV32ri, 1, CountReg).addImm(I->getValue()/4);
4643       } else {
4644         unsigned ByteReg = SelectExpr(Node->getOperand(3));
4645         BuildMI(BB, X86::SHR32ri, 2, CountReg).addReg(ByteReg).addImm(2);
4646       }
4647       Opcode = X86::REP_MOVSD;
4648       break;
4649     default:  // BYTE aligned
4650       CountReg = SelectExpr(Node->getOperand(3));
4651       Opcode = X86::REP_MOVSB;
4652       break;
4653     }
4654
4655     // No matter what the alignment is, we put the source in ESI, the
4656     // destination in EDI, and the count in ECX.
4657     unsigned TmpReg1 = SelectExpr(Node->getOperand(1));
4658     unsigned TmpReg2 = SelectExpr(Node->getOperand(2));
4659     BuildMI(BB, X86::MOV32rr, 1, X86::ECX).addReg(CountReg);
4660     BuildMI(BB, X86::MOV32rr, 1, X86::EDI).addReg(TmpReg1);
4661     BuildMI(BB, X86::MOV32rr, 1, X86::ESI).addReg(TmpReg2);
4662     BuildMI(BB, Opcode, 0);
4663     return;
4664   }
4665   case ISD::WRITEPORT:
4666     if (Node->getOperand(2).getValueType() != MVT::i16) {
4667       std::cerr << "llvm.writeport: Address size is not 16 bits\n";
4668       exit(1);
4669     }
4670     Select(Node->getOperand(0)); // Emit the chain.
4671
4672     Tmp1 = SelectExpr(Node->getOperand(1));
4673     switch (Node->getOperand(1).getValueType()) {
4674     case MVT::i8:
4675       BuildMI(BB, X86::MOV8rr, 1, X86::AL).addReg(Tmp1);
4676       Tmp2 = X86::OUT8ir;  Opc = X86::OUT8rr;
4677       break;
4678     case MVT::i16:
4679       BuildMI(BB, X86::MOV16rr, 1, X86::AX).addReg(Tmp1);
4680       Tmp2 = X86::OUT16ir; Opc = X86::OUT16rr;
4681       break;
4682     case MVT::i32:
4683       BuildMI(BB, X86::MOV32rr, 1, X86::EAX).addReg(Tmp1);
4684       Tmp2 = X86::OUT32ir; Opc = X86::OUT32rr;
4685       break;
4686     default:
4687       std::cerr << "llvm.writeport: invalid data type for X86 target";
4688       exit(1);
4689     }
4690
4691     // If the port is a single-byte constant, use the immediate form.
4692     if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(Node->getOperand(2)))
4693       if ((CN->getValue() & 255) == CN->getValue()) {
4694         BuildMI(BB, Tmp2, 1).addImm(CN->getValue());
4695         return;
4696       }
4697
4698     // Otherwise, move the I/O port address into the DX register.
4699     unsigned Reg = SelectExpr(Node->getOperand(2));
4700     BuildMI(BB, X86::MOV16rr, 1, X86::DX).addReg(Reg);
4701     BuildMI(BB, Opc, 0);
4702     return;
4703   }
4704   assert(0 && "Should not be reached!");
4705 }
4706
4707
4708 /// createX86PatternInstructionSelector - This pass converts an LLVM function
4709 /// into a machine code representation using pattern matching and a machine
4710 /// description file.
4711 ///
4712 FunctionPass *llvm::createX86PatternInstructionSelector(TargetMachine &TM) {
4713   return new ISel(TM);
4714 }