Rename maxStoresPerMemSet to maxStoresPerMemset, etc.
[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 "X86ISelLowering.h"
19 #include "llvm/CallingConv.h"
20 #include "llvm/Constants.h"
21 #include "llvm/Instructions.h"
22 #include "llvm/Function.h"
23 #include "llvm/CodeGen/MachineConstantPool.h"
24 #include "llvm/CodeGen/MachineFunction.h"
25 #include "llvm/CodeGen/MachineFrameInfo.h"
26 #include "llvm/CodeGen/SelectionDAG.h"
27 #include "llvm/CodeGen/SelectionDAGISel.h"
28 #include "llvm/CodeGen/SSARegMap.h"
29 #include "llvm/Target/TargetData.h"
30 #include "llvm/Target/TargetLowering.h"
31 #include "llvm/Target/TargetMachine.h"
32 #include "llvm/Target/TargetOptions.h"
33 #include "llvm/Support/CFG.h"
34 #include "llvm/Support/MathExtras.h"
35 #include "llvm/ADT/Statistic.h"
36 #include <set>
37 #include <iostream>
38 #include <algorithm>
39 using namespace llvm;
40
41 //===----------------------------------------------------------------------===//
42 //                      Pattern Matcher Implementation
43 //===----------------------------------------------------------------------===//
44
45 namespace {
46   /// X86ISelAddressMode - This corresponds to X86AddressMode, but uses
47   /// SDOperand's instead of register numbers for the leaves of the matched
48   /// tree.
49   struct X86ISelAddressMode {
50     enum {
51       RegBase,
52       FrameIndexBase,
53     } BaseType;
54
55     struct {            // This is really a union, discriminated by BaseType!
56       SDOperand Reg;
57       int FrameIndex;
58     } Base;
59
60     unsigned Scale;
61     SDOperand IndexReg;
62     unsigned Disp;
63     GlobalValue *GV;
64
65     X86ISelAddressMode()
66       : BaseType(RegBase), Scale(1), IndexReg(), Disp(), GV(0) {
67     }
68   };
69 }
70
71
72 namespace {
73   Statistic<>
74   NumFPKill("x86-codegen", "Number of FP_REG_KILL instructions added");
75
76   //===--------------------------------------------------------------------===//
77   /// ISel - X86 specific code to select X86 machine instructions for
78   /// SelectionDAG operations.
79   ///
80   class ISel : public SelectionDAGISel {
81     /// ContainsFPCode - Every instruction we select that uses or defines a FP
82     /// register should set this to true.
83     bool ContainsFPCode;
84
85     /// X86Lowering - This object fully describes how to lower LLVM code to an
86     /// X86-specific SelectionDAG.
87     X86TargetLowering X86Lowering;
88
89     /// RegPressureMap - This keeps an approximate count of the number of
90     /// registers required to evaluate each node in the graph.
91     std::map<SDNode*, unsigned> RegPressureMap;
92
93     /// ExprMap - As shared expressions are codegen'd, we keep track of which
94     /// vreg the value is produced in, so we only emit one copy of each compiled
95     /// tree.
96     std::map<SDOperand, unsigned> ExprMap;
97
98     /// TheDAG - The DAG being selected during Select* operations.
99     SelectionDAG *TheDAG;
100
101     /// Subtarget - Keep a pointer to the X86Subtarget around so that we can
102     /// make the right decision when generating code for different targets.
103     const X86Subtarget *Subtarget;
104     
105     const TargetData &TD;
106
107     /// X86ScalarSSE - Select between SSE2 or x87 floating point ops.
108     bool X86ScalarSSE;
109   public:
110     ISel(TargetMachine &TM) : SelectionDAGISel(X86Lowering), 
111                               X86Lowering(TM), TD(TM.getTargetData()) {
112       Subtarget = &TM.getSubtarget<X86Subtarget>();
113       X86ScalarSSE = Subtarget->hasSSE2();
114     }
115
116     virtual const char *getPassName() const {
117       return "X86 Pattern Instruction Selection";
118     }
119
120     unsigned getRegPressure(SDOperand O) {
121       return RegPressureMap[O.Val];
122     }
123     unsigned ComputeRegPressure(SDOperand O);
124
125     /// InstructionSelectBasicBlock - This callback is invoked by
126     /// SelectionDAGISel when it has created a SelectionDAG for us to codegen.
127     virtual void InstructionSelectBasicBlock(SelectionDAG &DAG);
128
129     virtual void EmitFunctionEntryCode(Function &Fn, MachineFunction &MF);
130
131     bool isFoldableLoad(SDOperand Op, SDOperand OtherOp,
132                         bool FloatPromoteOk = false);
133     void EmitFoldedLoad(SDOperand Op, X86AddressMode &AM);
134     bool TryToFoldLoadOpStore(SDNode *Node);
135     bool EmitOrOpOp(SDOperand Op1, SDOperand Op2, unsigned DestReg);
136     void EmitCMP(SDOperand LHS, SDOperand RHS, bool isOnlyUse);
137     bool EmitBranchCC(MachineBasicBlock *Dest, SDOperand Chain, SDOperand Cond);
138     void EmitSelectCC(SDOperand Cond, SDOperand True, SDOperand False, 
139                       MVT::ValueType SVT, unsigned RDest);
140     unsigned SelectExpr(SDOperand N);
141
142     X86AddressMode SelectAddrExprs(const X86ISelAddressMode &IAM);
143     bool MatchAddress(SDOperand N, X86ISelAddressMode &AM);
144     void SelectAddress(SDOperand N, X86AddressMode &AM);
145     bool EmitPotentialTailCall(SDNode *Node);
146     void EmitFastCCToFastCCTailCall(SDNode *TailCallNode);
147     void Select(SDOperand N);
148   };
149 }
150
151 /// EmitSpecialCodeForMain - Emit any code that needs to be executed only in
152 /// the main function.
153 static void EmitSpecialCodeForMain(MachineBasicBlock *BB,
154                                    MachineFrameInfo *MFI) {
155   // Switch the FPU to 64-bit precision mode for better compatibility and speed.
156   int CWFrameIdx = MFI->CreateStackObject(2, 2);
157   addFrameReference(BuildMI(BB, X86::FNSTCW16m, 4), CWFrameIdx);
158
159   // Set the high part to be 64-bit precision.
160   addFrameReference(BuildMI(BB, X86::MOV8mi, 5),
161                     CWFrameIdx, 1).addImm(2);
162
163   // Reload the modified control word now.
164   addFrameReference(BuildMI(BB, X86::FLDCW16m, 4), CWFrameIdx);
165 }
166
167 void ISel::EmitFunctionEntryCode(Function &Fn, MachineFunction &MF) {
168   // If this is main, emit special code for main.
169   MachineBasicBlock *BB = MF.begin();
170   if (Fn.hasExternalLinkage() && Fn.getName() == "main")
171     EmitSpecialCodeForMain(BB, MF.getFrameInfo());
172 }
173
174
175 /// InstructionSelectBasicBlock - This callback is invoked by SelectionDAGISel
176 /// when it has created a SelectionDAG for us to codegen.
177 void ISel::InstructionSelectBasicBlock(SelectionDAG &DAG) {
178   // While we're doing this, keep track of whether we see any FP code for
179   // FP_REG_KILL insertion.
180   ContainsFPCode = false;
181   MachineFunction *MF = BB->getParent();
182
183   // Scan the PHI nodes that already are inserted into this basic block.  If any
184   // of them is a PHI of a floating point value, we need to insert an
185   // FP_REG_KILL.
186   SSARegMap *RegMap = MF->getSSARegMap();
187   if (BB != MF->begin())
188     for (MachineBasicBlock::iterator I = BB->begin(), E = BB->end();
189          I != E; ++I) {
190       assert(I->getOpcode() == X86::PHI &&
191              "Isn't just PHI nodes?");
192       if (RegMap->getRegClass(I->getOperand(0).getReg()) ==
193           X86::RFPRegisterClass) {
194         ContainsFPCode = true;
195         break;
196       }
197     }
198
199   // Compute the RegPressureMap, which is an approximation for the number of
200   // registers required to compute each node.
201   ComputeRegPressure(DAG.getRoot());
202
203   TheDAG = &DAG;
204
205   // Codegen the basic block.
206   Select(DAG.getRoot());
207
208   TheDAG = 0;
209
210   // Finally, look at all of the successors of this block.  If any contain a PHI
211   // node of FP type, we need to insert an FP_REG_KILL in this block.
212   for (MachineBasicBlock::succ_iterator SI = BB->succ_begin(),
213          E = BB->succ_end(); SI != E && !ContainsFPCode; ++SI)
214     for (MachineBasicBlock::iterator I = (*SI)->begin(), E = (*SI)->end();
215          I != E && I->getOpcode() == X86::PHI; ++I) {
216       if (RegMap->getRegClass(I->getOperand(0).getReg()) ==
217           X86::RFPRegisterClass) {
218         ContainsFPCode = true;
219         break;
220       }
221     }
222
223   // Final check, check LLVM BB's that are successors to the LLVM BB
224   // corresponding to BB for FP PHI nodes.
225   const BasicBlock *LLVMBB = BB->getBasicBlock();
226   const PHINode *PN;
227   if (!ContainsFPCode)
228     for (succ_const_iterator SI = succ_begin(LLVMBB), E = succ_end(LLVMBB);
229          SI != E && !ContainsFPCode; ++SI)
230       for (BasicBlock::const_iterator II = SI->begin();
231            (PN = dyn_cast<PHINode>(II)); ++II)
232         if (PN->getType()->isFloatingPoint()) {
233           ContainsFPCode = true;
234           break;
235         }
236
237   // Insert FP_REG_KILL instructions into basic blocks that need them.  This
238   // only occurs due to the floating point stackifier not being aggressive
239   // enough to handle arbitrary global stackification.
240   //
241   // Currently we insert an FP_REG_KILL instruction into each block that uses or
242   // defines a floating point virtual register.
243   //
244   // When the global register allocators (like linear scan) finally update live
245   // variable analysis, we can keep floating point values in registers across
246   // basic blocks.  This will be a huge win, but we are waiting on the global
247   // allocators before we can do this.
248   //
249   if (ContainsFPCode) {
250     BuildMI(*BB, BB->getFirstTerminator(), X86::FP_REG_KILL, 0);
251     ++NumFPKill;
252   }
253
254   // Clear state used for selection.
255   ExprMap.clear();
256   RegPressureMap.clear();
257 }
258
259
260 // ComputeRegPressure - Compute the RegPressureMap, which is an approximation
261 // for the number of registers required to compute each node.  This is basically
262 // computing a generalized form of the Sethi-Ullman number for each node.
263 unsigned ISel::ComputeRegPressure(SDOperand O) {
264   SDNode *N = O.Val;
265   unsigned &Result = RegPressureMap[N];
266   if (Result) return Result;
267
268   // FIXME: Should operations like CALL (which clobber lots o regs) have a
269   // higher fixed cost??
270
271   if (N->getNumOperands() == 0) {
272     Result = 1;
273   } else {
274     unsigned MaxRegUse = 0;
275     unsigned NumExtraMaxRegUsers = 0;
276     for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
277       unsigned Regs;
278       if (N->getOperand(i).getOpcode() == ISD::Constant)
279         Regs = 0;
280       else
281         Regs = ComputeRegPressure(N->getOperand(i));
282       if (Regs > MaxRegUse) {
283         MaxRegUse = Regs;
284         NumExtraMaxRegUsers = 0;
285       } else if (Regs == MaxRegUse &&
286                  N->getOperand(i).getValueType() != MVT::Other) {
287         ++NumExtraMaxRegUsers;
288       }
289     }
290
291     if (O.getOpcode() != ISD::TokenFactor)
292       Result = MaxRegUse+NumExtraMaxRegUsers;
293     else
294       Result = MaxRegUse == 1 ? 0 : MaxRegUse-1;
295   }
296
297   //std::cerr << " WEIGHT: " << Result << " ";  N->dump(); std::cerr << "\n";
298   return Result;
299 }
300
301 /// NodeTransitivelyUsesValue - Return true if N or any of its uses uses Op.
302 /// The DAG cannot have cycles in it, by definition, so the visited set is not
303 /// needed to prevent infinite loops.  The DAG CAN, however, have unbounded
304 /// reuse, so it prevents exponential cases.
305 ///
306 static bool NodeTransitivelyUsesValue(SDOperand N, SDOperand Op,
307                                       std::set<SDNode*> &Visited) {
308   if (N == Op) return true;                        // Found it.
309   SDNode *Node = N.Val;
310   if (Node->getNumOperands() == 0 ||      // Leaf?
311       Node->getNodeDepth() <= Op.getNodeDepth()) return false; // Can't find it?
312   if (!Visited.insert(Node).second) return false;  // Already visited?
313
314   // Recurse for the first N-1 operands.
315   for (unsigned i = 1, e = Node->getNumOperands(); i != e; ++i)
316     if (NodeTransitivelyUsesValue(Node->getOperand(i), Op, Visited))
317       return true;
318
319   // Tail recurse for the last operand.
320   return NodeTransitivelyUsesValue(Node->getOperand(0), Op, Visited);
321 }
322
323 X86AddressMode ISel::SelectAddrExprs(const X86ISelAddressMode &IAM) {
324   X86AddressMode Result;
325
326   // If we need to emit two register operands, emit the one with the highest
327   // register pressure first.
328   if (IAM.BaseType == X86ISelAddressMode::RegBase &&
329       IAM.Base.Reg.Val && IAM.IndexReg.Val) {
330     bool EmitBaseThenIndex;
331     if (getRegPressure(IAM.Base.Reg) > getRegPressure(IAM.IndexReg)) {
332       std::set<SDNode*> Visited;
333       EmitBaseThenIndex = true;
334       // If Base ends up pointing to Index, we must emit index first.  This is
335       // because of the way we fold loads, we may end up doing bad things with
336       // the folded add.
337       if (NodeTransitivelyUsesValue(IAM.Base.Reg, IAM.IndexReg, Visited))
338         EmitBaseThenIndex = false;
339     } else {
340       std::set<SDNode*> Visited;
341       EmitBaseThenIndex = false;
342       // If Base ends up pointing to Index, we must emit index first.  This is
343       // because of the way we fold loads, we may end up doing bad things with
344       // the folded add.
345       if (NodeTransitivelyUsesValue(IAM.IndexReg, IAM.Base.Reg, Visited))
346         EmitBaseThenIndex = true;
347     }
348
349     if (EmitBaseThenIndex) {
350       Result.Base.Reg = SelectExpr(IAM.Base.Reg);
351       Result.IndexReg = SelectExpr(IAM.IndexReg);
352     } else {
353       Result.IndexReg = SelectExpr(IAM.IndexReg);
354       Result.Base.Reg = SelectExpr(IAM.Base.Reg);
355     }
356
357   } else if (IAM.BaseType == X86ISelAddressMode::RegBase && IAM.Base.Reg.Val) {
358     Result.Base.Reg = SelectExpr(IAM.Base.Reg);
359   } else if (IAM.IndexReg.Val) {
360     Result.IndexReg = SelectExpr(IAM.IndexReg);
361   }
362
363   switch (IAM.BaseType) {
364   case X86ISelAddressMode::RegBase:
365     Result.BaseType = X86AddressMode::RegBase;
366     break;
367   case X86ISelAddressMode::FrameIndexBase:
368     Result.BaseType = X86AddressMode::FrameIndexBase;
369     Result.Base.FrameIndex = IAM.Base.FrameIndex;
370     break;
371   default:
372     assert(0 && "Unknown base type!");
373     break;
374   }
375   Result.Scale = IAM.Scale;
376   Result.Disp = IAM.Disp;
377   Result.GV = IAM.GV;
378   return Result;
379 }
380
381 /// SelectAddress - Pattern match the maximal addressing mode for this node and
382 /// emit all of the leaf registers.
383 void ISel::SelectAddress(SDOperand N, X86AddressMode &AM) {
384   X86ISelAddressMode IAM;
385   MatchAddress(N, IAM);
386   AM = SelectAddrExprs(IAM);
387 }
388
389 /// MatchAddress - Add the specified node to the specified addressing mode,
390 /// returning true if it cannot be done.  This just pattern matches for the
391 /// addressing mode, it does not cause any code to be emitted.  For that, use
392 /// SelectAddress.
393 bool ISel::MatchAddress(SDOperand N, X86ISelAddressMode &AM) {
394   switch (N.getOpcode()) {
395   default: break;
396   case ISD::FrameIndex:
397     if (AM.BaseType == X86ISelAddressMode::RegBase && AM.Base.Reg.Val == 0) {
398       AM.BaseType = X86ISelAddressMode::FrameIndexBase;
399       AM.Base.FrameIndex = cast<FrameIndexSDNode>(N)->getIndex();
400       return false;
401     }
402     break;
403   case ISD::GlobalAddress:
404     if (AM.GV == 0) {
405       GlobalValue *GV = cast<GlobalAddressSDNode>(N)->getGlobal();
406       // For Darwin, external and weak symbols are indirect, so we want to load
407       // the value at address GV, not the value of GV itself.  This means that
408       // the GlobalAddress must be in the base or index register of the address,
409       // not the GV offset field.
410       if (Subtarget->getIndirectExternAndWeakGlobals() &&
411           (GV->hasWeakLinkage() || GV->isExternal())) {
412         break;
413       } else {
414         AM.GV = GV;
415         return false;
416       }
417     }
418     break;
419   case ISD::Constant:
420     AM.Disp += cast<ConstantSDNode>(N)->getValue();
421     return false;
422   case ISD::SHL:
423     // We might have folded the load into this shift, so don't regen the value
424     // if so.
425     if (ExprMap.count(N)) break;
426
427     if (AM.IndexReg.Val == 0 && AM.Scale == 1)
428       if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N.Val->getOperand(1))) {
429         unsigned Val = CN->getValue();
430         if (Val == 1 || Val == 2 || Val == 3) {
431           AM.Scale = 1 << Val;
432           SDOperand ShVal = N.Val->getOperand(0);
433
434           // Okay, we know that we have a scale by now.  However, if the scaled
435           // value is an add of something and a constant, we can fold the
436           // constant into the disp field here.
437           if (ShVal.Val->getOpcode() == ISD::ADD && ShVal.hasOneUse() &&
438               isa<ConstantSDNode>(ShVal.Val->getOperand(1))) {
439             AM.IndexReg = ShVal.Val->getOperand(0);
440             ConstantSDNode *AddVal =
441               cast<ConstantSDNode>(ShVal.Val->getOperand(1));
442             AM.Disp += AddVal->getValue() << Val;
443           } else {
444             AM.IndexReg = ShVal;
445           }
446           return false;
447         }
448       }
449     break;
450   case ISD::MUL:
451     // We might have folded the load into this mul, so don't regen the value if
452     // so.
453     if (ExprMap.count(N)) break;
454
455     // X*[3,5,9] -> X+X*[2,4,8]
456     if (AM.IndexReg.Val == 0 && AM.BaseType == X86ISelAddressMode::RegBase &&
457         AM.Base.Reg.Val == 0)
458       if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N.Val->getOperand(1)))
459         if (CN->getValue() == 3 || CN->getValue() == 5 || CN->getValue() == 9) {
460           AM.Scale = unsigned(CN->getValue())-1;
461
462           SDOperand MulVal = N.Val->getOperand(0);
463           SDOperand Reg;
464
465           // Okay, we know that we have a scale by now.  However, if the scaled
466           // value is an add of something and a constant, we can fold the
467           // constant into the disp field here.
468           if (MulVal.Val->getOpcode() == ISD::ADD && MulVal.hasOneUse() &&
469               isa<ConstantSDNode>(MulVal.Val->getOperand(1))) {
470             Reg = MulVal.Val->getOperand(0);
471             ConstantSDNode *AddVal =
472               cast<ConstantSDNode>(MulVal.Val->getOperand(1));
473             AM.Disp += AddVal->getValue() * CN->getValue();
474           } else {
475             Reg = N.Val->getOperand(0);
476           }
477
478           AM.IndexReg = AM.Base.Reg = Reg;
479           return false;
480         }
481     break;
482
483   case ISD::ADD: {
484     // We might have folded the load into this mul, so don't regen the value if
485     // so.
486     if (ExprMap.count(N)) break;
487
488     X86ISelAddressMode Backup = AM;
489     if (!MatchAddress(N.Val->getOperand(0), AM) &&
490         !MatchAddress(N.Val->getOperand(1), AM))
491       return false;
492     AM = Backup;
493     if (!MatchAddress(N.Val->getOperand(1), AM) &&
494         !MatchAddress(N.Val->getOperand(0), AM))
495       return false;
496     AM = Backup;
497     break;
498   }
499   }
500
501   // Is the base register already occupied?
502   if (AM.BaseType != X86ISelAddressMode::RegBase || AM.Base.Reg.Val) {
503     // If so, check to see if the scale index register is set.
504     if (AM.IndexReg.Val == 0) {
505       AM.IndexReg = N;
506       AM.Scale = 1;
507       return false;
508     }
509
510     // Otherwise, we cannot select it.
511     return true;
512   }
513
514   // Default, generate it as a register.
515   AM.BaseType = X86ISelAddressMode::RegBase;
516   AM.Base.Reg = N;
517   return false;
518 }
519
520 /// Emit2SetCCsAndLogical - Emit the following sequence of instructions,
521 /// assuming that the temporary registers are in the 8-bit register class.
522 ///
523 ///  Tmp1 = setcc1
524 ///  Tmp2 = setcc2
525 ///  DestReg = logicalop Tmp1, Tmp2
526 ///
527 static void Emit2SetCCsAndLogical(MachineBasicBlock *BB, unsigned SetCC1,
528                                   unsigned SetCC2, unsigned LogicalOp,
529                                   unsigned DestReg) {
530   SSARegMap *RegMap = BB->getParent()->getSSARegMap();
531   unsigned Tmp1 = RegMap->createVirtualRegister(X86::R8RegisterClass);
532   unsigned Tmp2 = RegMap->createVirtualRegister(X86::R8RegisterClass);
533   BuildMI(BB, SetCC1, 0, Tmp1);
534   BuildMI(BB, SetCC2, 0, Tmp2);
535   BuildMI(BB, LogicalOp, 2, DestReg).addReg(Tmp1).addReg(Tmp2);
536 }
537
538 /// EmitSetCC - Emit the code to set the specified 8-bit register to 1 if the
539 /// condition codes match the specified SetCCOpcode.  Note that some conditions
540 /// require multiple instructions to generate the correct value.
541 static void EmitSetCC(MachineBasicBlock *BB, unsigned DestReg,
542                       ISD::CondCode SetCCOpcode, bool isFP) {
543   unsigned Opc;
544   if (!isFP) {
545     switch (SetCCOpcode) {
546     default: assert(0 && "Illegal integer SetCC!");
547     case ISD::SETEQ: Opc = X86::SETEr; break;
548     case ISD::SETGT: Opc = X86::SETGr; break;
549     case ISD::SETGE: Opc = X86::SETGEr; break;
550     case ISD::SETLT: Opc = X86::SETLr; break;
551     case ISD::SETLE: Opc = X86::SETLEr; break;
552     case ISD::SETNE: Opc = X86::SETNEr; break;
553     case ISD::SETULT: Opc = X86::SETBr; break;
554     case ISD::SETUGT: Opc = X86::SETAr; break;
555     case ISD::SETULE: Opc = X86::SETBEr; break;
556     case ISD::SETUGE: Opc = X86::SETAEr; break;
557     }
558   } else {
559     // On a floating point condition, the flags are set as follows:
560     // ZF  PF  CF   op
561     //  0 | 0 | 0 | X > Y
562     //  0 | 0 | 1 | X < Y
563     //  1 | 0 | 0 | X == Y
564     //  1 | 1 | 1 | unordered
565     //
566     switch (SetCCOpcode) {
567     default: assert(0 && "Invalid FP setcc!");
568     case ISD::SETUEQ:
569     case ISD::SETEQ:
570       Opc = X86::SETEr;    // True if ZF = 1
571       break;
572     case ISD::SETOGT:
573     case ISD::SETGT:
574       Opc = X86::SETAr;    // True if CF = 0 and ZF = 0
575       break;
576     case ISD::SETOGE:
577     case ISD::SETGE:
578       Opc = X86::SETAEr;   // True if CF = 0
579       break;
580     case ISD::SETULT:
581     case ISD::SETLT:
582       Opc = X86::SETBr;    // True if CF = 1
583       break;
584     case ISD::SETULE:
585     case ISD::SETLE:
586       Opc = X86::SETBEr;   // True if CF = 1 or ZF = 1
587       break;
588     case ISD::SETONE:
589     case ISD::SETNE:
590       Opc = X86::SETNEr;   // True if ZF = 0
591       break;
592     case ISD::SETUO:
593       Opc = X86::SETPr;    // True if PF = 1
594       break;
595     case ISD::SETO:
596       Opc = X86::SETNPr;   // True if PF = 0
597       break;
598     case ISD::SETOEQ:      // !PF & ZF
599       Emit2SetCCsAndLogical(BB, X86::SETNPr, X86::SETEr, X86::AND8rr, DestReg);
600       return;
601     case ISD::SETOLT:      // !PF & CF
602       Emit2SetCCsAndLogical(BB, X86::SETNPr, X86::SETBr, X86::AND8rr, DestReg);
603       return;
604     case ISD::SETOLE:      // !PF & (CF || ZF)
605       Emit2SetCCsAndLogical(BB, X86::SETNPr, X86::SETBEr, X86::AND8rr, DestReg);
606       return;
607     case ISD::SETUGT:      // PF | (!ZF & !CF)
608       Emit2SetCCsAndLogical(BB, X86::SETPr, X86::SETAr, X86::OR8rr, DestReg);
609       return;
610     case ISD::SETUGE:      // PF | !CF
611       Emit2SetCCsAndLogical(BB, X86::SETPr, X86::SETAEr, X86::OR8rr, DestReg);
612       return;
613     case ISD::SETUNE:      // PF | !ZF
614       Emit2SetCCsAndLogical(BB, X86::SETPr, X86::SETNEr, X86::OR8rr, DestReg);
615       return;
616     }
617   }
618   BuildMI(BB, Opc, 0, DestReg);
619 }
620
621
622 /// EmitBranchCC - Emit code into BB that arranges for control to transfer to
623 /// the Dest block if the Cond condition is true.  If we cannot fold this
624 /// condition into the branch, return true.
625 ///
626 bool ISel::EmitBranchCC(MachineBasicBlock *Dest, SDOperand Chain,
627                         SDOperand Cond) {
628   // FIXME: Evaluate whether it would be good to emit code like (X < Y) | (A >
629   // B) using two conditional branches instead of one condbr, two setcc's, and
630   // an or.
631   if ((Cond.getOpcode() == ISD::OR ||
632        Cond.getOpcode() == ISD::AND) && Cond.Val->hasOneUse()) {
633     // And and or set the flags for us, so there is no need to emit a TST of the
634     // result.  It is only safe to do this if there is only a single use of the
635     // AND/OR though, otherwise we don't know it will be emitted here.
636     Select(Chain);
637     SelectExpr(Cond);
638     BuildMI(BB, X86::JNE, 1).addMBB(Dest);
639     return false;
640   }
641
642   // Codegen br not C -> JE.
643   if (Cond.getOpcode() == ISD::XOR)
644     if (ConstantSDNode *NC = dyn_cast<ConstantSDNode>(Cond.Val->getOperand(1)))
645       if (NC->isAllOnesValue()) {
646         unsigned CondR;
647         if (getRegPressure(Chain) > getRegPressure(Cond)) {
648           Select(Chain);
649           CondR = SelectExpr(Cond.Val->getOperand(0));
650         } else {
651           CondR = SelectExpr(Cond.Val->getOperand(0));
652           Select(Chain);
653         }
654         BuildMI(BB, X86::TEST8rr, 2).addReg(CondR).addReg(CondR);
655         BuildMI(BB, X86::JE, 1).addMBB(Dest);
656         return false;
657       }
658
659   if (Cond.getOpcode() != ISD::SETCC)
660     return true;                       // Can only handle simple setcc's so far.
661   ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
662
663   unsigned Opc;
664
665   // Handle integer conditions first.
666   if (MVT::isInteger(Cond.getOperand(0).getValueType())) {
667     switch (CC) {
668     default: assert(0 && "Illegal integer SetCC!");
669     case ISD::SETEQ: Opc = X86::JE; break;
670     case ISD::SETGT: Opc = X86::JG; break;
671     case ISD::SETGE: Opc = X86::JGE; break;
672     case ISD::SETLT: Opc = X86::JL; break;
673     case ISD::SETLE: Opc = X86::JLE; break;
674     case ISD::SETNE: Opc = X86::JNE; break;
675     case ISD::SETULT: Opc = X86::JB; break;
676     case ISD::SETUGT: Opc = X86::JA; break;
677     case ISD::SETULE: Opc = X86::JBE; break;
678     case ISD::SETUGE: Opc = X86::JAE; break;
679     }
680     Select(Chain);
681     EmitCMP(Cond.getOperand(0), Cond.getOperand(1), Cond.hasOneUse());
682     BuildMI(BB, Opc, 1).addMBB(Dest);
683     return false;
684   }
685
686   unsigned Opc2 = 0;  // Second branch if needed.
687
688   // On a floating point condition, the flags are set as follows:
689   // ZF  PF  CF   op
690   //  0 | 0 | 0 | X > Y
691   //  0 | 0 | 1 | X < Y
692   //  1 | 0 | 0 | X == Y
693   //  1 | 1 | 1 | unordered
694   //
695   switch (CC) {
696   default: assert(0 && "Invalid FP setcc!");
697   case ISD::SETUEQ:
698   case ISD::SETEQ:   Opc = X86::JE;  break;     // True if ZF = 1
699   case ISD::SETOGT:
700   case ISD::SETGT:   Opc = X86::JA;  break;     // True if CF = 0 and ZF = 0
701   case ISD::SETOGE:
702   case ISD::SETGE:   Opc = X86::JAE; break;     // True if CF = 0
703   case ISD::SETULT:
704   case ISD::SETLT:   Opc = X86::JB;  break;     // True if CF = 1
705   case ISD::SETULE:
706   case ISD::SETLE:   Opc = X86::JBE; break;     // True if CF = 1 or ZF = 1
707   case ISD::SETONE:
708   case ISD::SETNE:   Opc = X86::JNE; break;     // True if ZF = 0
709   case ISD::SETUO:   Opc = X86::JP;  break;     // True if PF = 1
710   case ISD::SETO:    Opc = X86::JNP; break;     // True if PF = 0
711   case ISD::SETUGT:      // PF = 1 | (ZF = 0 & CF = 0)
712     Opc = X86::JA;       // ZF = 0 & CF = 0
713     Opc2 = X86::JP;      // PF = 1
714     break;
715   case ISD::SETUGE:      // PF = 1 | CF = 0
716     Opc = X86::JAE;      // CF = 0
717     Opc2 = X86::JP;      // PF = 1
718     break;
719   case ISD::SETUNE:      // PF = 1 | ZF = 0
720     Opc = X86::JNE;      // ZF = 0
721     Opc2 = X86::JP;      // PF = 1
722     break;
723   case ISD::SETOEQ:      // PF = 0 & ZF = 1
724     //X86::JNP, X86::JE
725     //X86::AND8rr
726     return true;    // FIXME: Emit more efficient code for this branch.
727   case ISD::SETOLT:      // PF = 0 & CF = 1
728     //X86::JNP, X86::JB
729     //X86::AND8rr
730     return true;    // FIXME: Emit more efficient code for this branch.
731   case ISD::SETOLE:      // PF = 0 & (CF = 1 || ZF = 1)
732     //X86::JNP, X86::JBE
733     //X86::AND8rr
734     return true;    // FIXME: Emit more efficient code for this branch.
735   }
736
737   Select(Chain);
738   EmitCMP(Cond.getOperand(0), Cond.getOperand(1), Cond.hasOneUse());
739   BuildMI(BB, Opc, 1).addMBB(Dest);
740   if (Opc2)
741     BuildMI(BB, Opc2, 1).addMBB(Dest);
742   return false;
743 }
744
745 /// EmitSelectCC - Emit code into BB that performs a select operation between
746 /// the two registers RTrue and RFalse, generating a result into RDest.
747 ///
748 void ISel::EmitSelectCC(SDOperand Cond, SDOperand True, SDOperand False,
749                         MVT::ValueType SVT, unsigned RDest) {
750   unsigned RTrue, RFalse;
751   enum Condition {
752     EQ, NE, LT, LE, GT, GE, B, BE, A, AE, P, NP,
753     NOT_SET
754   } CondCode = NOT_SET;
755
756   static const unsigned CMOVTAB16[] = {
757     X86::CMOVE16rr,  X86::CMOVNE16rr, X86::CMOVL16rr,  X86::CMOVLE16rr,
758     X86::CMOVG16rr,  X86::CMOVGE16rr, X86::CMOVB16rr,  X86::CMOVBE16rr,
759     X86::CMOVA16rr,  X86::CMOVAE16rr, X86::CMOVP16rr,  X86::CMOVNP16rr,
760   };
761   static const unsigned CMOVTAB32[] = {
762     X86::CMOVE32rr,  X86::CMOVNE32rr, X86::CMOVL32rr,  X86::CMOVLE32rr,
763     X86::CMOVG32rr,  X86::CMOVGE32rr, X86::CMOVB32rr,  X86::CMOVBE32rr,
764     X86::CMOVA32rr,  X86::CMOVAE32rr, X86::CMOVP32rr,  X86::CMOVNP32rr,
765   };
766   static const unsigned CMOVTABFP[] = {
767     X86::FpCMOVE,  X86::FpCMOVNE, /*missing*/0, /*missing*/0,
768     /*missing*/0,  /*missing*/ 0, X86::FpCMOVB, X86::FpCMOVBE,
769     X86::FpCMOVNBE,X86::FpCMOVNB, X86::FpCMOVP, X86::FpCMOVNP
770   };
771   static const int SSE_CMOVTAB[] = {
772     /*CMPEQ*/   0, /*CMPNEQ*/   4, /*missing*/  0, /*missing*/  0,
773     /*missing*/ 0, /*missing*/  0, /*CMPLT*/    1, /*CMPLE*/    2,
774     /*CMPNLE*/  6, /*CMPNLT*/   5, /*CMPUNORD*/ 3, /*CMPORD*/   7
775   };
776   
777   if (Cond.getOpcode() == ISD::SETCC) {
778     ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
779     if (MVT::isInteger(Cond.getOperand(0).getValueType())) {
780       switch (CC) {
781       default: assert(0 && "Unknown integer comparison!");
782       case ISD::SETEQ:  CondCode = EQ; break;
783       case ISD::SETGT:  CondCode = GT; break;
784       case ISD::SETGE:  CondCode = GE; break;
785       case ISD::SETLT:  CondCode = LT; break;
786       case ISD::SETLE:  CondCode = LE; break;
787       case ISD::SETNE:  CondCode = NE; break;
788       case ISD::SETULT: CondCode = B; break;
789       case ISD::SETUGT: CondCode = A; break;
790       case ISD::SETULE: CondCode = BE; break;
791       case ISD::SETUGE: CondCode = AE; break;
792       }
793     } else {
794       // On a floating point condition, the flags are set as follows:
795       // ZF  PF  CF   op
796       //  0 | 0 | 0 | X > Y
797       //  0 | 0 | 1 | X < Y
798       //  1 | 0 | 0 | X == Y
799       //  1 | 1 | 1 | unordered
800       //
801       switch (CC) {
802       default: assert(0 && "Unknown FP comparison!");
803       case ISD::SETUEQ:
804       case ISD::SETEQ:  CondCode = EQ; break;     // True if ZF = 1
805       case ISD::SETOGT:
806       case ISD::SETGT:  CondCode = A;  break;     // True if CF = 0 and ZF = 0
807       case ISD::SETOGE:
808       case ISD::SETGE:  CondCode = AE; break;     // True if CF = 0
809       case ISD::SETULT:
810       case ISD::SETLT:  CondCode = B;  break;     // True if CF = 1
811       case ISD::SETULE:
812       case ISD::SETLE:  CondCode = BE; break;     // True if CF = 1 or ZF = 1
813       case ISD::SETONE:
814       case ISD::SETNE:  CondCode = NE; break;     // True if ZF = 0
815       case ISD::SETUO:  CondCode = P;  break;     // True if PF = 1
816       case ISD::SETO:   CondCode = NP; break;     // True if PF = 0
817       case ISD::SETUGT:      // PF = 1 | (ZF = 0 & CF = 0)
818       case ISD::SETUGE:      // PF = 1 | CF = 0
819       case ISD::SETUNE:      // PF = 1 | ZF = 0
820       case ISD::SETOEQ:      // PF = 0 & ZF = 1
821       case ISD::SETOLT:      // PF = 0 & CF = 1
822       case ISD::SETOLE:      // PF = 0 & (CF = 1 || ZF = 1)
823         // We cannot emit this comparison as a single cmov.
824         break;
825       }
826     }
827   
828
829     // There's no SSE equivalent of FCMOVE.  For cases where we set a condition
830     // code above and one of the results of the select is +0.0, then we can fake
831     // it up through a clever AND with mask.  Otherwise, we will fall through to
832     // the code below that will use a PHI node to select the right value.
833     if (X86ScalarSSE && (SVT == MVT::f32 || SVT == MVT::f64)) {
834       if (Cond.getOperand(0).getValueType() == SVT && 
835           NOT_SET != CondCode) {
836         ConstantFPSDNode *CT = dyn_cast<ConstantFPSDNode>(True);
837         ConstantFPSDNode *CF = dyn_cast<ConstantFPSDNode>(False);
838         bool TrueZero = CT && CT->isExactlyValue(0.0);
839         bool FalseZero = CF && CF->isExactlyValue(0.0);
840         if (TrueZero || FalseZero) {
841           SDOperand LHS = Cond.getOperand(0);
842           SDOperand RHS = Cond.getOperand(1);
843           
844           // Select the two halves of the condition
845           unsigned RLHS, RRHS;
846           if (getRegPressure(LHS) > getRegPressure(RHS)) {
847             RLHS = SelectExpr(LHS);
848             RRHS = SelectExpr(RHS);
849           } else {
850             RRHS = SelectExpr(RHS);
851             RLHS = SelectExpr(LHS);
852           }
853           
854           // Emit the comparison and generate a mask from it
855           unsigned MaskReg = MakeReg(SVT);
856           unsigned Opc = (SVT == MVT::f32) ? X86::CMPSSrr : X86::CMPSDrr;
857           BuildMI(BB, Opc, 3, MaskReg).addReg(RLHS).addReg(RRHS)
858             .addImm(SSE_CMOVTAB[CondCode]);
859           
860           if (TrueZero) {
861             RFalse = SelectExpr(False);
862             Opc = (SVT == MVT::f32) ? X86::ANDNPSrr : X86::ANDNPDrr;
863             BuildMI(BB, Opc, 2, RDest).addReg(MaskReg).addReg(RFalse);
864           } else {
865             RTrue = SelectExpr(True);
866             Opc = (SVT == MVT::f32) ? X86::ANDPSrr : X86::ANDPDrr;
867             BuildMI(BB, Opc, 2, RDest).addReg(MaskReg).addReg(RTrue);
868           }
869           return;
870         }
871       }
872     }
873   }
874     
875   // Select the true and false values for use in both the SSE PHI case, and the
876   // integer or x87 cmov cases below.
877   if (getRegPressure(True) > getRegPressure(False)) {
878     RTrue = SelectExpr(True);
879     RFalse = SelectExpr(False);
880   } else {
881     RFalse = SelectExpr(False);
882     RTrue = SelectExpr(True);
883   }
884
885   // Since there's no SSE equivalent of FCMOVE, and we couldn't generate an
886   // AND with mask, we'll have to do the normal RISC thing and generate a PHI
887   // node to select between the true and false values.
888   if (X86ScalarSSE && (SVT == MVT::f32 || SVT == MVT::f64)) {
889     // FIXME: emit a direct compare and branch rather than setting a cond reg
890     //        and testing it.
891     unsigned CondReg = SelectExpr(Cond);
892     BuildMI(BB, X86::TEST8rr, 2).addReg(CondReg).addReg(CondReg);
893     
894     // Create an iterator with which to insert the MBB for copying the false
895     // value and the MBB to hold the PHI instruction for this SetCC.
896     MachineBasicBlock *thisMBB = BB;
897     const BasicBlock *LLVM_BB = BB->getBasicBlock();
898     ilist<MachineBasicBlock>::iterator It = BB;
899     ++It;
900     
901     //  thisMBB:
902     //  ...
903     //   TrueVal = ...
904     //   cmpTY ccX, r1, r2
905     //   bCC sinkMBB
906     //   fallthrough --> copy0MBB
907     MachineBasicBlock *copy0MBB = new MachineBasicBlock(LLVM_BB);
908     MachineBasicBlock *sinkMBB = new MachineBasicBlock(LLVM_BB);
909     BuildMI(BB, X86::JNE, 1).addMBB(sinkMBB);
910     MachineFunction *F = BB->getParent();
911     F->getBasicBlockList().insert(It, copy0MBB);
912     F->getBasicBlockList().insert(It, sinkMBB);
913     // Update machine-CFG edges
914     BB->addSuccessor(copy0MBB);
915     BB->addSuccessor(sinkMBB);
916     
917     //  copy0MBB:
918     //   %FalseValue = ...
919     //   # fallthrough to sinkMBB
920     BB = copy0MBB;
921     // Update machine-CFG edges
922     BB->addSuccessor(sinkMBB);
923     
924     //  sinkMBB:
925     //   %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
926     //  ...
927     BB = sinkMBB;
928     BuildMI(BB, X86::PHI, 4, RDest).addReg(RFalse)
929       .addMBB(copy0MBB).addReg(RTrue).addMBB(thisMBB);
930     return;
931   }
932
933   unsigned Opc = 0;
934   if (CondCode != NOT_SET) {
935     switch (SVT) {
936     default: assert(0 && "Cannot select this type!");
937     case MVT::i16: Opc = CMOVTAB16[CondCode]; break;
938     case MVT::i32: Opc = CMOVTAB32[CondCode]; break;
939     case MVT::f64: Opc = CMOVTABFP[CondCode]; break;
940     }
941   }
942
943   // Finally, if we weren't able to fold this, just emit the condition and test
944   // it.
945   if (CondCode == NOT_SET || Opc == 0) {
946     // Get the condition into the zero flag.
947     unsigned CondReg = SelectExpr(Cond);
948     BuildMI(BB, X86::TEST8rr, 2).addReg(CondReg).addReg(CondReg);
949
950     switch (SVT) {
951     default: assert(0 && "Cannot select this type!");
952     case MVT::i16: Opc = X86::CMOVE16rr; break;
953     case MVT::i32: Opc = X86::CMOVE32rr; break;
954     case MVT::f64: Opc = X86::FpCMOVE; break;
955     }
956   } else {
957     // FIXME: CMP R, 0 -> TEST R, R
958     EmitCMP(Cond.getOperand(0), Cond.getOperand(1), Cond.Val->hasOneUse());
959     std::swap(RTrue, RFalse);
960   }
961   BuildMI(BB, Opc, 2, RDest).addReg(RTrue).addReg(RFalse);
962 }
963
964 void ISel::EmitCMP(SDOperand LHS, SDOperand RHS, bool HasOneUse) {
965   unsigned Opc;
966   if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(RHS)) {
967     Opc = 0;
968     if (HasOneUse && isFoldableLoad(LHS, RHS)) {
969       switch (RHS.getValueType()) {
970       default: break;
971       case MVT::i1:
972       case MVT::i8:  Opc = X86::CMP8mi;  break;
973       case MVT::i16: Opc = X86::CMP16mi; break;
974       case MVT::i32: Opc = X86::CMP32mi; break;
975       }
976       if (Opc) {
977         X86AddressMode AM;
978         EmitFoldedLoad(LHS, AM);
979         addFullAddress(BuildMI(BB, Opc, 5), AM).addImm(CN->getValue());
980         return;
981       }
982     }
983
984     switch (RHS.getValueType()) {
985     default: break;
986     case MVT::i1:
987     case MVT::i8:  Opc = X86::CMP8ri;  break;
988     case MVT::i16: Opc = X86::CMP16ri; break;
989     case MVT::i32: Opc = X86::CMP32ri; break;
990     }
991     if (Opc) {
992       unsigned Tmp1 = SelectExpr(LHS);
993       BuildMI(BB, Opc, 2).addReg(Tmp1).addImm(CN->getValue());
994       return;
995     }
996   } else if (ConstantFPSDNode *CN = dyn_cast<ConstantFPSDNode>(RHS)) {
997     if (!X86ScalarSSE && (CN->isExactlyValue(+0.0) ||
998                           CN->isExactlyValue(-0.0))) {
999       unsigned Reg = SelectExpr(LHS);
1000       BuildMI(BB, X86::FpTST, 1).addReg(Reg);
1001       BuildMI(BB, X86::FNSTSW8r, 0);
1002       BuildMI(BB, X86::SAHF, 1);
1003       return;
1004     }
1005   }
1006
1007   Opc = 0;
1008   if (HasOneUse && isFoldableLoad(LHS, RHS)) {
1009     switch (RHS.getValueType()) {
1010     default: break;
1011     case MVT::i1:
1012     case MVT::i8:  Opc = X86::CMP8mr;  break;
1013     case MVT::i16: Opc = X86::CMP16mr; break;
1014     case MVT::i32: Opc = X86::CMP32mr; break;
1015     }
1016     if (Opc) {
1017       X86AddressMode AM;
1018       EmitFoldedLoad(LHS, AM);
1019       unsigned Reg = SelectExpr(RHS);
1020       addFullAddress(BuildMI(BB, Opc, 5), AM).addReg(Reg);
1021       return;
1022     }
1023   }
1024
1025   switch (LHS.getValueType()) {
1026   default: assert(0 && "Cannot compare this value!");
1027   case MVT::i1:
1028   case MVT::i8:  Opc = X86::CMP8rr;  break;
1029   case MVT::i16: Opc = X86::CMP16rr; break;
1030   case MVT::i32: Opc = X86::CMP32rr; break;
1031   case MVT::f32: Opc = X86::UCOMISSrr; break;
1032   case MVT::f64: Opc = X86ScalarSSE ? X86::UCOMISDrr : X86::FpUCOMIr; break;
1033   }
1034   unsigned Tmp1, Tmp2;
1035   if (getRegPressure(LHS) > getRegPressure(RHS)) {
1036     Tmp1 = SelectExpr(LHS);
1037     Tmp2 = SelectExpr(RHS);
1038   } else {
1039     Tmp2 = SelectExpr(RHS);
1040     Tmp1 = SelectExpr(LHS);
1041   }
1042   BuildMI(BB, Opc, 2).addReg(Tmp1).addReg(Tmp2);
1043 }
1044
1045 /// isFoldableLoad - Return true if this is a load instruction that can safely
1046 /// be folded into an operation that uses it.
1047 bool ISel::isFoldableLoad(SDOperand Op, SDOperand OtherOp, bool FloatPromoteOk){
1048   if (Op.getOpcode() == ISD::LOAD) {
1049     // FIXME: currently can't fold constant pool indexes.
1050     if (isa<ConstantPoolSDNode>(Op.getOperand(1)))
1051       return false;
1052   } else if (FloatPromoteOk && Op.getOpcode() == ISD::EXTLOAD &&
1053              cast<VTSDNode>(Op.getOperand(3))->getVT() == MVT::f32) {
1054     // FIXME: currently can't fold constant pool indexes.
1055     if (isa<ConstantPoolSDNode>(Op.getOperand(1)))
1056       return false;
1057   } else {
1058     return false;
1059   }
1060
1061   // If this load has already been emitted, we clearly can't fold it.
1062   assert(Op.ResNo == 0 && "Not a use of the value of the load?");
1063   if (ExprMap.count(Op.getValue(1))) return false;
1064   assert(!ExprMap.count(Op.getValue(0)) && "Value in map but not token chain?");
1065   assert(!ExprMap.count(Op.getValue(1))&&"Token lowered but value not in map?");
1066
1067   // If there is not just one use of its value, we cannot fold.
1068   if (!Op.Val->hasNUsesOfValue(1, 0)) return false;
1069
1070   // Finally, we cannot fold the load into the operation if this would induce a
1071   // cycle into the resultant dag.  To check for this, see if OtherOp (the other
1072   // operand of the operation we are folding the load into) can possible use the
1073   // chain node defined by the load.
1074   if (OtherOp.Val && !Op.Val->hasNUsesOfValue(0, 1)) { // Has uses of chain?
1075     std::set<SDNode*> Visited;
1076     if (NodeTransitivelyUsesValue(OtherOp, Op.getValue(1), Visited))
1077       return false;
1078   }
1079   return true;
1080 }
1081
1082
1083 /// EmitFoldedLoad - Ensure that the arguments of the load are code generated,
1084 /// and compute the address being loaded into AM.
1085 void ISel::EmitFoldedLoad(SDOperand Op, X86AddressMode &AM) {
1086   SDOperand Chain   = Op.getOperand(0);
1087   SDOperand Address = Op.getOperand(1);
1088
1089   if (getRegPressure(Chain) > getRegPressure(Address)) {
1090     Select(Chain);
1091     SelectAddress(Address, AM);
1092   } else {
1093     SelectAddress(Address, AM);
1094     Select(Chain);
1095   }
1096
1097   // The chain for this load is now lowered.
1098   assert(ExprMap.count(SDOperand(Op.Val, 1)) == 0 &&
1099          "Load emitted more than once?");
1100   if (!ExprMap.insert(std::make_pair(Op.getValue(1), 1)).second)
1101     assert(0 && "Load emitted more than once!");
1102 }
1103
1104 // EmitOrOpOp - Pattern match the expression (Op1|Op2), where we know that op1
1105 // and op2 are i8/i16/i32 values with one use each (the or).  If we can form a
1106 // SHLD or SHRD, emit the instruction (generating the value into DestReg) and
1107 // return true.
1108 bool ISel::EmitOrOpOp(SDOperand Op1, SDOperand Op2, unsigned DestReg) {
1109   if (Op1.getOpcode() == ISD::SHL && Op2.getOpcode() == ISD::SRL) {
1110     // good!
1111   } else if (Op2.getOpcode() == ISD::SHL && Op1.getOpcode() == ISD::SRL) {
1112     std::swap(Op1, Op2);  // Op1 is the SHL now.
1113   } else {
1114     return false;  // No match
1115   }
1116
1117   SDOperand ShlVal = Op1.getOperand(0);
1118   SDOperand ShlAmt = Op1.getOperand(1);
1119   SDOperand ShrVal = Op2.getOperand(0);
1120   SDOperand ShrAmt = Op2.getOperand(1);
1121
1122   unsigned RegSize = MVT::getSizeInBits(Op1.getValueType());
1123
1124   // Find out if ShrAmt = 32-ShlAmt  or  ShlAmt = 32-ShrAmt.
1125   if (ShlAmt.getOpcode() == ISD::SUB && ShlAmt.getOperand(1) == ShrAmt)
1126     if (ConstantSDNode *SubCST = dyn_cast<ConstantSDNode>(ShlAmt.getOperand(0)))
1127       if (SubCST->getValue() == RegSize) {
1128         // (A >> ShrAmt) | (A << (32-ShrAmt)) ==> ROR A, ShrAmt
1129         // (A >> ShrAmt) | (B << (32-ShrAmt)) ==> SHRD A, B, ShrAmt
1130         if (ShrVal == ShlVal) {
1131           unsigned Reg, ShAmt;
1132           if (getRegPressure(ShrVal) > getRegPressure(ShrAmt)) {
1133             Reg = SelectExpr(ShrVal);
1134             ShAmt = SelectExpr(ShrAmt);
1135           } else {
1136             ShAmt = SelectExpr(ShrAmt);
1137             Reg = SelectExpr(ShrVal);
1138           }
1139           BuildMI(BB, X86::MOV8rr, 1, X86::CL).addReg(ShAmt);
1140           unsigned Opc = RegSize == 8 ? X86::ROR8rCL :
1141                         (RegSize == 16 ? X86::ROR16rCL : X86::ROR32rCL);
1142           BuildMI(BB, Opc, 1, DestReg).addReg(Reg);
1143           return true;
1144         } else if (RegSize != 8) {
1145           unsigned AReg, BReg;
1146           if (getRegPressure(ShlVal) > getRegPressure(ShrVal)) {
1147             BReg = SelectExpr(ShlVal);
1148             AReg = SelectExpr(ShrVal);
1149           } else {
1150             AReg = SelectExpr(ShrVal);
1151             BReg = SelectExpr(ShlVal);
1152           }
1153           unsigned ShAmt = SelectExpr(ShrAmt);
1154           BuildMI(BB, X86::MOV8rr, 1, X86::CL).addReg(ShAmt);
1155           unsigned Opc = RegSize == 16 ? X86::SHRD16rrCL : X86::SHRD32rrCL;
1156           BuildMI(BB, Opc, 2, DestReg).addReg(AReg).addReg(BReg);
1157           return true;
1158         }
1159       }
1160
1161   if (ShrAmt.getOpcode() == ISD::SUB && ShrAmt.getOperand(1) == ShlAmt)
1162     if (ConstantSDNode *SubCST = dyn_cast<ConstantSDNode>(ShrAmt.getOperand(0)))
1163       if (SubCST->getValue() == RegSize) {
1164         // (A << ShlAmt) | (A >> (32-ShlAmt)) ==> ROL A, ShrAmt
1165         // (A << ShlAmt) | (B >> (32-ShlAmt)) ==> SHLD A, B, ShrAmt
1166         if (ShrVal == ShlVal) {
1167           unsigned Reg, ShAmt;
1168           if (getRegPressure(ShrVal) > getRegPressure(ShlAmt)) {
1169             Reg = SelectExpr(ShrVal);
1170             ShAmt = SelectExpr(ShlAmt);
1171           } else {
1172             ShAmt = SelectExpr(ShlAmt);
1173             Reg = SelectExpr(ShrVal);
1174           }
1175           BuildMI(BB, X86::MOV8rr, 1, X86::CL).addReg(ShAmt);
1176           unsigned Opc = RegSize == 8 ? X86::ROL8rCL :
1177                         (RegSize == 16 ? X86::ROL16rCL : X86::ROL32rCL);
1178           BuildMI(BB, Opc, 1, DestReg).addReg(Reg);
1179           return true;
1180         } else if (RegSize != 8) {
1181           unsigned AReg, BReg;
1182           if (getRegPressure(ShlVal) > getRegPressure(ShrVal)) {
1183             AReg = SelectExpr(ShlVal);
1184             BReg = SelectExpr(ShrVal);
1185           } else {
1186             BReg = SelectExpr(ShrVal);
1187             AReg = SelectExpr(ShlVal);
1188           }
1189           unsigned ShAmt = SelectExpr(ShlAmt);
1190           BuildMI(BB, X86::MOV8rr, 1, X86::CL).addReg(ShAmt);
1191           unsigned Opc = RegSize == 16 ? X86::SHLD16rrCL : X86::SHLD32rrCL;
1192           BuildMI(BB, Opc, 2, DestReg).addReg(AReg).addReg(BReg);
1193           return true;
1194         }
1195       }
1196
1197   if (ConstantSDNode *ShrCst = dyn_cast<ConstantSDNode>(ShrAmt))
1198     if (ConstantSDNode *ShlCst = dyn_cast<ConstantSDNode>(ShlAmt))
1199       if (ShrCst->getValue() < RegSize && ShlCst->getValue() < RegSize)
1200         if (ShrCst->getValue() == RegSize-ShlCst->getValue()) {
1201           // (A >> 5) | (A << 27) --> ROR A, 5
1202           // (A >> 5) | (B << 27) --> SHRD A, B, 5
1203           if (ShrVal == ShlVal) {
1204             unsigned Reg = SelectExpr(ShrVal);
1205             unsigned Opc = RegSize == 8 ? X86::ROR8ri :
1206               (RegSize == 16 ? X86::ROR16ri : X86::ROR32ri);
1207             BuildMI(BB, Opc, 2, DestReg).addReg(Reg).addImm(ShrCst->getValue());
1208             return true;
1209           } else if (RegSize != 8) {
1210             unsigned AReg, BReg;
1211             if (getRegPressure(ShlVal) > getRegPressure(ShrVal)) {
1212               BReg = SelectExpr(ShlVal);
1213               AReg = SelectExpr(ShrVal);
1214             } else {
1215               AReg = SelectExpr(ShrVal);
1216               BReg = SelectExpr(ShlVal);
1217             }
1218             unsigned Opc = RegSize == 16 ? X86::SHRD16rri8 : X86::SHRD32rri8;
1219             BuildMI(BB, Opc, 3, DestReg).addReg(AReg).addReg(BReg)
1220               .addImm(ShrCst->getValue());
1221             return true;
1222           }
1223         }
1224
1225   return false;
1226 }
1227
1228 unsigned ISel::SelectExpr(SDOperand N) {
1229   unsigned Result;
1230   unsigned Tmp1 = 0, Tmp2 = 0, Tmp3 = 0, Opc = 0;
1231   SDNode *Node = N.Val;
1232   SDOperand Op0, Op1;
1233
1234   if (Node->getOpcode() == ISD::CopyFromReg ||
1235       Node->getOpcode() == ISD::Register) {
1236     unsigned Reg = (Node->getOpcode() == ISD::CopyFromReg) ?
1237       cast<RegisterSDNode>(Node->getOperand(1))->getReg() :
1238       cast<RegisterSDNode>(Node)->getReg();
1239     // Just use the specified register as our input if we can.
1240     if (Node->getOpcode() == ISD::Register ||
1241         MRegisterInfo::isVirtualRegister(Reg))
1242       return Reg;
1243   } 
1244
1245   unsigned &Reg = ExprMap[N];
1246   if (Reg) return Reg;
1247
1248   switch (N.getOpcode()) {
1249   default:
1250     Reg = Result = (N.getValueType() != MVT::Other) ?
1251                             MakeReg(N.getValueType()) : 1;
1252     break;
1253   case X86ISD::TAILCALL:
1254   case X86ISD::CALL:
1255     // If this is a call instruction, make sure to prepare ALL of the result
1256     // values as well as the chain.
1257     ExprMap[N.getValue(0)] = 1;
1258     if (Node->getNumValues() > 1) {
1259       Result = MakeReg(Node->getValueType(1));
1260       ExprMap[N.getValue(1)] = Result;
1261       for (unsigned i = 2, e = Node->getNumValues(); i != e; ++i)
1262         ExprMap[N.getValue(i)] = MakeReg(Node->getValueType(i));
1263     } else {
1264       Result = 1;
1265     }
1266     break;
1267   case ISD::ADD_PARTS:
1268   case ISD::SUB_PARTS:
1269   case ISD::SHL_PARTS:
1270   case ISD::SRL_PARTS:
1271   case ISD::SRA_PARTS:
1272     Result = MakeReg(Node->getValueType(0));
1273     ExprMap[N.getValue(0)] = Result;
1274     for (unsigned i = 1, e = N.Val->getNumValues(); i != e; ++i)
1275       ExprMap[N.getValue(i)] = MakeReg(Node->getValueType(i));
1276     break;
1277   }
1278
1279   switch (N.getOpcode()) {
1280   default:
1281     Node->dump();
1282     assert(0 && "Node not handled!\n");
1283   case ISD::FP_EXTEND:
1284     assert(X86ScalarSSE && "Scalar SSE FP must be enabled to use f32");
1285     Tmp1 = SelectExpr(N.getOperand(0));
1286     BuildMI(BB, X86::CVTSS2SDrr, 1, Result).addReg(Tmp1);
1287     return Result;
1288   case ISD::FP_ROUND:
1289     assert(X86ScalarSSE && "Scalar SSE FP must be enabled to use f32");
1290     Tmp1 = SelectExpr(N.getOperand(0));
1291     BuildMI(BB, X86::CVTSD2SSrr, 1, Result).addReg(Tmp1);
1292     return Result;
1293   case ISD::CopyFromReg:
1294     Select(N.getOperand(0));
1295     if (Result == 1) {
1296       Reg = Result = ExprMap[N.getValue(0)] =
1297         MakeReg(N.getValue(0).getValueType());
1298     }
1299     Tmp1 = cast<RegisterSDNode>(Node->getOperand(1))->getReg();
1300     switch (Node->getValueType(0)) {
1301     default: assert(0 && "Cannot CopyFromReg this!");
1302     case MVT::i1:
1303     case MVT::i8:
1304       BuildMI(BB, X86::MOV8rr, 1, Result).addReg(Tmp1);
1305       return Result;
1306     case MVT::i16:
1307       BuildMI(BB, X86::MOV16rr, 1, Result).addReg(Tmp1);
1308       return Result;
1309     case MVT::i32:
1310       BuildMI(BB, X86::MOV32rr, 1, Result).addReg(Tmp1);
1311       return Result;
1312     }
1313
1314   case ISD::FrameIndex:
1315     Tmp1 = cast<FrameIndexSDNode>(N)->getIndex();
1316     addFrameReference(BuildMI(BB, X86::LEA32r, 4, Result), (int)Tmp1);
1317     return Result;
1318   case ISD::ConstantPool: {
1319     Constant *C = cast<ConstantPoolSDNode>(N)->get();
1320     unsigned Align = cast<ConstantPoolSDNode>(N)->getAlignment();
1321     if (Align == 0) {
1322       Align = C->getType() == Type::DoubleTy ? 3 : 
1323           TD.getTypeAlignmentShift(C->getType());
1324     }
1325     Tmp1 = BB->getParent()->getConstantPool()->getConstantPoolIndex(C, Align);
1326     addConstantPoolReference(BuildMI(BB, X86::LEA32r, 4, Result), Tmp1);
1327     return Result;
1328   }
1329   case ISD::ConstantFP:
1330     if (X86ScalarSSE) {
1331       assert(cast<ConstantFPSDNode>(N)->isExactlyValue(+0.0) &&
1332              "SSE only supports +0.0");
1333       Opc = (N.getValueType() == MVT::f32) ? X86::FLD0SS : X86::FLD0SD;
1334       BuildMI(BB, Opc, 0, Result);
1335       return Result;
1336     }
1337     ContainsFPCode = true;
1338     Tmp1 = Result;   // Intermediate Register
1339     if (cast<ConstantFPSDNode>(N)->getValue() < 0.0 ||
1340         cast<ConstantFPSDNode>(N)->isExactlyValue(-0.0))
1341       Tmp1 = MakeReg(MVT::f64);
1342
1343     if (cast<ConstantFPSDNode>(N)->isExactlyValue(+0.0) ||
1344         cast<ConstantFPSDNode>(N)->isExactlyValue(-0.0))
1345       BuildMI(BB, X86::FpLD0, 0, Tmp1);
1346     else if (cast<ConstantFPSDNode>(N)->isExactlyValue(+1.0) ||
1347              cast<ConstantFPSDNode>(N)->isExactlyValue(-1.0))
1348       BuildMI(BB, X86::FpLD1, 0, Tmp1);
1349     else
1350       assert(0 && "Unexpected constant!");
1351     if (Tmp1 != Result)
1352       BuildMI(BB, X86::FpCHS, 1, Result).addReg(Tmp1);
1353     return Result;
1354   case ISD::Constant:
1355     switch (N.getValueType()) {
1356     default: assert(0 && "Cannot use constants of this type!");
1357     case MVT::i1:
1358     case MVT::i8:  Opc = X86::MOV8ri;  break;
1359     case MVT::i16: Opc = X86::MOV16ri; break;
1360     case MVT::i32: Opc = X86::MOV32ri; break;
1361     }
1362     BuildMI(BB, Opc, 1,Result).addImm(cast<ConstantSDNode>(N)->getValue());
1363     return Result;
1364   case ISD::UNDEF:
1365     BuildMI(BB, X86::IMPLICIT_DEF, 0, Result);
1366     return Result;
1367   case ISD::GlobalAddress: {
1368     GlobalValue *GV = cast<GlobalAddressSDNode>(N)->getGlobal();
1369     // For Darwin, external and weak symbols are indirect, so we want to load
1370     // the value at address GV, not the value of GV itself.
1371     if (Subtarget->getIndirectExternAndWeakGlobals() &&
1372         (GV->hasWeakLinkage() || GV->isExternal())) {
1373       BuildMI(BB, X86::MOV32rm, 4, Result).addReg(0).addZImm(1).addReg(0)
1374         .addGlobalAddress(GV, false, 0);
1375     } else {
1376       BuildMI(BB, X86::MOV32ri, 1, Result).addGlobalAddress(GV);
1377     }
1378     return Result;
1379   }
1380   case ISD::ExternalSymbol: {
1381     const char *Sym = cast<ExternalSymbolSDNode>(N)->getSymbol();
1382     BuildMI(BB, X86::MOV32ri, 1, Result).addExternalSymbol(Sym);
1383     return Result;
1384   }
1385   case ISD::ANY_EXTEND:   // treat any extend like zext
1386   case ISD::ZERO_EXTEND: {
1387     int DestIs16 = N.getValueType() == MVT::i16;
1388     int SrcIs16  = N.getOperand(0).getValueType() == MVT::i16;
1389
1390     // FIXME: This hack is here for zero extension casts from bool to i8.  This
1391     // would not be needed if bools were promoted by Legalize.
1392     if (N.getValueType() == MVT::i8) {
1393       Tmp1 = SelectExpr(N.getOperand(0));
1394       BuildMI(BB, X86::MOV8rr, 1, Result).addReg(Tmp1);
1395       return Result;
1396     }
1397
1398     if (isFoldableLoad(N.getOperand(0), SDOperand())) {
1399       static const unsigned Opc[3] = {
1400         X86::MOVZX32rm8, X86::MOVZX32rm16, X86::MOVZX16rm8
1401       };
1402
1403       X86AddressMode AM;
1404       EmitFoldedLoad(N.getOperand(0), AM);
1405       addFullAddress(BuildMI(BB, Opc[SrcIs16+DestIs16*2], 4, Result), AM);
1406
1407       return Result;
1408     }
1409
1410     static const unsigned Opc[3] = {
1411       X86::MOVZX32rr8, X86::MOVZX32rr16, X86::MOVZX16rr8
1412     };
1413     Tmp1 = SelectExpr(N.getOperand(0));
1414     BuildMI(BB, Opc[SrcIs16+DestIs16*2], 1, Result).addReg(Tmp1);
1415     return Result;
1416   }
1417   case ISD::SIGN_EXTEND: {
1418     int DestIs16 = N.getValueType() == MVT::i16;
1419     int SrcIs16  = N.getOperand(0).getValueType() == MVT::i16;
1420
1421     // FIXME: Legalize should promote bools to i8!
1422     assert(N.getOperand(0).getValueType() != MVT::i1 &&
1423            "Sign extend from bool not implemented!");
1424
1425     if (isFoldableLoad(N.getOperand(0), SDOperand())) {
1426       static const unsigned Opc[3] = {
1427         X86::MOVSX32rm8, X86::MOVSX32rm16, X86::MOVSX16rm8
1428       };
1429
1430       X86AddressMode AM;
1431       EmitFoldedLoad(N.getOperand(0), AM);
1432       addFullAddress(BuildMI(BB, Opc[SrcIs16+DestIs16*2], 4, Result), AM);
1433       return Result;
1434     }
1435
1436     static const unsigned Opc[3] = {
1437       X86::MOVSX32rr8, X86::MOVSX32rr16, X86::MOVSX16rr8
1438     };
1439     Tmp1 = SelectExpr(N.getOperand(0));
1440     BuildMI(BB, Opc[SrcIs16+DestIs16*2], 1, Result).addReg(Tmp1);
1441     return Result;
1442   }
1443   case ISD::TRUNCATE:
1444     // Handle cast of LARGER int to SMALLER int using a move to EAX followed by
1445     // a move out of AX or AL.
1446     switch (N.getOperand(0).getValueType()) {
1447     default: assert(0 && "Unknown truncate!");
1448     case MVT::i8:  Tmp2 = X86::AL;  Opc = X86::MOV8rr;  break;
1449     case MVT::i16: Tmp2 = X86::AX;  Opc = X86::MOV16rr; break;
1450     case MVT::i32: Tmp2 = X86::EAX; Opc = X86::MOV32rr; break;
1451     }
1452     Tmp1 = SelectExpr(N.getOperand(0));
1453     BuildMI(BB, Opc, 1, Tmp2).addReg(Tmp1);
1454
1455     switch (N.getValueType()) {
1456     default: assert(0 && "Unknown truncate!");
1457     case MVT::i1:
1458     case MVT::i8:  Tmp2 = X86::AL;  Opc = X86::MOV8rr;  break;
1459     case MVT::i16: Tmp2 = X86::AX;  Opc = X86::MOV16rr; break;
1460     }
1461     BuildMI(BB, Opc, 1, Result).addReg(Tmp2);
1462     return Result;
1463
1464   case ISD::SINT_TO_FP: {
1465     Tmp1 = SelectExpr(N.getOperand(0));  // Get the operand register
1466     unsigned PromoteOpcode = 0;
1467
1468     // We can handle any sint to fp with the direct sse conversion instructions.
1469     if (X86ScalarSSE) {
1470       Opc = (N.getValueType() == MVT::f64) ? X86::CVTSI2SDrr : X86::CVTSI2SSrr;
1471       BuildMI(BB, Opc, 1, Result).addReg(Tmp1);
1472       return Result;
1473     }
1474
1475     ContainsFPCode = true;
1476
1477     // Spill the integer to memory and reload it from there.
1478     MVT::ValueType SrcTy = N.getOperand(0).getValueType();
1479     unsigned Size = MVT::getSizeInBits(SrcTy)/8;
1480     MachineFunction *F = BB->getParent();
1481     int FrameIdx = F->getFrameInfo()->CreateStackObject(Size, Size);
1482
1483     switch (SrcTy) {
1484     case MVT::i32:
1485       addFrameReference(BuildMI(BB, X86::MOV32mr, 5), FrameIdx).addReg(Tmp1);
1486       addFrameReference(BuildMI(BB, X86::FpILD32m, 5, Result), FrameIdx);
1487       break;
1488     case MVT::i16:
1489       addFrameReference(BuildMI(BB, X86::MOV16mr, 5), FrameIdx).addReg(Tmp1);
1490       addFrameReference(BuildMI(BB, X86::FpILD16m, 5, Result), FrameIdx);
1491       break;
1492     default: break; // No promotion required.
1493     }
1494     return Result;
1495   }
1496   case ISD::FP_TO_SINT:
1497     Tmp1 = SelectExpr(N.getOperand(0));  // Get the operand register
1498
1499     // If the target supports SSE2 and is performing FP operations in SSE regs
1500     // instead of the FP stack, then we can use the efficient CVTSS2SI and
1501     // CVTSD2SI instructions.
1502     assert(X86ScalarSSE);
1503     if (MVT::f32 == N.getOperand(0).getValueType()) {
1504       BuildMI(BB, X86::CVTTSS2SIrr, 1, Result).addReg(Tmp1);
1505     } else if (MVT::f64 == N.getOperand(0).getValueType()) {
1506       BuildMI(BB, X86::CVTTSD2SIrr, 1, Result).addReg(Tmp1);
1507     } else {
1508       assert(0 && "Not an f32 or f64?");
1509       abort();
1510     }
1511     return Result;
1512
1513   case ISD::FADD:
1514   case ISD::ADD:
1515     Op0 = N.getOperand(0);
1516     Op1 = N.getOperand(1);
1517
1518     if (isFoldableLoad(Op0, Op1, true)) {
1519       std::swap(Op0, Op1);
1520       goto FoldAdd;
1521     }
1522
1523     if (isFoldableLoad(Op1, Op0, true)) {
1524     FoldAdd:
1525       switch (N.getValueType()) {
1526       default: assert(0 && "Cannot add this type!");
1527       case MVT::i1:
1528       case MVT::i8:  Opc = X86::ADD8rm;  break;
1529       case MVT::i16: Opc = X86::ADD16rm; break;
1530       case MVT::i32: Opc = X86::ADD32rm; break;
1531       case MVT::f32: Opc = X86::ADDSSrm; break;
1532       case MVT::f64:
1533         // For F64, handle promoted load operations (from F32) as well!
1534         if (X86ScalarSSE) {
1535           assert(Op1.getOpcode() == ISD::LOAD && "SSE load not promoted");
1536           Opc = X86::ADDSDrm;
1537         } else {
1538           Opc = Op1.getOpcode() == ISD::LOAD ? X86::FpADD64m : X86::FpADD32m;
1539         }
1540         break;
1541       }
1542       X86AddressMode AM;
1543       EmitFoldedLoad(Op1, AM);
1544       Tmp1 = SelectExpr(Op0);
1545       addFullAddress(BuildMI(BB, Opc, 5, Result).addReg(Tmp1), AM);
1546       return Result;
1547     }
1548
1549     // See if we can codegen this as an LEA to fold operations together.
1550     if (N.getValueType() == MVT::i32) {
1551       ExprMap.erase(N);
1552       X86ISelAddressMode AM;
1553       MatchAddress(N, AM);
1554       ExprMap[N] = Result;
1555
1556       // If this is not just an add, emit the LEA.  For a simple add (like
1557       // reg+reg or reg+imm), we just emit an add.  It might be a good idea to
1558       // leave this as LEA, then peephole it to 'ADD' after two address elim
1559       // happens.
1560       if (AM.Scale != 1 || AM.BaseType == X86ISelAddressMode::FrameIndexBase||
1561           AM.GV || (AM.Base.Reg.Val && AM.IndexReg.Val && AM.Disp)) {
1562         X86AddressMode XAM = SelectAddrExprs(AM);
1563         addFullAddress(BuildMI(BB, X86::LEA32r, 4, Result), XAM);
1564         return Result;
1565       }
1566     }
1567
1568     if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(Op1)) {
1569       Opc = 0;
1570       if (CN->getValue() == 1) {   // add X, 1 -> inc X
1571         switch (N.getValueType()) {
1572         default: assert(0 && "Cannot integer add this type!");
1573         case MVT::i8:  Opc = X86::INC8r; break;
1574         case MVT::i16: Opc = X86::INC16r; break;
1575         case MVT::i32: Opc = X86::INC32r; break;
1576         }
1577       } else if (CN->isAllOnesValue()) { // add X, -1 -> dec X
1578         switch (N.getValueType()) {
1579         default: assert(0 && "Cannot integer add this type!");
1580         case MVT::i8:  Opc = X86::DEC8r; break;
1581         case MVT::i16: Opc = X86::DEC16r; break;
1582         case MVT::i32: Opc = X86::DEC32r; break;
1583         }
1584       }
1585
1586       if (Opc) {
1587         Tmp1 = SelectExpr(Op0);
1588         BuildMI(BB, Opc, 1, Result).addReg(Tmp1);
1589         return Result;
1590       }
1591
1592       switch (N.getValueType()) {
1593       default: assert(0 && "Cannot add this type!");
1594       case MVT::i8:  Opc = X86::ADD8ri; break;
1595       case MVT::i16: Opc = X86::ADD16ri; break;
1596       case MVT::i32: Opc = X86::ADD32ri; break;
1597       }
1598       if (Opc) {
1599         Tmp1 = SelectExpr(Op0);
1600         BuildMI(BB, Opc, 2, Result).addReg(Tmp1).addImm(CN->getValue());
1601         return Result;
1602       }
1603     }
1604
1605     switch (N.getValueType()) {
1606     default: assert(0 && "Cannot add this type!");
1607     case MVT::i8:  Opc = X86::ADD8rr; break;
1608     case MVT::i16: Opc = X86::ADD16rr; break;
1609     case MVT::i32: Opc = X86::ADD32rr; break;
1610     case MVT::f32: Opc = X86::ADDSSrr; break;
1611     case MVT::f64: Opc = X86ScalarSSE ? X86::ADDSDrr : X86::FpADD; break;
1612     }
1613
1614     if (getRegPressure(Op0) > getRegPressure(Op1)) {
1615       Tmp1 = SelectExpr(Op0);
1616       Tmp2 = SelectExpr(Op1);
1617     } else {
1618       Tmp2 = SelectExpr(Op1);
1619       Tmp1 = SelectExpr(Op0);
1620     }
1621
1622     BuildMI(BB, Opc, 2, Result).addReg(Tmp1).addReg(Tmp2);
1623     return Result;
1624
1625   case ISD::FSQRT:
1626     Tmp1 = SelectExpr(Node->getOperand(0));
1627     if (X86ScalarSSE) {
1628       Opc = (N.getValueType() == MVT::f32) ? X86::SQRTSSrr : X86::SQRTSDrr;
1629       BuildMI(BB, Opc, 1, Result).addReg(Tmp1);
1630     } else {
1631       BuildMI(BB, X86::FpSQRT, 1, Result).addReg(Tmp1);
1632     }
1633     return Result;
1634
1635   // FIXME:
1636   // Once we can spill 16 byte constants into the constant pool, we can
1637   // implement SSE equivalents of FABS and FCHS.
1638   case ISD::FABS:
1639   case ISD::FNEG:
1640   case ISD::FSIN:
1641   case ISD::FCOS:
1642     assert(N.getValueType()==MVT::f64 && "Illegal type for this operation");
1643     Tmp1 = SelectExpr(Node->getOperand(0));
1644     switch (N.getOpcode()) {
1645     default: assert(0 && "Unreachable!");
1646     case ISD::FABS: BuildMI(BB, X86::FpABS, 1, Result).addReg(Tmp1); break;
1647     case ISD::FNEG: BuildMI(BB, X86::FpCHS, 1, Result).addReg(Tmp1); break;
1648     case ISD::FSIN: BuildMI(BB, X86::FpSIN, 1, Result).addReg(Tmp1); break;
1649     case ISD::FCOS: BuildMI(BB, X86::FpCOS, 1, Result).addReg(Tmp1); break;
1650     }
1651     return Result;
1652
1653   case ISD::MULHU:
1654     switch (N.getValueType()) {
1655     default: assert(0 && "Unsupported VT!");
1656     case MVT::i8:  Tmp2 = X86::MUL8r;  break;
1657     case MVT::i16: Tmp2 = X86::MUL16r;  break;
1658     case MVT::i32: Tmp2 = X86::MUL32r;  break;
1659     }
1660     // FALL THROUGH
1661   case ISD::MULHS: {
1662     unsigned MovOpc, LowReg, HiReg;
1663     switch (N.getValueType()) {
1664     default: assert(0 && "Unsupported VT!");
1665     case MVT::i8:
1666       MovOpc = X86::MOV8rr;
1667       LowReg = X86::AL;
1668       HiReg = X86::AH;
1669       Opc = X86::IMUL8r;
1670       break;
1671     case MVT::i16:
1672       MovOpc = X86::MOV16rr;
1673       LowReg = X86::AX;
1674       HiReg = X86::DX;
1675       Opc = X86::IMUL16r;
1676       break;
1677     case MVT::i32:
1678       MovOpc = X86::MOV32rr;
1679       LowReg = X86::EAX;
1680       HiReg = X86::EDX;
1681       Opc = X86::IMUL32r;
1682       break;
1683     }
1684     if (Node->getOpcode() != ISD::MULHS)
1685       Opc = Tmp2;  // Get the MULHU opcode.
1686
1687     Op0 = Node->getOperand(0);
1688     Op1 = Node->getOperand(1);
1689     if (getRegPressure(Op0) > getRegPressure(Op1)) {
1690       Tmp1 = SelectExpr(Op0);
1691       Tmp2 = SelectExpr(Op1);
1692     } else {
1693       Tmp2 = SelectExpr(Op1);
1694       Tmp1 = SelectExpr(Op0);
1695     }
1696
1697     // FIXME: Implement folding of loads into the memory operands here!
1698     BuildMI(BB, MovOpc, 1, LowReg).addReg(Tmp1);
1699     BuildMI(BB, Opc, 1).addReg(Tmp2);
1700     BuildMI(BB, MovOpc, 1, Result).addReg(HiReg);
1701     return Result;
1702   }
1703
1704   case ISD::FSUB:
1705   case ISD::FMUL:
1706   case ISD::SUB:
1707   case ISD::MUL:
1708   case ISD::AND:
1709   case ISD::OR:
1710   case ISD::XOR: {
1711     static const unsigned SUBTab[] = {
1712       X86::SUB8ri, X86::SUB16ri, X86::SUB32ri, 0, 0,
1713       X86::SUB8rm, X86::SUB16rm, X86::SUB32rm, X86::FpSUB32m, X86::FpSUB64m,
1714       X86::SUB8rr, X86::SUB16rr, X86::SUB32rr, X86::FpSUB  , X86::FpSUB,
1715     };
1716     static const unsigned SSE_SUBTab[] = {
1717       X86::SUB8ri, X86::SUB16ri, X86::SUB32ri, 0, 0,
1718       X86::SUB8rm, X86::SUB16rm, X86::SUB32rm, X86::SUBSSrm, X86::SUBSDrm,
1719       X86::SUB8rr, X86::SUB16rr, X86::SUB32rr, X86::SUBSSrr, X86::SUBSDrr,
1720     };
1721     static const unsigned MULTab[] = {
1722       0, X86::IMUL16rri, X86::IMUL32rri, 0, 0,
1723       0, X86::IMUL16rm , X86::IMUL32rm, X86::FpMUL32m, X86::FpMUL64m,
1724       0, X86::IMUL16rr , X86::IMUL32rr, X86::FpMUL  , X86::FpMUL,
1725     };
1726     static const unsigned SSE_MULTab[] = {
1727       0, X86::IMUL16rri, X86::IMUL32rri, 0, 0,
1728       0, X86::IMUL16rm , X86::IMUL32rm, X86::MULSSrm, X86::MULSDrm,
1729       0, X86::IMUL16rr , X86::IMUL32rr, X86::MULSSrr, X86::MULSDrr,
1730     };
1731     static const unsigned ANDTab[] = {
1732       X86::AND8ri, X86::AND16ri, X86::AND32ri, 0, 0,
1733       X86::AND8rm, X86::AND16rm, X86::AND32rm, 0, 0,
1734       X86::AND8rr, X86::AND16rr, X86::AND32rr, 0, 0,
1735     };
1736     static const unsigned ORTab[] = {
1737       X86::OR8ri, X86::OR16ri, X86::OR32ri, 0, 0,
1738       X86::OR8rm, X86::OR16rm, X86::OR32rm, 0, 0,
1739       X86::OR8rr, X86::OR16rr, X86::OR32rr, 0, 0,
1740     };
1741     static const unsigned XORTab[] = {
1742       X86::XOR8ri, X86::XOR16ri, X86::XOR32ri, 0, 0,
1743       X86::XOR8rm, X86::XOR16rm, X86::XOR32rm, 0, 0,
1744       X86::XOR8rr, X86::XOR16rr, X86::XOR32rr, 0, 0,
1745     };
1746
1747     Op0 = Node->getOperand(0);
1748     Op1 = Node->getOperand(1);
1749
1750     if (Node->getOpcode() == ISD::OR && Op0.hasOneUse() && Op1.hasOneUse())
1751       if (EmitOrOpOp(Op0, Op1, Result)) // Match SHLD, SHRD, and rotates.
1752         return Result;
1753
1754     if (Node->getOpcode() == ISD::SUB)
1755       if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N.getOperand(0)))
1756         if (CN->isNullValue()) {   // 0 - N -> neg N
1757           switch (N.getValueType()) {
1758           default: assert(0 && "Cannot sub this type!");
1759           case MVT::i1:
1760           case MVT::i8:  Opc = X86::NEG8r;  break;
1761           case MVT::i16: Opc = X86::NEG16r; break;
1762           case MVT::i32: Opc = X86::NEG32r; break;
1763           }
1764           Tmp1 = SelectExpr(N.getOperand(1));
1765           BuildMI(BB, Opc, 1, Result).addReg(Tmp1);
1766           return Result;
1767         }
1768
1769     if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(Op1)) {
1770       if (CN->isAllOnesValue() && Node->getOpcode() == ISD::XOR) {
1771         Opc = 0;
1772         switch (N.getValueType()) {
1773         default: assert(0 && "Cannot add this type!");
1774         case MVT::i1:  break;  // Not supported, don't invert upper bits!
1775         case MVT::i8:  Opc = X86::NOT8r;  break;
1776         case MVT::i16: Opc = X86::NOT16r; break;
1777         case MVT::i32: Opc = X86::NOT32r; break;
1778         }
1779         if (Opc) {
1780           Tmp1 = SelectExpr(Op0);
1781           BuildMI(BB, Opc, 1, Result).addReg(Tmp1);
1782           return Result;
1783         }
1784       }
1785
1786       // Fold common multiplies into LEA instructions.
1787       if (Node->getOpcode() == ISD::MUL && N.getValueType() == MVT::i32) {
1788         switch ((int)CN->getValue()) {
1789         default: break;
1790         case 3:
1791         case 5:
1792         case 9:
1793           // Remove N from exprmap so SelectAddress doesn't get confused.
1794           ExprMap.erase(N);
1795           X86AddressMode AM;
1796           SelectAddress(N, AM);
1797           // Restore it to the map.
1798           ExprMap[N] = Result;
1799           addFullAddress(BuildMI(BB, X86::LEA32r, 4, Result), AM);
1800           return Result;
1801         }
1802       }
1803
1804       switch (N.getValueType()) {
1805       default: assert(0 && "Cannot xor this type!");
1806       case MVT::i1:
1807       case MVT::i8:  Opc = 0; break;
1808       case MVT::i16: Opc = 1; break;
1809       case MVT::i32: Opc = 2; break;
1810       }
1811       switch (Node->getOpcode()) {
1812       default: assert(0 && "Unreachable!");
1813       case ISD::FSUB:
1814       case ISD::SUB: Opc = X86ScalarSSE ? SSE_SUBTab[Opc] : SUBTab[Opc]; break;
1815       case ISD::FMUL:
1816       case ISD::MUL: Opc = X86ScalarSSE ? SSE_MULTab[Opc] : MULTab[Opc]; break;
1817       case ISD::AND: Opc = ANDTab[Opc]; break;
1818       case ISD::OR:  Opc =  ORTab[Opc]; break;
1819       case ISD::XOR: Opc = XORTab[Opc]; break;
1820       }
1821       if (Opc) {  // Can't fold MUL:i8 R, imm
1822         Tmp1 = SelectExpr(Op0);
1823         BuildMI(BB, Opc, 2, Result).addReg(Tmp1).addImm(CN->getValue());
1824         return Result;
1825       }
1826     }
1827
1828     if (isFoldableLoad(Op0, Op1, true))
1829       if (Node->getOpcode() != ISD::SUB && Node->getOpcode() != ISD::FSUB) {
1830         std::swap(Op0, Op1);
1831         goto FoldOps;
1832       } else {
1833         // For FP, emit 'reverse' subract, with a memory operand.
1834         if (N.getValueType() == MVT::f64 && !X86ScalarSSE) {
1835           if (Op0.getOpcode() == ISD::EXTLOAD)
1836             Opc = X86::FpSUBR32m;
1837           else
1838             Opc = X86::FpSUBR64m;
1839
1840           X86AddressMode AM;
1841           EmitFoldedLoad(Op0, AM);
1842           Tmp1 = SelectExpr(Op1);
1843           addFullAddress(BuildMI(BB, Opc, 5, Result).addReg(Tmp1), AM);
1844           return Result;
1845         }
1846       }
1847
1848     if (isFoldableLoad(Op1, Op0, true)) {
1849     FoldOps:
1850       switch (N.getValueType()) {
1851       default: assert(0 && "Cannot operate on this type!");
1852       case MVT::i1:
1853       case MVT::i8:  Opc = 5; break;
1854       case MVT::i16: Opc = 6; break;
1855       case MVT::i32: Opc = 7; break;
1856       case MVT::f32: Opc = 8; break;
1857         // For F64, handle promoted load operations (from F32) as well!
1858       case MVT::f64:
1859         assert((!X86ScalarSSE || Op1.getOpcode() == ISD::LOAD) &&
1860                "SSE load should have been promoted");
1861         Opc = Op1.getOpcode() == ISD::LOAD ? 9 : 8; break;
1862       }
1863       switch (Node->getOpcode()) {
1864       default: assert(0 && "Unreachable!");
1865       case ISD::FSUB:
1866       case ISD::SUB: Opc = X86ScalarSSE ? SSE_SUBTab[Opc] : SUBTab[Opc]; break;
1867       case ISD::FMUL:
1868       case ISD::MUL: Opc = X86ScalarSSE ? SSE_MULTab[Opc] : MULTab[Opc]; break;
1869       case ISD::AND: Opc = ANDTab[Opc]; break;
1870       case ISD::OR:  Opc =  ORTab[Opc]; break;
1871       case ISD::XOR: Opc = XORTab[Opc]; break;
1872       }
1873
1874       X86AddressMode AM;
1875       EmitFoldedLoad(Op1, AM);
1876       Tmp1 = SelectExpr(Op0);
1877       if (Opc) {
1878         addFullAddress(BuildMI(BB, Opc, 5, Result).addReg(Tmp1), AM);
1879       } else {
1880         assert(Node->getOpcode() == ISD::MUL &&
1881                N.getValueType() == MVT::i8 && "Unexpected situation!");
1882         // Must use the MUL instruction, which forces use of AL.
1883         BuildMI(BB, X86::MOV8rr, 1, X86::AL).addReg(Tmp1);
1884         addFullAddress(BuildMI(BB, X86::MUL8m, 1), AM);
1885         BuildMI(BB, X86::MOV8rr, 1, Result).addReg(X86::AL);
1886       }
1887       return Result;
1888     }
1889
1890     if (getRegPressure(Op0) > getRegPressure(Op1)) {
1891       Tmp1 = SelectExpr(Op0);
1892       Tmp2 = SelectExpr(Op1);
1893     } else {
1894       Tmp2 = SelectExpr(Op1);
1895       Tmp1 = SelectExpr(Op0);
1896     }
1897
1898     switch (N.getValueType()) {
1899     default: assert(0 && "Cannot add this type!");
1900     case MVT::i1:
1901     case MVT::i8:  Opc = 10; break;
1902     case MVT::i16: Opc = 11; break;
1903     case MVT::i32: Opc = 12; break;
1904     case MVT::f32: Opc = 13; break;
1905     case MVT::f64: Opc = 14; break;
1906     }
1907     switch (Node->getOpcode()) {
1908     default: assert(0 && "Unreachable!");
1909     case ISD::FSUB:
1910     case ISD::SUB: Opc = X86ScalarSSE ? SSE_SUBTab[Opc] : SUBTab[Opc]; break;
1911     case ISD::FMUL:
1912     case ISD::MUL: Opc = X86ScalarSSE ? SSE_MULTab[Opc] : MULTab[Opc]; break;
1913     case ISD::AND: Opc = ANDTab[Opc]; break;
1914     case ISD::OR:  Opc =  ORTab[Opc]; break;
1915     case ISD::XOR: Opc = XORTab[Opc]; break;
1916     }
1917     if (Opc) {
1918       BuildMI(BB, Opc, 2, Result).addReg(Tmp1).addReg(Tmp2);
1919     } else {
1920       assert(Node->getOpcode() == ISD::MUL &&
1921              N.getValueType() == MVT::i8 && "Unexpected situation!");
1922       // Must use the MUL instruction, which forces use of AL.
1923       BuildMI(BB, X86::MOV8rr, 1, X86::AL).addReg(Tmp1);
1924       BuildMI(BB, X86::MUL8r, 1).addReg(Tmp2);
1925       BuildMI(BB, X86::MOV8rr, 1, Result).addReg(X86::AL);
1926     }
1927     return Result;
1928   }
1929   case ISD::ADD_PARTS:
1930   case ISD::SUB_PARTS: {
1931     assert(N.getNumOperands() == 4 && N.getValueType() == MVT::i32 &&
1932            "Not an i64 add/sub!");
1933     // Emit all of the operands.
1934     std::vector<unsigned> InVals;
1935     for (unsigned i = 0, e = N.getNumOperands(); i != e; ++i)
1936       InVals.push_back(SelectExpr(N.getOperand(i)));
1937     if (N.getOpcode() == ISD::ADD_PARTS) {
1938       BuildMI(BB, X86::ADD32rr, 2, Result).addReg(InVals[0]).addReg(InVals[2]);
1939       BuildMI(BB, X86::ADC32rr,2,Result+1).addReg(InVals[1]).addReg(InVals[3]);
1940     } else {
1941       BuildMI(BB, X86::SUB32rr, 2, Result).addReg(InVals[0]).addReg(InVals[2]);
1942       BuildMI(BB, X86::SBB32rr, 2,Result+1).addReg(InVals[1]).addReg(InVals[3]);
1943     }
1944     return Result+N.ResNo;
1945   }
1946
1947   case ISD::SHL_PARTS:
1948   case ISD::SRA_PARTS:
1949   case ISD::SRL_PARTS: {
1950     assert(N.getNumOperands() == 3 && N.getValueType() == MVT::i32 &&
1951            "Not an i64 shift!");
1952     unsigned ShiftOpLo = SelectExpr(N.getOperand(0));
1953     unsigned ShiftOpHi = SelectExpr(N.getOperand(1));
1954     unsigned TmpReg = MakeReg(MVT::i32);
1955     if (N.getOpcode() == ISD::SRA_PARTS) {
1956       // If this is a SHR of a Long, then we need to do funny sign extension
1957       // stuff.  TmpReg gets the value to use as the high-part if we are
1958       // shifting more than 32 bits.
1959       BuildMI(BB, X86::SAR32ri, 2, TmpReg).addReg(ShiftOpHi).addImm(31);
1960     } else {
1961       // Other shifts use a fixed zero value if the shift is more than 32 bits.
1962       BuildMI(BB, X86::MOV32ri, 1, TmpReg).addImm(0);
1963     }
1964
1965     // Initialize CL with the shift amount.
1966     unsigned ShiftAmountReg = SelectExpr(N.getOperand(2));
1967     BuildMI(BB, X86::MOV8rr, 1, X86::CL).addReg(ShiftAmountReg);
1968
1969     unsigned TmpReg2 = MakeReg(MVT::i32);
1970     unsigned TmpReg3 = MakeReg(MVT::i32);
1971     if (N.getOpcode() == ISD::SHL_PARTS) {
1972       // TmpReg2 = shld inHi, inLo
1973       BuildMI(BB, X86::SHLD32rrCL, 2,TmpReg2).addReg(ShiftOpHi)
1974         .addReg(ShiftOpLo);
1975       // TmpReg3 = shl  inLo, CL
1976       BuildMI(BB, X86::SHL32rCL, 1, TmpReg3).addReg(ShiftOpLo);
1977
1978       // Set the flags to indicate whether the shift was by more than 32 bits.
1979       BuildMI(BB, X86::TEST8ri, 2).addReg(X86::CL).addImm(32);
1980
1981       // DestHi = (>32) ? TmpReg3 : TmpReg2;
1982       BuildMI(BB, X86::CMOVNE32rr, 2,
1983               Result+1).addReg(TmpReg2).addReg(TmpReg3);
1984       // DestLo = (>32) ? TmpReg : TmpReg3;
1985       BuildMI(BB, X86::CMOVNE32rr, 2,
1986               Result).addReg(TmpReg3).addReg(TmpReg);
1987     } else {
1988       // TmpReg2 = shrd inLo, inHi
1989       BuildMI(BB, X86::SHRD32rrCL,2,TmpReg2).addReg(ShiftOpLo)
1990         .addReg(ShiftOpHi);
1991       // TmpReg3 = s[ah]r  inHi, CL
1992       BuildMI(BB, N.getOpcode() == ISD::SRA_PARTS ? X86::SAR32rCL
1993                                                   : X86::SHR32rCL, 1, TmpReg3)
1994         .addReg(ShiftOpHi);
1995
1996       // Set the flags to indicate whether the shift was by more than 32 bits.
1997       BuildMI(BB, X86::TEST8ri, 2).addReg(X86::CL).addImm(32);
1998
1999       // DestLo = (>32) ? TmpReg3 : TmpReg2;
2000       BuildMI(BB, X86::CMOVNE32rr, 2,
2001               Result).addReg(TmpReg2).addReg(TmpReg3);
2002
2003       // DestHi = (>32) ? TmpReg : TmpReg3;
2004       BuildMI(BB, X86::CMOVNE32rr, 2,
2005               Result+1).addReg(TmpReg3).addReg(TmpReg);
2006     }
2007     return Result+N.ResNo;
2008   }
2009
2010   case ISD::SELECT:
2011     EmitSelectCC(N.getOperand(0), N.getOperand(1), N.getOperand(2),
2012                  N.getValueType(), Result);
2013     return Result;
2014
2015   case ISD::FDIV:
2016   case ISD::FREM:
2017   case ISD::SDIV:
2018   case ISD::UDIV:
2019   case ISD::SREM:
2020   case ISD::UREM: {
2021     assert((N.getOpcode() != ISD::SREM || MVT::isInteger(N.getValueType())) &&
2022            "We don't support this operator!");
2023
2024     if (N.getOpcode() == ISD::SDIV || N.getOpcode() == ISD::FDIV) {
2025       // We can fold loads into FpDIVs, but not really into any others.
2026       if (N.getValueType() == MVT::f64 && !X86ScalarSSE) {
2027         // Check for reversed and unreversed DIV.
2028         if (isFoldableLoad(N.getOperand(0), N.getOperand(1), true)) {
2029           if (N.getOperand(0).getOpcode() == ISD::EXTLOAD)
2030             Opc = X86::FpDIVR32m;
2031           else
2032             Opc = X86::FpDIVR64m;
2033           X86AddressMode AM;
2034           EmitFoldedLoad(N.getOperand(0), AM);
2035           Tmp1 = SelectExpr(N.getOperand(1));
2036           addFullAddress(BuildMI(BB, Opc, 5, Result).addReg(Tmp1), AM);
2037           return Result;
2038         } else if (isFoldableLoad(N.getOperand(1), N.getOperand(0), true) &&
2039                    N.getOperand(1).getOpcode() == ISD::LOAD) {
2040           if (N.getOperand(1).getOpcode() == ISD::EXTLOAD)
2041             Opc = X86::FpDIV32m;
2042           else
2043             Opc = X86::FpDIV64m;
2044           X86AddressMode AM;
2045           EmitFoldedLoad(N.getOperand(1), AM);
2046           Tmp1 = SelectExpr(N.getOperand(0));
2047           addFullAddress(BuildMI(BB, Opc, 5, Result).addReg(Tmp1), AM);
2048           return Result;
2049         }
2050       }
2051     }
2052
2053     if (getRegPressure(N.getOperand(0)) > getRegPressure(N.getOperand(1))) {
2054       Tmp1 = SelectExpr(N.getOperand(0));
2055       Tmp2 = SelectExpr(N.getOperand(1));
2056     } else {
2057       Tmp2 = SelectExpr(N.getOperand(1));
2058       Tmp1 = SelectExpr(N.getOperand(0));
2059     }
2060
2061     bool isSigned = N.getOpcode() == ISD::SDIV || N.getOpcode() == ISD::SREM;
2062     bool isDiv    = N.getOpcode() == ISD::SDIV || N.getOpcode() == ISD::UDIV;
2063     unsigned LoReg, HiReg, DivOpcode, MovOpcode, ClrOpcode, SExtOpcode;
2064     switch (N.getValueType()) {
2065     default: assert(0 && "Cannot sdiv this type!");
2066     case MVT::i8:
2067       DivOpcode = isSigned ? X86::IDIV8r : X86::DIV8r;
2068       LoReg = X86::AL;
2069       HiReg = X86::AH;
2070       MovOpcode = X86::MOV8rr;
2071       ClrOpcode = X86::MOV8ri;
2072       SExtOpcode = X86::CBW;
2073       break;
2074     case MVT::i16:
2075       DivOpcode = isSigned ? X86::IDIV16r : X86::DIV16r;
2076       LoReg = X86::AX;
2077       HiReg = X86::DX;
2078       MovOpcode = X86::MOV16rr;
2079       ClrOpcode = X86::MOV16ri;
2080       SExtOpcode = X86::CWD;
2081       break;
2082     case MVT::i32:
2083       DivOpcode = isSigned ? X86::IDIV32r : X86::DIV32r;
2084       LoReg = X86::EAX;
2085       HiReg = X86::EDX;
2086       MovOpcode = X86::MOV32rr;
2087       ClrOpcode = X86::MOV32ri;
2088       SExtOpcode = X86::CDQ;
2089       break;
2090     case MVT::f32:
2091       BuildMI(BB, X86::DIVSSrr, 2, Result).addReg(Tmp1).addReg(Tmp2);
2092       return Result;
2093     case MVT::f64:
2094       Opc = X86ScalarSSE ? X86::DIVSDrr : X86::FpDIV;
2095       BuildMI(BB, Opc, 2, Result).addReg(Tmp1).addReg(Tmp2);
2096       return Result;
2097     }
2098
2099     // Set up the low part.
2100     BuildMI(BB, MovOpcode, 1, LoReg).addReg(Tmp1);
2101
2102     if (isSigned) {
2103       // Sign extend the low part into the high part.
2104       BuildMI(BB, SExtOpcode, 0);
2105     } else {
2106       // Zero out the high part, effectively zero extending the input.
2107       BuildMI(BB, ClrOpcode, 1, HiReg).addImm(0);
2108     }
2109
2110     // Emit the DIV/IDIV instruction.
2111     BuildMI(BB, DivOpcode, 1).addReg(Tmp2);
2112
2113     // Get the result of the divide or rem.
2114     BuildMI(BB, MovOpcode, 1, Result).addReg(isDiv ? LoReg : HiReg);
2115     return Result;
2116   }
2117
2118   case ISD::SHL:
2119     if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N.getOperand(1))) {
2120       if (CN->getValue() == 1) {   // X = SHL Y, 1  -> X = ADD Y, Y
2121         switch (N.getValueType()) {
2122         default: assert(0 && "Cannot shift this type!");
2123         case MVT::i8:  Opc = X86::ADD8rr; break;
2124         case MVT::i16: Opc = X86::ADD16rr; break;
2125         case MVT::i32: Opc = X86::ADD32rr; break;
2126         }
2127         Tmp1 = SelectExpr(N.getOperand(0));
2128         BuildMI(BB, Opc, 2, Result).addReg(Tmp1).addReg(Tmp1);
2129         return Result;
2130       }
2131
2132       switch (N.getValueType()) {
2133       default: assert(0 && "Cannot shift this type!");
2134       case MVT::i8:  Opc = X86::SHL8ri; break;
2135       case MVT::i16: Opc = X86::SHL16ri; break;
2136       case MVT::i32: Opc = X86::SHL32ri; break;
2137       }
2138       Tmp1 = SelectExpr(N.getOperand(0));
2139       BuildMI(BB, Opc, 2, Result).addReg(Tmp1).addImm(CN->getValue());
2140       return Result;
2141     }
2142
2143     if (getRegPressure(N.getOperand(0)) > getRegPressure(N.getOperand(1))) {
2144       Tmp1 = SelectExpr(N.getOperand(0));
2145       Tmp2 = SelectExpr(N.getOperand(1));
2146     } else {
2147       Tmp2 = SelectExpr(N.getOperand(1));
2148       Tmp1 = SelectExpr(N.getOperand(0));
2149     }
2150
2151     switch (N.getValueType()) {
2152     default: assert(0 && "Cannot shift this type!");
2153     case MVT::i8 : Opc = X86::SHL8rCL; break;
2154     case MVT::i16: Opc = X86::SHL16rCL; break;
2155     case MVT::i32: Opc = X86::SHL32rCL; break;
2156     }
2157     BuildMI(BB, X86::MOV8rr, 1, X86::CL).addReg(Tmp2);
2158     BuildMI(BB, Opc, 1, Result).addReg(Tmp1);
2159     return Result;
2160   case ISD::SRL:
2161     if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N.getOperand(1))) {
2162       switch (N.getValueType()) {
2163       default: assert(0 && "Cannot shift this type!");
2164       case MVT::i8:  Opc = X86::SHR8ri; break;
2165       case MVT::i16: Opc = X86::SHR16ri; break;
2166       case MVT::i32: Opc = X86::SHR32ri; break;
2167       }
2168       Tmp1 = SelectExpr(N.getOperand(0));
2169       BuildMI(BB, Opc, 2, Result).addReg(Tmp1).addImm(CN->getValue());
2170       return Result;
2171     }
2172
2173     if (getRegPressure(N.getOperand(0)) > getRegPressure(N.getOperand(1))) {
2174       Tmp1 = SelectExpr(N.getOperand(0));
2175       Tmp2 = SelectExpr(N.getOperand(1));
2176     } else {
2177       Tmp2 = SelectExpr(N.getOperand(1));
2178       Tmp1 = SelectExpr(N.getOperand(0));
2179     }
2180
2181     switch (N.getValueType()) {
2182     default: assert(0 && "Cannot shift this type!");
2183     case MVT::i8 : Opc = X86::SHR8rCL; break;
2184     case MVT::i16: Opc = X86::SHR16rCL; break;
2185     case MVT::i32: Opc = X86::SHR32rCL; break;
2186     }
2187     BuildMI(BB, X86::MOV8rr, 1, X86::CL).addReg(Tmp2);
2188     BuildMI(BB, Opc, 1, Result).addReg(Tmp1);
2189     return Result;
2190   case ISD::SRA:
2191     if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N.getOperand(1))) {
2192       switch (N.getValueType()) {
2193       default: assert(0 && "Cannot shift this type!");
2194       case MVT::i8:  Opc = X86::SAR8ri; break;
2195       case MVT::i16: Opc = X86::SAR16ri; break;
2196       case MVT::i32: Opc = X86::SAR32ri; break;
2197       }
2198       Tmp1 = SelectExpr(N.getOperand(0));
2199       BuildMI(BB, Opc, 2, Result).addReg(Tmp1).addImm(CN->getValue());
2200       return Result;
2201     }
2202
2203     if (getRegPressure(N.getOperand(0)) > getRegPressure(N.getOperand(1))) {
2204       Tmp1 = SelectExpr(N.getOperand(0));
2205       Tmp2 = SelectExpr(N.getOperand(1));
2206     } else {
2207       Tmp2 = SelectExpr(N.getOperand(1));
2208       Tmp1 = SelectExpr(N.getOperand(0));
2209     }
2210
2211     switch (N.getValueType()) {
2212     default: assert(0 && "Cannot shift this type!");
2213     case MVT::i8 : Opc = X86::SAR8rCL; break;
2214     case MVT::i16: Opc = X86::SAR16rCL; break;
2215     case MVT::i32: Opc = X86::SAR32rCL; break;
2216     }
2217     BuildMI(BB, X86::MOV8rr, 1, X86::CL).addReg(Tmp2);
2218     BuildMI(BB, Opc, 1, Result).addReg(Tmp1);
2219     return Result;
2220
2221   case ISD::SETCC:
2222     EmitCMP(N.getOperand(0), N.getOperand(1), Node->hasOneUse());
2223     EmitSetCC(BB, Result, cast<CondCodeSDNode>(N.getOperand(2))->get(),
2224               MVT::isFloatingPoint(N.getOperand(1).getValueType()));
2225     return Result;
2226   case ISD::LOAD:
2227     // Make sure we generate both values.
2228     if (Result != 1) {  // Generate the token
2229       if (!ExprMap.insert(std::make_pair(N.getValue(1), 1)).second)
2230         assert(0 && "Load already emitted!?");
2231     } else
2232       Result = ExprMap[N.getValue(0)] = MakeReg(N.getValue(0).getValueType());
2233
2234     switch (Node->getValueType(0)) {
2235     default: assert(0 && "Cannot load this type!");
2236     case MVT::i1:
2237     case MVT::i8:  Opc = X86::MOV8rm; break;
2238     case MVT::i16: Opc = X86::MOV16rm; break;
2239     case MVT::i32: Opc = X86::MOV32rm; break;
2240     case MVT::f32: Opc = X86::MOVSSrm; break;
2241     case MVT::f64:
2242       if (X86ScalarSSE) {
2243         Opc = X86::MOVSDrm;
2244       } else {
2245         Opc = X86::FpLD64m;
2246         ContainsFPCode = true;
2247       }
2248       break;
2249     }
2250
2251     if (ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(N.getOperand(1))){
2252       Constant *C = CP->get();
2253       unsigned Align = CP->getAlignment();
2254       if (Align == 0) {
2255         Align = C->getType() == Type::DoubleTy ? 3 : 
2256               TD.getTypeAlignmentShift(C->getType());
2257       }
2258       
2259       unsigned CPIdx = BB->getParent()->getConstantPool()->
2260         getConstantPoolIndex(C, Align);
2261       Select(N.getOperand(0));
2262       addConstantPoolReference(BuildMI(BB, Opc, 4, Result), CPIdx);
2263     } else {
2264       X86AddressMode AM;
2265
2266       SDOperand Chain   = N.getOperand(0);
2267       SDOperand Address = N.getOperand(1);
2268       if (getRegPressure(Chain) > getRegPressure(Address)) {
2269         Select(Chain);
2270         SelectAddress(Address, AM);
2271       } else {
2272         SelectAddress(Address, AM);
2273         Select(Chain);
2274       }
2275
2276       addFullAddress(BuildMI(BB, Opc, 4, Result), AM);
2277     }
2278     return Result;
2279   case X86ISD::FILD:
2280     // Make sure we generate both values.
2281     assert(Result != 1 && N.getValueType() == MVT::f64);
2282     if (!ExprMap.insert(std::make_pair(N.getValue(1), 1)).second)
2283       assert(0 && "Load already emitted!?");
2284
2285     {
2286       X86AddressMode AM;
2287
2288       SDOperand Chain   = N.getOperand(0);
2289       SDOperand Address = N.getOperand(1);
2290       if (getRegPressure(Chain) > getRegPressure(Address)) {
2291         Select(Chain);
2292         SelectAddress(Address, AM);
2293       } else {
2294         SelectAddress(Address, AM);
2295         Select(Chain);
2296       }
2297
2298       addFullAddress(BuildMI(BB, X86::FpILD64m, 4, Result), AM);
2299     }
2300     return Result;
2301
2302   case ISD::EXTLOAD:          // Arbitrarily codegen extloads as MOVZX*
2303   case ISD::ZEXTLOAD: {
2304     // Make sure we generate both values.
2305     if (Result != 1)
2306       ExprMap[N.getValue(1)] = 1;   // Generate the token
2307     else
2308       Result = ExprMap[N.getValue(0)] = MakeReg(N.getValue(0).getValueType());
2309
2310     if (ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(N.getOperand(1)))
2311       if (Node->getValueType(0) == MVT::f64) {
2312         assert(cast<VTSDNode>(Node->getOperand(3))->getVT() == MVT::f32 &&
2313                "Bad EXTLOAD!");
2314         unsigned CPIdx = BB->getParent()->getConstantPool()->
2315           getConstantPoolIndex(CP->get(), 2);
2316
2317         addConstantPoolReference(BuildMI(BB, X86::FpLD32m, 4, Result), CPIdx);
2318         return Result;
2319       }
2320
2321     X86AddressMode AM;
2322     if (getRegPressure(Node->getOperand(0)) >
2323            getRegPressure(Node->getOperand(1))) {
2324       Select(Node->getOperand(0)); // chain
2325       SelectAddress(Node->getOperand(1), AM);
2326     } else {
2327       SelectAddress(Node->getOperand(1), AM);
2328       Select(Node->getOperand(0)); // chain
2329     }
2330
2331     switch (Node->getValueType(0)) {
2332     default: assert(0 && "Unknown type to sign extend to.");
2333     case MVT::f64:
2334       assert(cast<VTSDNode>(Node->getOperand(3))->getVT() == MVT::f32 &&
2335              "Bad EXTLOAD!");
2336       addFullAddress(BuildMI(BB, X86::FpLD32m, 5, Result), AM);
2337       break;
2338     case MVT::i32:
2339       switch (cast<VTSDNode>(Node->getOperand(3))->getVT()) {
2340       default:
2341         assert(0 && "Bad zero extend!");
2342       case MVT::i1:
2343       case MVT::i8:
2344         addFullAddress(BuildMI(BB, X86::MOVZX32rm8, 5, Result), AM);
2345         break;
2346       case MVT::i16:
2347         addFullAddress(BuildMI(BB, X86::MOVZX32rm16, 5, Result), AM);
2348         break;
2349       }
2350       break;
2351     case MVT::i16:
2352       assert(cast<VTSDNode>(Node->getOperand(3))->getVT() <= MVT::i8 &&
2353              "Bad zero extend!");
2354       addFullAddress(BuildMI(BB, X86::MOVZX16rm8, 5, Result), AM);
2355       break;
2356     case MVT::i8:
2357       assert(cast<VTSDNode>(Node->getOperand(3))->getVT() == MVT::i1 &&
2358              "Bad zero extend!");
2359       addFullAddress(BuildMI(BB, X86::MOV8rm, 5, Result), AM);
2360       break;
2361     }
2362     return Result;
2363   }
2364   case ISD::SEXTLOAD: {
2365     // Make sure we generate both values.
2366     if (Result != 1)
2367       ExprMap[N.getValue(1)] = 1;   // Generate the token
2368     else
2369       Result = ExprMap[N.getValue(0)] = MakeReg(N.getValue(0).getValueType());
2370
2371     X86AddressMode AM;
2372     if (getRegPressure(Node->getOperand(0)) >
2373            getRegPressure(Node->getOperand(1))) {
2374       Select(Node->getOperand(0)); // chain
2375       SelectAddress(Node->getOperand(1), AM);
2376     } else {
2377       SelectAddress(Node->getOperand(1), AM);
2378       Select(Node->getOperand(0)); // chain
2379     }
2380
2381     switch (Node->getValueType(0)) {
2382     case MVT::i8: assert(0 && "Cannot sign extend from bool!");
2383     default: assert(0 && "Unknown type to sign extend to.");
2384     case MVT::i32:
2385       switch (cast<VTSDNode>(Node->getOperand(3))->getVT()) {
2386       default:
2387       case MVT::i1: assert(0 && "Cannot sign extend from bool!");
2388       case MVT::i8:
2389         addFullAddress(BuildMI(BB, X86::MOVSX32rm8, 5, Result), AM);
2390         break;
2391       case MVT::i16:
2392         addFullAddress(BuildMI(BB, X86::MOVSX32rm16, 5, Result), AM);
2393         break;
2394       }
2395       break;
2396     case MVT::i16:
2397       assert(cast<VTSDNode>(Node->getOperand(3))->getVT() == MVT::i8 &&
2398              "Cannot sign extend from bool!");
2399       addFullAddress(BuildMI(BB, X86::MOVSX16rm8, 5, Result), AM);
2400       break;
2401     }
2402     return Result;
2403   }
2404
2405   case X86ISD::TAILCALL:
2406   case X86ISD::CALL: {
2407     // The chain for this call is now lowered.
2408     ExprMap.insert(std::make_pair(N.getValue(0), 1));
2409
2410     bool isDirect = isa<GlobalAddressSDNode>(N.getOperand(1)) ||
2411                     isa<ExternalSymbolSDNode>(N.getOperand(1));
2412     unsigned Callee = 0;
2413     if (isDirect) {
2414       Select(N.getOperand(0));
2415     } else {
2416       if (getRegPressure(N.getOperand(0)) > getRegPressure(N.getOperand(1))) {
2417         Select(N.getOperand(0));
2418         Callee = SelectExpr(N.getOperand(1));
2419       } else {
2420         Callee = SelectExpr(N.getOperand(1));
2421         Select(N.getOperand(0));
2422       }
2423     }
2424
2425     // If this call has values to pass in registers, do so now.
2426     if (Node->getNumOperands() > 4) {
2427       // The first value is passed in (a part of) EAX, the second in EDX.
2428       unsigned RegOp1 = SelectExpr(N.getOperand(4));
2429       unsigned RegOp2 =
2430         Node->getNumOperands() > 5 ? SelectExpr(N.getOperand(5)) : 0;
2431
2432       switch (N.getOperand(4).getValueType()) {
2433       default: assert(0 && "Bad thing to pass in regs");
2434       case MVT::i1:
2435       case MVT::i8:  BuildMI(BB, X86::MOV8rr , 1,X86::AL).addReg(RegOp1); break;
2436       case MVT::i16: BuildMI(BB, X86::MOV16rr, 1,X86::AX).addReg(RegOp1); break;
2437       case MVT::i32: BuildMI(BB, X86::MOV32rr, 1,X86::EAX).addReg(RegOp1);break;
2438       }
2439       if (RegOp2)
2440         switch (N.getOperand(5).getValueType()) {
2441         default: assert(0 && "Bad thing to pass in regs");
2442         case MVT::i1:
2443         case MVT::i8:
2444           BuildMI(BB, X86::MOV8rr , 1, X86::DL).addReg(RegOp2);
2445           break;
2446         case MVT::i16:
2447           BuildMI(BB, X86::MOV16rr, 1, X86::DX).addReg(RegOp2);
2448           break;
2449         case MVT::i32:
2450           BuildMI(BB, X86::MOV32rr, 1, X86::EDX).addReg(RegOp2);
2451           break;
2452         }
2453     }
2454
2455     if (GlobalAddressSDNode *GASD =
2456                dyn_cast<GlobalAddressSDNode>(N.getOperand(1))) {
2457       BuildMI(BB, X86::CALLpcrel32, 1).addGlobalAddress(GASD->getGlobal(),true);
2458     } else if (ExternalSymbolSDNode *ESSDN =
2459                dyn_cast<ExternalSymbolSDNode>(N.getOperand(1))) {
2460       BuildMI(BB, X86::CALLpcrel32,
2461               1).addExternalSymbol(ESSDN->getSymbol(), true);
2462     } else {
2463       if (getRegPressure(N.getOperand(0)) > getRegPressure(N.getOperand(1))) {
2464         Select(N.getOperand(0));
2465         Tmp1 = SelectExpr(N.getOperand(1));
2466       } else {
2467         Tmp1 = SelectExpr(N.getOperand(1));
2468         Select(N.getOperand(0));
2469       }
2470
2471       BuildMI(BB, X86::CALL32r, 1).addReg(Tmp1);
2472     }
2473
2474     // Get caller stack amount and amount the callee added to the stack pointer.
2475     Tmp1 = cast<ConstantSDNode>(N.getOperand(2))->getValue();
2476     Tmp2 = cast<ConstantSDNode>(N.getOperand(3))->getValue();
2477     BuildMI(BB, X86::ADJCALLSTACKUP, 2).addImm(Tmp1).addImm(Tmp2);
2478
2479     if (Node->getNumValues() != 1)
2480       switch (Node->getValueType(1)) {
2481       default: assert(0 && "Unknown value type for call result!");
2482       case MVT::Other: return 1;
2483       case MVT::i1:
2484       case MVT::i8:
2485         BuildMI(BB, X86::MOV8rr, 1, Result).addReg(X86::AL);
2486         break;
2487       case MVT::i16:
2488         BuildMI(BB, X86::MOV16rr, 1, Result).addReg(X86::AX);
2489         break;
2490       case MVT::i32:
2491         BuildMI(BB, X86::MOV32rr, 1, Result).addReg(X86::EAX);
2492         if (Node->getNumValues() == 3 && Node->getValueType(2) == MVT::i32)
2493           BuildMI(BB, X86::MOV32rr, 1, Result+1).addReg(X86::EDX);
2494         break;
2495       case MVT::f64:     // Floating-point return values live in %ST(0)
2496         if (X86ScalarSSE) {
2497           ContainsFPCode = true;
2498           BuildMI(BB, X86::FpGETRESULT, 1, X86::FP0);
2499
2500           unsigned Size = MVT::getSizeInBits(MVT::f64)/8;
2501           MachineFunction *F = BB->getParent();
2502           int FrameIdx = F->getFrameInfo()->CreateStackObject(Size, Size);
2503           addFrameReference(BuildMI(BB, X86::FpST64m, 5), FrameIdx).addReg(X86::FP0);
2504           addFrameReference(BuildMI(BB, X86::MOVSDrm, 4, Result), FrameIdx);
2505           break;
2506         } else {
2507           ContainsFPCode = true;
2508           BuildMI(BB, X86::FpGETRESULT, 1, Result);
2509           break;
2510         }
2511       }
2512     return Result+N.ResNo-1;
2513   }
2514   case ISD::READPORT:
2515     // First, determine that the size of the operand falls within the acceptable
2516     // range for this architecture.
2517     //
2518     if (Node->getOperand(1).getValueType() != MVT::i16) {
2519       std::cerr << "llvm.readport: Address size is not 16 bits\n";
2520       exit(1);
2521     }
2522
2523     // Make sure we generate both values.
2524     if (Result != 1) {  // Generate the token
2525       if (!ExprMap.insert(std::make_pair(N.getValue(1), 1)).second)
2526         assert(0 && "readport already emitted!?");
2527     } else
2528       Result = ExprMap[N.getValue(0)] = MakeReg(N.getValue(0).getValueType());
2529
2530     Select(Node->getOperand(0));  // Select the chain.
2531
2532     // If the port is a single-byte constant, use the immediate form.
2533     if (ConstantSDNode *Port = dyn_cast<ConstantSDNode>(Node->getOperand(1)))
2534       if ((Port->getValue() & 255) == Port->getValue()) {
2535         switch (Node->getValueType(0)) {
2536         case MVT::i8:
2537           BuildMI(BB, X86::IN8ri, 1).addImm(Port->getValue());
2538           BuildMI(BB, X86::MOV8rr, 1, Result).addReg(X86::AL);
2539           return Result;
2540         case MVT::i16:
2541           BuildMI(BB, X86::IN16ri, 1).addImm(Port->getValue());
2542           BuildMI(BB, X86::MOV16rr, 1, Result).addReg(X86::AX);
2543           return Result;
2544         case MVT::i32:
2545           BuildMI(BB, X86::IN32ri, 1).addImm(Port->getValue());
2546           BuildMI(BB, X86::MOV32rr, 1, Result).addReg(X86::EAX);
2547           return Result;
2548         default: break;
2549         }
2550       }
2551
2552     // Now, move the I/O port address into the DX register and use the IN
2553     // instruction to get the input data.
2554     //
2555     Tmp1 = SelectExpr(Node->getOperand(1));
2556     BuildMI(BB, X86::MOV16rr, 1, X86::DX).addReg(Tmp1);
2557     switch (Node->getValueType(0)) {
2558     case MVT::i8:
2559       BuildMI(BB, X86::IN8rr, 0);
2560       BuildMI(BB, X86::MOV8rr, 1, Result).addReg(X86::AL);
2561       return Result;
2562     case MVT::i16:
2563       BuildMI(BB, X86::IN16rr, 0);
2564       BuildMI(BB, X86::MOV16rr, 1, Result).addReg(X86::AX);
2565       return Result;
2566     case MVT::i32:
2567       BuildMI(BB, X86::IN32rr, 0);
2568       BuildMI(BB, X86::MOV32rr, 1, Result).addReg(X86::EAX);
2569       return Result;
2570     default:
2571       std::cerr << "Cannot do input on this data type";
2572       exit(1);
2573     }
2574
2575   }
2576
2577   return 0;
2578 }
2579
2580 /// TryToFoldLoadOpStore - Given a store node, try to fold together a
2581 /// load/op/store instruction.  If successful return true.
2582 bool ISel::TryToFoldLoadOpStore(SDNode *Node) {
2583   assert(Node->getOpcode() == ISD::STORE && "Can only do this for stores!");
2584   SDOperand Chain  = Node->getOperand(0);
2585   SDOperand StVal  = Node->getOperand(1);
2586   SDOperand StPtr  = Node->getOperand(2);
2587
2588   // The chain has to be a load, the stored value must be an integer binary
2589   // operation with one use.
2590   if (!StVal.Val->hasOneUse() || StVal.Val->getNumOperands() != 2 ||
2591       MVT::isFloatingPoint(StVal.getValueType()))
2592     return false;
2593
2594   // Token chain must either be a factor node or the load to fold.
2595   if (Chain.getOpcode() != ISD::LOAD && Chain.getOpcode() != ISD::TokenFactor)
2596     return false;
2597
2598   SDOperand TheLoad;
2599
2600   // Check to see if there is a load from the same pointer that we're storing
2601   // to in either operand of the binop.
2602   if (StVal.getOperand(0).getOpcode() == ISD::LOAD &&
2603       StVal.getOperand(0).getOperand(1) == StPtr)
2604     TheLoad = StVal.getOperand(0);
2605   else if (StVal.getOperand(1).getOpcode() == ISD::LOAD &&
2606            StVal.getOperand(1).getOperand(1) == StPtr)
2607     TheLoad = StVal.getOperand(1);
2608   else
2609     return false;  // No matching load operand.
2610
2611   // We can only fold the load if there are no intervening side-effecting
2612   // operations.  This means that the store uses the load as its token chain, or
2613   // there are only token factor nodes in between the store and load.
2614   if (Chain != TheLoad.getValue(1)) {
2615     // Okay, the other option is that we have a store referring to (possibly
2616     // nested) token factor nodes.  For now, just try peeking through one level
2617     // of token factors to see if this is the case.
2618     bool ChainOk = false;
2619     if (Chain.getOpcode() == ISD::TokenFactor) {
2620       for (unsigned i = 0, e = Chain.getNumOperands(); i != e; ++i)
2621         if (Chain.getOperand(i) == TheLoad.getValue(1)) {
2622           ChainOk = true;
2623           break;
2624         }
2625     }
2626
2627     if (!ChainOk) return false;
2628   }
2629
2630   if (TheLoad.getOperand(1) != StPtr)
2631     return false;
2632
2633   // Make sure that one of the operands of the binop is the load, and that the
2634   // load folds into the binop.
2635   if (((StVal.getOperand(0) != TheLoad ||
2636         !isFoldableLoad(TheLoad, StVal.getOperand(1))) &&
2637        (StVal.getOperand(1) != TheLoad ||
2638         !isFoldableLoad(TheLoad, StVal.getOperand(0)))))
2639     return false;
2640
2641   // Finally, check to see if this is one of the ops we can handle!
2642   static const unsigned ADDTAB[] = {
2643     X86::ADD8mi, X86::ADD16mi, X86::ADD32mi,
2644     X86::ADD8mr, X86::ADD16mr, X86::ADD32mr,
2645   };
2646   static const unsigned SUBTAB[] = {
2647     X86::SUB8mi, X86::SUB16mi, X86::SUB32mi,
2648     X86::SUB8mr, X86::SUB16mr, X86::SUB32mr,
2649   };
2650   static const unsigned ANDTAB[] = {
2651     X86::AND8mi, X86::AND16mi, X86::AND32mi,
2652     X86::AND8mr, X86::AND16mr, X86::AND32mr,
2653   };
2654   static const unsigned ORTAB[] = {
2655     X86::OR8mi, X86::OR16mi, X86::OR32mi,
2656     X86::OR8mr, X86::OR16mr, X86::OR32mr,
2657   };
2658   static const unsigned XORTAB[] = {
2659     X86::XOR8mi, X86::XOR16mi, X86::XOR32mi,
2660     X86::XOR8mr, X86::XOR16mr, X86::XOR32mr,
2661   };
2662   static const unsigned SHLTAB[] = {
2663     X86::SHL8mi, X86::SHL16mi, X86::SHL32mi,
2664     /*Have to put the reg in CL*/0, 0, 0,
2665   };
2666   static const unsigned SARTAB[] = {
2667     X86::SAR8mi, X86::SAR16mi, X86::SAR32mi,
2668     /*Have to put the reg in CL*/0, 0, 0,
2669   };
2670   static const unsigned SHRTAB[] = {
2671     X86::SHR8mi, X86::SHR16mi, X86::SHR32mi,
2672     /*Have to put the reg in CL*/0, 0, 0,
2673   };
2674
2675   const unsigned *TabPtr = 0;
2676   switch (StVal.getOpcode()) {
2677   default:
2678     std::cerr << "CANNOT [mem] op= val: ";
2679     StVal.Val->dump(); std::cerr << "\n";
2680   case ISD::FMUL:
2681   case ISD::MUL:
2682   case ISD::FDIV:
2683   case ISD::SDIV:
2684   case ISD::UDIV:
2685   case ISD::FREM:
2686   case ISD::SREM:
2687   case ISD::UREM: return false;
2688
2689   case ISD::ADD: TabPtr = ADDTAB; break;
2690   case ISD::SUB: TabPtr = SUBTAB; break;
2691   case ISD::AND: TabPtr = ANDTAB; break;
2692   case ISD:: OR: TabPtr =  ORTAB; break;
2693   case ISD::XOR: TabPtr = XORTAB; break;
2694   case ISD::SHL: TabPtr = SHLTAB; break;
2695   case ISD::SRA: TabPtr = SARTAB; break;
2696   case ISD::SRL: TabPtr = SHRTAB; break;
2697   }
2698
2699   // Handle: [mem] op= CST
2700   SDOperand Op0 = StVal.getOperand(0);
2701   SDOperand Op1 = StVal.getOperand(1);
2702   unsigned Opc = 0;
2703   if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(Op1)) {
2704     switch (Op0.getValueType()) { // Use Op0's type because of shifts.
2705     default: break;
2706     case MVT::i1:
2707     case MVT::i8:  Opc = TabPtr[0]; break;
2708     case MVT::i16: Opc = TabPtr[1]; break;
2709     case MVT::i32: Opc = TabPtr[2]; break;
2710     }
2711
2712     if (Opc) {
2713       if (!ExprMap.insert(std::make_pair(TheLoad.getValue(1), 1)).second)
2714         assert(0 && "Already emitted?");
2715       Select(Chain);
2716
2717       X86AddressMode AM;
2718       if (getRegPressure(TheLoad.getOperand(0)) >
2719           getRegPressure(TheLoad.getOperand(1))) {
2720         Select(TheLoad.getOperand(0));
2721         SelectAddress(TheLoad.getOperand(1), AM);
2722       } else {
2723         SelectAddress(TheLoad.getOperand(1), AM);
2724         Select(TheLoad.getOperand(0));
2725       }
2726
2727       if (StVal.getOpcode() == ISD::ADD) {
2728         if (CN->getValue() == 1) {
2729           switch (Op0.getValueType()) {
2730           default: break;
2731           case MVT::i8:
2732             addFullAddress(BuildMI(BB, X86::INC8m, 4), AM);
2733             return true;
2734           case MVT::i16: Opc = TabPtr[1];
2735             addFullAddress(BuildMI(BB, X86::INC16m, 4), AM);
2736             return true;
2737           case MVT::i32: Opc = TabPtr[2];
2738             addFullAddress(BuildMI(BB, X86::INC32m, 4), AM);
2739             return true;
2740           }
2741         } else if (CN->getValue()+1 == 0) {   // [X] += -1 -> DEC [X]
2742           switch (Op0.getValueType()) {
2743           default: break;
2744           case MVT::i8:
2745             addFullAddress(BuildMI(BB, X86::DEC8m, 4), AM);
2746             return true;
2747           case MVT::i16: Opc = TabPtr[1];
2748             addFullAddress(BuildMI(BB, X86::DEC16m, 4), AM);
2749             return true;
2750           case MVT::i32: Opc = TabPtr[2];
2751             addFullAddress(BuildMI(BB, X86::DEC32m, 4), AM);
2752             return true;
2753           }
2754         }
2755       }
2756
2757       addFullAddress(BuildMI(BB, Opc, 4+1),AM).addImm(CN->getValue());
2758       return true;
2759     }
2760   }
2761
2762   // If we have [mem] = V op [mem], try to turn it into:
2763   // [mem] = [mem] op V.
2764   if (Op1 == TheLoad && 
2765       StVal.getOpcode() != ISD::SUB && StVal.getOpcode() != ISD::FSUB &&
2766       StVal.getOpcode() != ISD::SHL && StVal.getOpcode() != ISD::SRA &&
2767       StVal.getOpcode() != ISD::SRL)
2768     std::swap(Op0, Op1);
2769
2770   if (Op0 != TheLoad) return false;
2771
2772   switch (Op0.getValueType()) {
2773   default: return false;
2774   case MVT::i1:
2775   case MVT::i8:  Opc = TabPtr[3]; break;
2776   case MVT::i16: Opc = TabPtr[4]; break;
2777   case MVT::i32: Opc = TabPtr[5]; break;
2778   }
2779
2780   // Table entry doesn't exist?
2781   if (Opc == 0) return false;
2782
2783   if (!ExprMap.insert(std::make_pair(TheLoad.getValue(1), 1)).second)
2784     assert(0 && "Already emitted?");
2785   Select(Chain);
2786   Select(TheLoad.getOperand(0));
2787
2788   X86AddressMode AM;
2789   SelectAddress(TheLoad.getOperand(1), AM);
2790   unsigned Reg = SelectExpr(Op1);
2791   addFullAddress(BuildMI(BB, Opc, 4+1), AM).addReg(Reg);
2792   return true;
2793 }
2794
2795 /// If node is a ret(tailcall) node, emit the specified tail call and return
2796 /// true, otherwise return false.
2797 ///
2798 /// FIXME: This whole thing should be a post-legalize optimization pass which
2799 /// recognizes and transforms the dag.  We don't want the selection phase doing
2800 /// this stuff!!
2801 ///
2802 bool ISel::EmitPotentialTailCall(SDNode *RetNode) {
2803   assert(RetNode->getOpcode() == ISD::RET && "Not a return");
2804
2805   SDOperand Chain = RetNode->getOperand(0);
2806
2807   // If this is a token factor node where one operand is a call, dig into it.
2808   SDOperand TokFactor;
2809   unsigned TokFactorOperand = 0;
2810   if (Chain.getOpcode() == ISD::TokenFactor) {
2811     for (unsigned i = 0, e = Chain.getNumOperands(); i != e; ++i)
2812       if (Chain.getOperand(i).getOpcode() == ISD::CALLSEQ_END ||
2813           Chain.getOperand(i).getOpcode() == X86ISD::TAILCALL) {
2814         TokFactorOperand = i;
2815         TokFactor = Chain;
2816         Chain = Chain.getOperand(i);
2817         break;
2818       }
2819     if (TokFactor.Val == 0) return false;  // No call operand.
2820   }
2821
2822   // Skip the CALLSEQ_END node if present.
2823   if (Chain.getOpcode() == ISD::CALLSEQ_END)
2824     Chain = Chain.getOperand(0);
2825
2826   // Is a tailcall the last control operation that occurs before the return?
2827   if (Chain.getOpcode() != X86ISD::TAILCALL)
2828     return false;
2829
2830   // If we return a value, is it the value produced by the call?
2831   if (RetNode->getNumOperands() > 1) {
2832     // Not returning the ret val of the call?
2833     if (Chain.Val->getNumValues() == 1 ||
2834         RetNode->getOperand(1) != Chain.getValue(1))
2835       return false;
2836
2837     if (RetNode->getNumOperands() > 2) {
2838       if (Chain.Val->getNumValues() == 2 ||
2839           RetNode->getOperand(2) != Chain.getValue(2))
2840         return false;
2841     }
2842     assert(RetNode->getNumOperands() <= 3);
2843   }
2844
2845   // CalleeCallArgAmt - The total number of bytes used for the callee arg area.
2846   // For FastCC, this will always be > 0.
2847   unsigned CalleeCallArgAmt =
2848     cast<ConstantSDNode>(Chain.getOperand(2))->getValue();
2849
2850   // CalleeCallArgPopAmt - The number of bytes in the call area popped by the
2851   // callee.  For FastCC this will always be > 0, for CCC this is always 0.
2852   unsigned CalleeCallArgPopAmt =
2853     cast<ConstantSDNode>(Chain.getOperand(3))->getValue();
2854
2855   // There are several cases we can handle here.  First, if the caller and
2856   // callee are both CCC functions, we can tailcall if the callee takes <= the
2857   // number of argument bytes that the caller does.
2858   if (CalleeCallArgPopAmt == 0 &&                  // Callee is C CallingConv?
2859       X86Lowering.getBytesToPopOnReturn() == 0) {  // Caller is C CallingConv?
2860     // Check to see if caller arg area size >= callee arg area size.
2861     if (X86Lowering.getBytesCallerReserves() >= CalleeCallArgAmt) {
2862       //std::cerr << "CCC TAILCALL UNIMP!\n";
2863       // If TokFactor is non-null, emit all operands.
2864
2865       //EmitCCCToCCCTailCall(Chain.Val);
2866       //return true;
2867     }
2868     return false;
2869   }
2870
2871   // Second, if both are FastCC functions, we can always perform the tail call.
2872   if (CalleeCallArgPopAmt && X86Lowering.getBytesToPopOnReturn()) {
2873     // If TokFactor is non-null, emit all operands before the call.
2874     if (TokFactor.Val) {
2875       for (unsigned i = 0, e = TokFactor.getNumOperands(); i != e; ++i)
2876         if (i != TokFactorOperand)
2877           Select(TokFactor.getOperand(i));
2878     }
2879
2880     EmitFastCCToFastCCTailCall(Chain.Val);
2881     return true;
2882   }
2883
2884   // We don't support mixed calls, due to issues with alignment.  We could in
2885   // theory handle some mixed calls from CCC -> FastCC if the stack is properly
2886   // aligned (which depends on the number of arguments to the callee).  TODO.
2887   return false;
2888 }
2889
2890 static SDOperand GetAdjustedArgumentStores(SDOperand Chain, int Offset,
2891                                            SelectionDAG &DAG) {
2892   MVT::ValueType StoreVT;
2893   switch (Chain.getOpcode()) {
2894   default: assert(0 && "Unexpected node!");
2895   case ISD::CALLSEQ_START:
2896     // If we found the start of the call sequence, we're done.  We actually
2897     // strip off the CALLSEQ_START node, to avoid generating the
2898     // ADJCALLSTACKDOWN marker for the tail call.
2899     return Chain.getOperand(0);
2900   case ISD::TokenFactor: {
2901     std::vector<SDOperand> Ops;
2902     Ops.reserve(Chain.getNumOperands());
2903     for (unsigned i = 0, e = Chain.getNumOperands(); i != e; ++i)
2904       Ops.push_back(GetAdjustedArgumentStores(Chain.getOperand(i), Offset,DAG));
2905     return DAG.getNode(ISD::TokenFactor, MVT::Other, Ops);
2906   }
2907   case ISD::STORE:       // Normal store
2908     StoreVT = Chain.getOperand(1).getValueType();
2909     break;
2910   case ISD::TRUNCSTORE:  // FLOAT store
2911     StoreVT = cast<VTSDNode>(Chain.getOperand(4))->getVT();
2912     break;
2913   }
2914
2915   SDOperand OrigDest = Chain.getOperand(2);
2916   unsigned OrigOffset;
2917
2918   if (OrigDest.getOpcode() == ISD::CopyFromReg) {
2919     OrigOffset = 0;
2920     assert(cast<RegisterSDNode>(OrigDest.getOperand(1))->getReg() == X86::ESP);
2921   } else if (OrigDest.getOpcode() == ISD::ADD &&
2922              isa<ConstantSDNode>(OrigDest.getOperand(1)) &&
2923              OrigDest.getOperand(0).getOpcode() == ISD::CopyFromReg &&
2924              cast<RegisterSDNode>(OrigDest.getOperand(0).getOperand(1))->getReg()
2925                    == X86::ESP) {
2926     // We expect only (ESP+C)
2927     OrigOffset = cast<ConstantSDNode>(OrigDest.getOperand(1))->getValue();
2928   } else if (OrigDest.getOpcode() == ISD::Register) {
2929     // We expect only (ESP+C)
2930     OrigOffset = 0;
2931   } else {
2932     assert(OrigDest.getOpcode() == ISD::ADD &&
2933            isa<ConstantSDNode>(OrigDest.getOperand(1)) &&
2934            OrigDest.getOperand(0).getOpcode() == ISD::Register &&
2935            cast<RegisterSDNode>(OrigDest.getOperand(0))->getReg() == X86::ESP);
2936     OrigOffset = cast<ConstantSDNode>(OrigDest.getOperand(1))->getValue();
2937   }
2938
2939   // Compute the new offset from the incoming ESP value we wish to use.
2940   unsigned NewOffset = OrigOffset + Offset;
2941
2942   unsigned OpSize = (MVT::getSizeInBits(StoreVT)+7)/8;  // Bits -> Bytes
2943   MachineFunction &MF = DAG.getMachineFunction();
2944   int FI = MF.getFrameInfo()->CreateFixedObject(OpSize, NewOffset);
2945   SDOperand FIN = DAG.getFrameIndex(FI, MVT::i32);
2946
2947   SDOperand InChain = GetAdjustedArgumentStores(Chain.getOperand(0), Offset,
2948                                                 DAG);
2949   if (Chain.getOpcode() == ISD::STORE)
2950     return DAG.getNode(ISD::STORE, MVT::Other, InChain, Chain.getOperand(1),
2951                        FIN);
2952   assert(Chain.getOpcode() == ISD::TRUNCSTORE);
2953   return DAG.getNode(ISD::TRUNCSTORE, MVT::Other, InChain, Chain.getOperand(1),
2954                      FIN, DAG.getSrcValue(NULL), DAG.getValueType(StoreVT));
2955 }
2956
2957
2958 /// EmitFastCCToFastCCTailCall - Given a tailcall in the tail position to a
2959 /// fastcc function from a fastcc function, emit the code to emit a 'proper'
2960 /// tail call.
2961 void ISel::EmitFastCCToFastCCTailCall(SDNode *TailCallNode) {
2962   unsigned CalleeCallArgSize =
2963     cast<ConstantSDNode>(TailCallNode->getOperand(2))->getValue();
2964   unsigned CallerArgSize = X86Lowering.getBytesToPopOnReturn();
2965
2966   //std::cerr << "****\n*** EMITTING TAIL CALL!\n****\n";
2967
2968   // Adjust argument stores.  Instead of storing to [ESP], f.e., store to frame
2969   // indexes that are relative to the incoming ESP.  If the incoming and
2970   // outgoing arg sizes are the same we will store to [InESP] instead of
2971   // [CurESP] and the ESP referenced will be relative to the incoming function
2972   // ESP.
2973   int ESPOffset = CallerArgSize-CalleeCallArgSize;
2974   SDOperand AdjustedArgStores =
2975     GetAdjustedArgumentStores(TailCallNode->getOperand(0), ESPOffset, *TheDAG);
2976
2977   // Copy the return address of the caller into a virtual register so we don't
2978   // clobber it.
2979   SDOperand RetVal(0, 0);
2980   if (ESPOffset) {
2981     SDOperand RetValAddr = X86Lowering.getReturnAddressFrameIndex(*TheDAG);
2982     RetVal = TheDAG->getLoad(MVT::i32, TheDAG->getEntryNode(),
2983                                        RetValAddr, TheDAG->getSrcValue(NULL));
2984     SelectExpr(RetVal);
2985   }
2986
2987   // Codegen all of the argument stores.
2988   Select(AdjustedArgStores);
2989
2990   if (RetVal.Val) {
2991     // Emit a store of the saved ret value to the new location.
2992     MachineFunction &MF = TheDAG->getMachineFunction();
2993     int ReturnAddrFI = MF.getFrameInfo()->CreateFixedObject(4, ESPOffset-4);
2994     SDOperand RetValAddr = TheDAG->getFrameIndex(ReturnAddrFI, MVT::i32);
2995     Select(TheDAG->getNode(ISD::STORE, MVT::Other, TheDAG->getEntryNode(),
2996                            RetVal, RetValAddr));
2997   }
2998
2999   // Get the destination value.
3000   SDOperand Callee = TailCallNode->getOperand(1);
3001   bool isDirect = isa<GlobalAddressSDNode>(Callee) ||
3002                   isa<ExternalSymbolSDNode>(Callee);
3003   unsigned CalleeReg = 0;
3004   if (!isDirect) {
3005     // If this is not a direct tail call, evaluate the callee's address.
3006     CalleeReg = SelectExpr(Callee);
3007   }
3008
3009   unsigned RegOp1 = 0;
3010   unsigned RegOp2 = 0;
3011
3012   if (TailCallNode->getNumOperands() > 4) {
3013     // The first value is passed in (a part of) EAX, the second in EDX.
3014     RegOp1 = SelectExpr(TailCallNode->getOperand(4));
3015     if (TailCallNode->getNumOperands() > 5)
3016       RegOp2 = SelectExpr(TailCallNode->getOperand(5));
3017
3018     switch (TailCallNode->getOperand(4).getValueType()) {
3019     default: assert(0 && "Bad thing to pass in regs");
3020     case MVT::i1:
3021     case MVT::i8:
3022       BuildMI(BB, X86::MOV8rr, 1, X86::AL).addReg(RegOp1);
3023       RegOp1 = X86::AL;
3024       break;
3025     case MVT::i16:
3026       BuildMI(BB, X86::MOV16rr, 1,X86::AX).addReg(RegOp1);
3027       RegOp1 = X86::AX;
3028       break;
3029     case MVT::i32:
3030       BuildMI(BB, X86::MOV32rr, 1,X86::EAX).addReg(RegOp1);
3031       RegOp1 = X86::EAX;
3032       break;
3033     }
3034     if (RegOp2)
3035       switch (TailCallNode->getOperand(5).getValueType()) {
3036       default: assert(0 && "Bad thing to pass in regs");
3037       case MVT::i1:
3038       case MVT::i8:
3039         BuildMI(BB, X86::MOV8rr, 1, X86::DL).addReg(RegOp2);
3040         RegOp2 = X86::DL;
3041         break;
3042       case MVT::i16:
3043         BuildMI(BB, X86::MOV16rr, 1, X86::DX).addReg(RegOp2);
3044         RegOp2 = X86::DX;
3045         break;
3046       case MVT::i32:
3047         BuildMI(BB, X86::MOV32rr, 1, X86::EDX).addReg(RegOp2);
3048         RegOp2 = X86::EDX;
3049         break;
3050       }
3051   }
3052   
3053   // If this is not a direct tail call, put the callee's address into ECX.
3054   // The address has to be evaluated into a non-callee save register that is
3055   // not used for arguments.  This means either ECX, as EAX and EDX may be
3056   // used for argument passing.  We do this here to make sure that the
3057   // expressions for arguments and callee are all evaluated before the copies
3058   // into physical registers.
3059   if (!isDirect)
3060     BuildMI(BB, X86::MOV32rr, 1, X86::ECX).addReg(CalleeReg);
3061
3062   // Adjust ESP.
3063   if (ESPOffset)
3064     BuildMI(BB, X86::ADJSTACKPTRri, 2,
3065             X86::ESP).addReg(X86::ESP).addImm(ESPOffset);
3066
3067   // TODO: handle jmp [mem]
3068   if (!isDirect) {
3069     BuildMI(BB, X86::TAILJMPr, 1).addReg(X86::ECX);
3070   } else if (GlobalAddressSDNode *GASD = dyn_cast<GlobalAddressSDNode>(Callee)){
3071     BuildMI(BB, X86::TAILJMPd, 1).addGlobalAddress(GASD->getGlobal(), true);
3072   } else {
3073     ExternalSymbolSDNode *ESSDN = cast<ExternalSymbolSDNode>(Callee);
3074     BuildMI(BB, X86::TAILJMPd, 1).addExternalSymbol(ESSDN->getSymbol(), true);
3075   }
3076   // ADD IMPLICIT USE RegOp1/RegOp2's
3077 }
3078
3079
3080 void ISel::Select(SDOperand N) {
3081   unsigned Tmp1 = 0, Tmp2 = 0, Opc = 0;
3082
3083   if (!ExprMap.insert(std::make_pair(N, 1)).second)
3084     return;  // Already selected.
3085
3086   SDNode *Node = N.Val;
3087
3088   switch (Node->getOpcode()) {
3089   default:
3090     Node->dump(); std::cerr << "\n";
3091     assert(0 && "Node not handled yet!");
3092   case X86ISD::RDTSC_DAG:
3093     Select(Node->getOperand(0)); //Chain
3094     BuildMI(BB, X86::RDTSC, 0);
3095     return;
3096
3097   case ISD::EntryToken: return;  // Noop
3098   case ISD::TokenFactor:
3099     if (Node->getNumOperands() == 2) {
3100       bool OneFirst =
3101         getRegPressure(Node->getOperand(1))>getRegPressure(Node->getOperand(0));
3102       Select(Node->getOperand(OneFirst));
3103       Select(Node->getOperand(!OneFirst));
3104     } else {
3105       std::vector<std::pair<unsigned, unsigned> > OpsP;
3106       for (unsigned i = 0, e = Node->getNumOperands(); i != e; ++i)
3107         OpsP.push_back(std::make_pair(getRegPressure(Node->getOperand(i)), i));
3108       std::sort(OpsP.begin(), OpsP.end());
3109       std::reverse(OpsP.begin(), OpsP.end());
3110       for (unsigned i = 0, e = Node->getNumOperands(); i != e; ++i)
3111         Select(Node->getOperand(OpsP[i].second));
3112     }
3113     return;
3114   case ISD::CopyToReg:
3115     if (getRegPressure(N.getOperand(0)) > getRegPressure(N.getOperand(2))) {
3116       Select(N.getOperand(0));
3117       Tmp1 = SelectExpr(N.getOperand(2));
3118     } else {
3119       Tmp1 = SelectExpr(N.getOperand(2));
3120       Select(N.getOperand(0));
3121     }
3122     Tmp2 = cast<RegisterSDNode>(N.getOperand(1))->getReg();
3123
3124     if (Tmp1 != Tmp2) {
3125       switch (N.getOperand(2).getValueType()) {
3126       default: assert(0 && "Invalid type for operation!");
3127       case MVT::i1:
3128       case MVT::i8:  Opc = X86::MOV8rr; break;
3129       case MVT::i16: Opc = X86::MOV16rr; break;
3130       case MVT::i32: Opc = X86::MOV32rr; break;
3131       case MVT::f32: Opc = X86::MOVSSrr; break;
3132       case MVT::f64:
3133         if (X86ScalarSSE) {
3134           Opc = X86::MOVSDrr;
3135         } else {
3136           Opc = X86::FpMOV;
3137           ContainsFPCode = true;
3138         }
3139         break;
3140       }
3141       BuildMI(BB, Opc, 1, Tmp2).addReg(Tmp1);
3142     }
3143     return;
3144   case ISD::RET:
3145     if (N.getOperand(0).getOpcode() == ISD::CALLSEQ_END ||
3146         N.getOperand(0).getOpcode() == X86ISD::TAILCALL ||
3147         N.getOperand(0).getOpcode() == ISD::TokenFactor)
3148       if (EmitPotentialTailCall(Node))
3149         return;
3150
3151     switch (N.getNumOperands()) {
3152     default:
3153       assert(0 && "Unknown return instruction!");
3154     case 3:
3155       assert(N.getOperand(1).getValueType() == MVT::i32 &&
3156              N.getOperand(2).getValueType() == MVT::i32 &&
3157              "Unknown two-register value!");
3158       if (getRegPressure(N.getOperand(1)) > getRegPressure(N.getOperand(2))) {
3159         Tmp1 = SelectExpr(N.getOperand(1));
3160         Tmp2 = SelectExpr(N.getOperand(2));
3161       } else {
3162         Tmp2 = SelectExpr(N.getOperand(2));
3163         Tmp1 = SelectExpr(N.getOperand(1));
3164       }
3165       Select(N.getOperand(0));
3166
3167       BuildMI(BB, X86::MOV32rr, 1, X86::EAX).addReg(Tmp1);
3168       BuildMI(BB, X86::MOV32rr, 1, X86::EDX).addReg(Tmp2);
3169       break;
3170     case 2:
3171       if (getRegPressure(N.getOperand(0)) > getRegPressure(N.getOperand(1))) {
3172         Select(N.getOperand(0));
3173         Tmp1 = SelectExpr(N.getOperand(1));
3174       } else {
3175         Tmp1 = SelectExpr(N.getOperand(1));
3176         Select(N.getOperand(0));
3177       }
3178       switch (N.getOperand(1).getValueType()) {
3179       default: assert(0 && "All other types should have been promoted!!");
3180       case MVT::f32:
3181         if (X86ScalarSSE) {
3182           // Spill the value to memory and reload it into top of stack.
3183           unsigned Size = MVT::getSizeInBits(MVT::f32)/8;
3184           MachineFunction *F = BB->getParent();
3185           int FrameIdx = F->getFrameInfo()->CreateStackObject(Size, Size);
3186           addFrameReference(BuildMI(BB, X86::MOVSSmr, 5), FrameIdx).addReg(Tmp1);
3187           addFrameReference(BuildMI(BB, X86::FpLD32m, 4, X86::FP0), FrameIdx);
3188           BuildMI(BB, X86::FpSETRESULT, 1).addReg(X86::FP0);
3189           ContainsFPCode = true;
3190         } else {
3191           assert(0 && "MVT::f32 only legal with scalar sse fp");
3192           abort();
3193         }
3194         break;
3195       case MVT::f64:
3196         if (X86ScalarSSE) {
3197           // Spill the value to memory and reload it into top of stack.
3198           unsigned Size = MVT::getSizeInBits(MVT::f64)/8;
3199           MachineFunction *F = BB->getParent();
3200           int FrameIdx = F->getFrameInfo()->CreateStackObject(Size, Size);
3201           addFrameReference(BuildMI(BB, X86::MOVSDmr, 5), FrameIdx).addReg(Tmp1);
3202           addFrameReference(BuildMI(BB, X86::FpLD64m, 4, X86::FP0), FrameIdx);
3203           BuildMI(BB, X86::FpSETRESULT, 1).addReg(X86::FP0);
3204           ContainsFPCode = true;
3205         } else {
3206           BuildMI(BB, X86::FpSETRESULT, 1).addReg(Tmp1);
3207         }
3208         break;
3209       case MVT::i32:
3210         BuildMI(BB, X86::MOV32rr, 1, X86::EAX).addReg(Tmp1);
3211         break;
3212       }
3213       break;
3214     case 1:
3215       Select(N.getOperand(0));
3216       break;
3217     }
3218     if (X86Lowering.getBytesToPopOnReturn() == 0)
3219       BuildMI(BB, X86::RET, 0); // Just emit a 'ret' instruction
3220     else
3221       BuildMI(BB, X86::RETI, 1).addImm(X86Lowering.getBytesToPopOnReturn());
3222     return;
3223   case ISD::BR: {
3224     Select(N.getOperand(0));
3225     MachineBasicBlock *Dest =
3226       cast<BasicBlockSDNode>(N.getOperand(1))->getBasicBlock();
3227     BuildMI(BB, X86::JMP, 1).addMBB(Dest);
3228     return;
3229   }
3230
3231   case ISD::BRCOND: {
3232     MachineBasicBlock *Dest =
3233       cast<BasicBlockSDNode>(N.getOperand(2))->getBasicBlock();
3234
3235     // Try to fold a setcc into the branch.  If this fails, emit a test/jne
3236     // pair.
3237     if (EmitBranchCC(Dest, N.getOperand(0), N.getOperand(1))) {
3238       if (getRegPressure(N.getOperand(0)) > getRegPressure(N.getOperand(1))) {
3239         Select(N.getOperand(0));
3240         Tmp1 = SelectExpr(N.getOperand(1));
3241       } else {
3242         Tmp1 = SelectExpr(N.getOperand(1));
3243         Select(N.getOperand(0));
3244       }
3245       BuildMI(BB, X86::TEST8rr, 2).addReg(Tmp1).addReg(Tmp1);
3246       BuildMI(BB, X86::JNE, 1).addMBB(Dest);
3247     }
3248
3249     return;
3250   }
3251
3252   case ISD::LOAD:
3253     // If this load could be folded into the only using instruction, and if it
3254     // is safe to emit the instruction here, try to do so now.
3255     if (Node->hasNUsesOfValue(1, 0)) {
3256       SDOperand TheVal = N.getValue(0);
3257       SDNode *User = 0;
3258       for (SDNode::use_iterator UI = Node->use_begin(); ; ++UI) {
3259         assert(UI != Node->use_end() && "Didn't find use!");
3260         SDNode *UN = *UI;
3261         for (unsigned i = 0, e = UN->getNumOperands(); i != e; ++i)
3262           if (UN->getOperand(i) == TheVal) {
3263             User = UN;
3264             goto FoundIt;
3265           }
3266       }
3267     FoundIt:
3268       // Only handle unary operators right now.
3269       if (User->getNumOperands() == 1) {
3270         ExprMap.erase(N);
3271         SelectExpr(SDOperand(User, 0));
3272         return;
3273       }
3274     }
3275     ExprMap.erase(N);
3276     SelectExpr(N);
3277     return;
3278   case ISD::READPORT:
3279   case ISD::EXTLOAD:
3280   case ISD::SEXTLOAD:
3281   case ISD::ZEXTLOAD:
3282   case X86ISD::TAILCALL:
3283   case X86ISD::CALL:
3284     ExprMap.erase(N);
3285     SelectExpr(N);
3286     return;
3287   case ISD::CopyFromReg:
3288   case X86ISD::FILD:
3289     ExprMap.erase(N);
3290     SelectExpr(N.getValue(0));
3291     return;
3292
3293   case X86ISD::FP_TO_INT16_IN_MEM:
3294   case X86ISD::FP_TO_INT32_IN_MEM:
3295   case X86ISD::FP_TO_INT64_IN_MEM: {
3296     assert(N.getOperand(1).getValueType() == MVT::f64);
3297     X86AddressMode AM;
3298     Select(N.getOperand(0));   // Select the token chain
3299
3300     unsigned ValReg;
3301     if (getRegPressure(N.getOperand(1)) > getRegPressure(N.getOperand(2))) {
3302       ValReg = SelectExpr(N.getOperand(1));
3303       SelectAddress(N.getOperand(2), AM);
3304      } else {
3305        SelectAddress(N.getOperand(2), AM);
3306        ValReg = SelectExpr(N.getOperand(1));
3307      }
3308
3309     // Change the floating point control register to use "round towards zero"
3310     // mode when truncating to an integer value.
3311     //
3312     MachineFunction *F = BB->getParent();
3313     int CWFrameIdx = F->getFrameInfo()->CreateStackObject(2, 2);
3314     addFrameReference(BuildMI(BB, X86::FNSTCW16m, 4), CWFrameIdx);
3315
3316     // Load the old value of the high byte of the control word...
3317     unsigned OldCW = MakeReg(MVT::i16);
3318     addFrameReference(BuildMI(BB, X86::MOV16rm, 4, OldCW), CWFrameIdx);
3319
3320     // Set the high part to be round to zero...
3321     addFrameReference(BuildMI(BB, X86::MOV16mi, 5), CWFrameIdx).addImm(0xC7F);
3322
3323     // Reload the modified control word now...
3324     addFrameReference(BuildMI(BB, X86::FLDCW16m, 4), CWFrameIdx);
3325
3326     // Restore the memory image of control word to original value
3327     addFrameReference(BuildMI(BB, X86::MOV16mr, 5), CWFrameIdx).addReg(OldCW);
3328
3329     // Get the X86 opcode to use.
3330     switch (N.getOpcode()) {
3331     case X86ISD::FP_TO_INT16_IN_MEM: Tmp1 = X86::FpIST16m; break;
3332     case X86ISD::FP_TO_INT32_IN_MEM: Tmp1 = X86::FpIST32m; break;
3333     case X86ISD::FP_TO_INT64_IN_MEM: Tmp1 = X86::FpIST64m; break;
3334     }
3335
3336     addFullAddress(BuildMI(BB, Tmp1, 5), AM).addReg(ValReg);
3337
3338     // Reload the original control word now.
3339     addFrameReference(BuildMI(BB, X86::FLDCW16m, 4), CWFrameIdx);
3340     return;
3341   }
3342
3343   case ISD::TRUNCSTORE: {  // truncstore chain, val, ptr, SRCVALUE, storety
3344     X86AddressMode AM;
3345     MVT::ValueType StoredTy = cast<VTSDNode>(N.getOperand(4))->getVT();
3346     assert((StoredTy == MVT::i1 || StoredTy == MVT::f32 ||
3347             StoredTy == MVT::i16 /*FIXME: THIS IS JUST FOR TESTING!*/)
3348            && "Unsupported TRUNCSTORE for this target!");
3349
3350     if (StoredTy == MVT::i16) {
3351       // FIXME: This is here just to allow testing.  X86 doesn't really have a
3352       // TRUNCSTORE i16 operation, but this is required for targets that do not
3353       // have 16-bit integer registers.  We occasionally disable 16-bit integer
3354       // registers to test the promotion code.
3355       Select(N.getOperand(0));
3356       Tmp1 = SelectExpr(N.getOperand(1));
3357       SelectAddress(N.getOperand(2), AM);
3358
3359       BuildMI(BB, X86::MOV32rr, 1, X86::EAX).addReg(Tmp1);
3360       addFullAddress(BuildMI(BB, X86::MOV16mr, 5), AM).addReg(X86::AX);
3361       return;
3362     }
3363
3364     // Store of constant bool?
3365     if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N.getOperand(1))) {
3366       if (getRegPressure(N.getOperand(0)) > getRegPressure(N.getOperand(2))) {
3367         Select(N.getOperand(0));
3368         SelectAddress(N.getOperand(2), AM);
3369       } else {
3370         SelectAddress(N.getOperand(2), AM);
3371         Select(N.getOperand(0));
3372       }
3373       addFullAddress(BuildMI(BB, X86::MOV8mi, 5), AM).addImm(CN->getValue());
3374       return;
3375     }
3376
3377     switch (StoredTy) {
3378     default: assert(0 && "Cannot truncstore this type!");
3379     case MVT::i1: Opc = X86::MOV8mr; break;
3380     case MVT::f32:
3381       assert(!X86ScalarSSE && "Cannot truncstore scalar SSE regs");
3382       Opc = X86::FpST32m; break;
3383     }
3384
3385     std::vector<std::pair<unsigned, unsigned> > RP;
3386     RP.push_back(std::make_pair(getRegPressure(N.getOperand(0)), 0));
3387     RP.push_back(std::make_pair(getRegPressure(N.getOperand(1)), 1));
3388     RP.push_back(std::make_pair(getRegPressure(N.getOperand(2)), 2));
3389     std::sort(RP.begin(), RP.end());
3390
3391     Tmp1 = 0;   // Silence a warning.
3392     for (unsigned i = 0; i != 3; ++i)
3393       switch (RP[2-i].second) {
3394       default: assert(0 && "Unknown operand number!");
3395       case 0: Select(N.getOperand(0)); break;
3396       case 1: Tmp1 = SelectExpr(N.getOperand(1)); break;
3397       case 2: SelectAddress(N.getOperand(2), AM); break;
3398       }
3399
3400     addFullAddress(BuildMI(BB, Opc, 4+1), AM).addReg(Tmp1);
3401     return;
3402   }
3403   case ISD::STORE: {
3404     X86AddressMode AM;
3405
3406     if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N.getOperand(1))) {
3407       Opc = 0;
3408       switch (CN->getValueType(0)) {
3409       default: assert(0 && "Invalid type for operation!");
3410       case MVT::i1:
3411       case MVT::i8:  Opc = X86::MOV8mi; break;
3412       case MVT::i16: Opc = X86::MOV16mi; break;
3413       case MVT::i32: Opc = X86::MOV32mi; break;
3414       }
3415       if (Opc) {
3416         if (getRegPressure(N.getOperand(0)) > getRegPressure(N.getOperand(2))) {
3417           Select(N.getOperand(0));
3418           SelectAddress(N.getOperand(2), AM);
3419         } else {
3420           SelectAddress(N.getOperand(2), AM);
3421           Select(N.getOperand(0));
3422         }
3423         addFullAddress(BuildMI(BB, Opc, 4+1), AM).addImm(CN->getValue());
3424         return;
3425       }
3426     } else if (GlobalAddressSDNode *GA =
3427                       dyn_cast<GlobalAddressSDNode>(N.getOperand(1))) {
3428       assert(GA->getValueType(0) == MVT::i32 && "Bad pointer operand");
3429
3430       if (getRegPressure(N.getOperand(0)) > getRegPressure(N.getOperand(2))) {
3431         Select(N.getOperand(0));
3432         SelectAddress(N.getOperand(2), AM);
3433       } else {
3434         SelectAddress(N.getOperand(2), AM);
3435         Select(N.getOperand(0));
3436       }
3437       GlobalValue *GV = GA->getGlobal();
3438       // For Darwin, external and weak symbols are indirect, so we want to load
3439       // the value at address GV, not the value of GV itself.
3440       if (Subtarget->getIndirectExternAndWeakGlobals() &&
3441           (GV->hasWeakLinkage() || GV->isExternal())) {
3442         Tmp1 = MakeReg(MVT::i32);
3443         BuildMI(BB, X86::MOV32rm, 4, Tmp1).addReg(0).addZImm(1).addReg(0)
3444           .addGlobalAddress(GV, false, 0);
3445         addFullAddress(BuildMI(BB, X86::MOV32mr, 4+1),AM).addReg(Tmp1);
3446       } else {
3447         addFullAddress(BuildMI(BB, X86::MOV32mi, 4+1),AM).addGlobalAddress(GV);
3448       }
3449       return;
3450     }
3451
3452     // Check to see if this is a load/op/store combination.
3453     if (TryToFoldLoadOpStore(Node))
3454       return;
3455
3456     switch (N.getOperand(1).getValueType()) {
3457     default: assert(0 && "Cannot store this type!");
3458     case MVT::i1:
3459     case MVT::i8:  Opc = X86::MOV8mr; break;
3460     case MVT::i16: Opc = X86::MOV16mr; break;
3461     case MVT::i32: Opc = X86::MOV32mr; break;
3462     case MVT::f32: Opc = X86::MOVSSmr; break;
3463     case MVT::f64: Opc = X86ScalarSSE ? X86::MOVSDmr : X86::FpST64m; break;
3464     }
3465
3466     std::vector<std::pair<unsigned, unsigned> > RP;
3467     RP.push_back(std::make_pair(getRegPressure(N.getOperand(0)), 0));
3468     RP.push_back(std::make_pair(getRegPressure(N.getOperand(1)), 1));
3469     RP.push_back(std::make_pair(getRegPressure(N.getOperand(2)), 2));
3470     std::sort(RP.begin(), RP.end());
3471
3472     Tmp1 = 0; // Silence a warning.
3473     for (unsigned i = 0; i != 3; ++i)
3474       switch (RP[2-i].second) {
3475       default: assert(0 && "Unknown operand number!");
3476       case 0: Select(N.getOperand(0)); break;
3477       case 1: Tmp1 = SelectExpr(N.getOperand(1)); break;
3478       case 2: SelectAddress(N.getOperand(2), AM); break;
3479       }
3480
3481     addFullAddress(BuildMI(BB, Opc, 4+1), AM).addReg(Tmp1);
3482     return;
3483   }
3484   case ISD::CALLSEQ_START:
3485     Select(N.getOperand(0));
3486     // Stack amount
3487     Tmp1 = cast<ConstantSDNode>(N.getOperand(1))->getValue();
3488     BuildMI(BB, X86::ADJCALLSTACKDOWN, 1).addImm(Tmp1);
3489     return;
3490   case ISD::CALLSEQ_END:
3491     Select(N.getOperand(0));
3492     return;
3493   case ISD::MEMSET: {
3494     Select(N.getOperand(0));  // Select the chain.
3495     unsigned Align =
3496       (unsigned)cast<ConstantSDNode>(Node->getOperand(4))->getValue();
3497     if (Align == 0) Align = 1;
3498
3499     // Turn the byte code into # iterations
3500     unsigned CountReg;
3501     unsigned Opcode;
3502     if (ConstantSDNode *ValC = dyn_cast<ConstantSDNode>(Node->getOperand(2))) {
3503       unsigned Val = ValC->getValue() & 255;
3504
3505       // If the value is a constant, then we can potentially use larger sets.
3506       switch (Align & 3) {
3507       case 2:   // WORD aligned
3508         CountReg = MakeReg(MVT::i32);
3509         if (ConstantSDNode *I = dyn_cast<ConstantSDNode>(Node->getOperand(3))) {
3510           BuildMI(BB, X86::MOV32ri, 1, CountReg).addImm(I->getValue()/2);
3511         } else {
3512           unsigned ByteReg = SelectExpr(Node->getOperand(3));
3513           BuildMI(BB, X86::SHR32ri, 2, CountReg).addReg(ByteReg).addImm(1);
3514         }
3515         BuildMI(BB, X86::MOV16ri, 1, X86::AX).addImm((Val << 8) | Val);
3516         Opcode = X86::REP_STOSW;
3517         break;
3518       case 0:   // DWORD aligned
3519         CountReg = MakeReg(MVT::i32);
3520         if (ConstantSDNode *I = dyn_cast<ConstantSDNode>(Node->getOperand(3))) {
3521           BuildMI(BB, X86::MOV32ri, 1, CountReg).addImm(I->getValue()/4);
3522         } else {
3523           unsigned ByteReg = SelectExpr(Node->getOperand(3));
3524           BuildMI(BB, X86::SHR32ri, 2, CountReg).addReg(ByteReg).addImm(2);
3525         }
3526         Val = (Val << 8) | Val;
3527         BuildMI(BB, X86::MOV32ri, 1, X86::EAX).addImm((Val << 16) | Val);
3528         Opcode = X86::REP_STOSD;
3529         break;
3530       default:  // BYTE aligned
3531         CountReg = SelectExpr(Node->getOperand(3));
3532         BuildMI(BB, X86::MOV8ri, 1, X86::AL).addImm(Val);
3533         Opcode = X86::REP_STOSB;
3534         break;
3535       }
3536     } else {
3537       // If it's not a constant value we are storing, just fall back.  We could
3538       // try to be clever to form 16 bit and 32 bit values, but we don't yet.
3539       unsigned ValReg = SelectExpr(Node->getOperand(2));
3540       BuildMI(BB, X86::MOV8rr, 1, X86::AL).addReg(ValReg);
3541       CountReg = SelectExpr(Node->getOperand(3));
3542       Opcode = X86::REP_STOSB;
3543     }
3544
3545     // No matter what the alignment is, we put the destination in EDI, and the
3546     // count in ECX.
3547     unsigned TmpReg1 = SelectExpr(Node->getOperand(1));
3548     BuildMI(BB, X86::MOV32rr, 1, X86::ECX).addReg(CountReg);
3549     BuildMI(BB, X86::MOV32rr, 1, X86::EDI).addReg(TmpReg1);
3550     BuildMI(BB, Opcode, 0);
3551     return;
3552   }
3553   case ISD::MEMCPY: {
3554     Select(N.getOperand(0));  // Select the chain.
3555     unsigned Align =
3556       (unsigned)cast<ConstantSDNode>(Node->getOperand(4))->getValue();
3557     if (Align == 0) Align = 1;
3558
3559     // Turn the byte code into # iterations
3560     unsigned CountReg;
3561     unsigned Opcode;
3562     switch (Align & 3) {
3563     case 2:   // WORD aligned
3564       CountReg = MakeReg(MVT::i32);
3565       if (ConstantSDNode *I = dyn_cast<ConstantSDNode>(Node->getOperand(3))) {
3566         BuildMI(BB, X86::MOV32ri, 1, CountReg).addImm(I->getValue()/2);
3567       } else {
3568         unsigned ByteReg = SelectExpr(Node->getOperand(3));
3569         BuildMI(BB, X86::SHR32ri, 2, CountReg).addReg(ByteReg).addImm(1);
3570       }
3571       Opcode = X86::REP_MOVSW;
3572       break;
3573     case 0:   // DWORD aligned
3574       CountReg = MakeReg(MVT::i32);
3575       if (ConstantSDNode *I = dyn_cast<ConstantSDNode>(Node->getOperand(3))) {
3576         BuildMI(BB, X86::MOV32ri, 1, CountReg).addImm(I->getValue()/4);
3577       } else {
3578         unsigned ByteReg = SelectExpr(Node->getOperand(3));
3579         BuildMI(BB, X86::SHR32ri, 2, CountReg).addReg(ByteReg).addImm(2);
3580       }
3581       Opcode = X86::REP_MOVSD;
3582       break;
3583     default:  // BYTE aligned
3584       CountReg = SelectExpr(Node->getOperand(3));
3585       Opcode = X86::REP_MOVSB;
3586       break;
3587     }
3588
3589     // No matter what the alignment is, we put the source in ESI, the
3590     // destination in EDI, and the count in ECX.
3591     unsigned TmpReg1 = SelectExpr(Node->getOperand(1));
3592     unsigned TmpReg2 = SelectExpr(Node->getOperand(2));
3593     BuildMI(BB, X86::MOV32rr, 1, X86::ECX).addReg(CountReg);
3594     BuildMI(BB, X86::MOV32rr, 1, X86::EDI).addReg(TmpReg1);
3595     BuildMI(BB, X86::MOV32rr, 1, X86::ESI).addReg(TmpReg2);
3596     BuildMI(BB, Opcode, 0);
3597     return;
3598   }
3599   case ISD::WRITEPORT:
3600     if (Node->getOperand(2).getValueType() != MVT::i16) {
3601       std::cerr << "llvm.writeport: Address size is not 16 bits\n";
3602       exit(1);
3603     }
3604     Select(Node->getOperand(0)); // Emit the chain.
3605
3606     Tmp1 = SelectExpr(Node->getOperand(1));
3607     switch (Node->getOperand(1).getValueType()) {
3608     case MVT::i8:
3609       BuildMI(BB, X86::MOV8rr, 1, X86::AL).addReg(Tmp1);
3610       Tmp2 = X86::OUT8ir;  Opc = X86::OUT8rr;
3611       break;
3612     case MVT::i16:
3613       BuildMI(BB, X86::MOV16rr, 1, X86::AX).addReg(Tmp1);
3614       Tmp2 = X86::OUT16ir; Opc = X86::OUT16rr;
3615       break;
3616     case MVT::i32:
3617       BuildMI(BB, X86::MOV32rr, 1, X86::EAX).addReg(Tmp1);
3618       Tmp2 = X86::OUT32ir; Opc = X86::OUT32rr;
3619       break;
3620     default:
3621       std::cerr << "llvm.writeport: invalid data type for X86 target";
3622       exit(1);
3623     }
3624
3625     // If the port is a single-byte constant, use the immediate form.
3626     if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(Node->getOperand(2)))
3627       if ((CN->getValue() & 255) == CN->getValue()) {
3628         BuildMI(BB, Tmp2, 1).addImm(CN->getValue());
3629         return;
3630       }
3631
3632     // Otherwise, move the I/O port address into the DX register.
3633     unsigned Reg = SelectExpr(Node->getOperand(2));
3634     BuildMI(BB, X86::MOV16rr, 1, X86::DX).addReg(Reg);
3635     BuildMI(BB, Opc, 0);
3636     return;
3637   }
3638   assert(0 && "Should not be reached!");
3639 }
3640
3641
3642 /// createX86ISelPattern - This pass converts an LLVM function
3643 /// into a machine code representation using pattern matching and a machine
3644 /// description file.
3645 ///
3646 FunctionPass *llvm::createX86ISelPattern(TargetMachine &TM) {
3647   return new ISel(TM);
3648 }