Implement casts from unsigned integers to floating point
[oota-llvm.git] / lib / Target / X86 / X86ISelSimple.cpp
index f14923beddc1b9e7feaf8ef77dd7e0c554f3bbb3..7d231e92966369d56856423990ac1fb63164b4fa 100644 (file)
@@ -17,6 +17,7 @@
 #include "llvm/DerivedTypes.h"
 #include "llvm/Constants.h"
 #include "llvm/Pass.h"
+#include "llvm/Intrinsics.h"
 #include "llvm/CodeGen/MachineFunction.h"
 #include "llvm/CodeGen/MachineInstrBuilder.h"
 #include "llvm/CodeGen/SSARegMap.h"
@@ -28,8 +29,8 @@
 #include <map>
 
 /// BMI - A special BuildMI variant that takes an iterator to insert the
-/// instruction at as well as a basic block.
-/// this is the version for when you have a destination register in mind.
+/// instruction at as well as a basic block.  This is the version for when you
+/// have a destination register in mind.
 inline static MachineInstrBuilder BMI(MachineBasicBlock *MBB,
                                       MachineBasicBlock::iterator &I,
                                       MachineOpCode Opcode,
@@ -47,7 +48,7 @@ inline static MachineInstrBuilder BMI(MachineBasicBlock *MBB,
                                       MachineBasicBlock::iterator &I,
                                       MachineOpCode Opcode,
                                       unsigned NumOperands) {
-  assert(I > MBB->begin() && I <= MBB->end() && "Bad iterator!");
+  assert(I >= MBB->begin() && I <= MBB->end() && "Bad iterator!");
   MachineInstr *MI = new MachineInstr(Opcode, NumOperands, true, true);
   I = MBB->insert(I, MI)+1;
   return MachineInstrBuilder(MI);
@@ -57,8 +58,9 @@ inline static MachineInstrBuilder BMI(MachineBasicBlock *MBB,
 namespace {
   struct ISel : public FunctionPass, InstVisitor<ISel> {
     TargetMachine &TM;
-    MachineFunction *F;                    // The function we are compiling into
-    MachineBasicBlock *BB;                 // The current MBB we are compiling
+    MachineFunction *F;                 // The function we are compiling into
+    MachineBasicBlock *BB;              // The current MBB we are compiling
+    int VarArgsFrameIndex;              // FrameIndex for start of varargs area
 
     std::map<Value*, unsigned> RegMap;  // Mapping between Val's and SSA Regs
 
@@ -78,6 +80,8 @@ namespace {
         F->getBasicBlockList().push_back(MBBMap[I] = new MachineBasicBlock(I));
 
       BB = &F->front();
+
+      // Copy incoming arguments off of the stack...
       LoadArgumentsToVirtualRegs(Fn);
 
       // Instruction select everything except PHI nodes
@@ -132,6 +136,7 @@ namespace {
     void doCall(const ValueRecord &Ret, MachineInstr *CallMI,
                const std::vector<ValueRecord> &Args);
     void visitCallInst(CallInst &I);
+    void visitIntrinsicCall(LLVMIntrinsic::ID ID, CallInst &I);
 
     // Arithmetic operators
     void visitSimpleBinary(BinaryOperator &B, unsigned OpcodeClass);
@@ -171,6 +176,7 @@ namespace {
     void visitShiftInst(ShiftInst &I);
     void visitPHINode(PHINode &I) {}      // PHI nodes handled by second pass
     void visitCastInst(CastInst &I);
+    void visitVarArgInst(VarArgInst &I);
 
     void visitInstruction(Instruction &I) {
       std::cerr << "Cannot instruction select: " << I;
@@ -192,6 +198,18 @@ namespace {
                           Value *Src, User::op_iterator IdxBegin,
                           User::op_iterator IdxEnd, unsigned TargetReg);
 
+    /// emitCastOperation - Common code shared between visitCastInst and
+    /// constant expression cast support.
+    void emitCastOperation(MachineBasicBlock *BB,MachineBasicBlock::iterator&IP,
+                           Value *Src, const Type *DestTy, unsigned TargetReg);
+
+    /// emitSimpleBinaryOperation - Common code shared between visitSimpleBinary
+    /// and constant expression support.
+    void emitSimpleBinaryOperation(MachineBasicBlock *BB,
+                                   MachineBasicBlock::iterator &IP,
+                                   Value *Op0, Value *Op1,
+                                   unsigned OperatorClass, unsigned TargetReg);
+
     /// copyConstantToRegister - Output the instructions required to put the
     /// specified constant into the specified register.
     ///
@@ -303,14 +321,29 @@ void ISel::copyConstantToRegister(MachineBasicBlock *MBB,
                                   MachineBasicBlock::iterator &IP,
                                   Constant *C, unsigned R) {
   if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
-    if (CE->getOpcode() == Instruction::GetElementPtr) {
+    unsigned Class = 0;
+    switch (CE->getOpcode()) {
+    case Instruction::GetElementPtr:
       emitGEPOperation(MBB, IP, CE->getOperand(0),
                        CE->op_begin()+1, CE->op_end(), R);
       return;
-    }
+    case Instruction::Cast:
+      emitCastOperation(MBB, IP, CE->getOperand(0), CE->getType(), R);
+      return;
+
+    case Instruction::Xor: ++Class; // FALL THROUGH
+    case Instruction::Or:  ++Class; // FALL THROUGH
+    case Instruction::And: ++Class; // FALL THROUGH
+    case Instruction::Sub: ++Class; // FALL THROUGH
+    case Instruction::Add:
+      emitSimpleBinaryOperation(MBB, IP, CE->getOperand(0), CE->getOperand(1),
+                                Class, R);
+      return;
 
-    std::cerr << "Offending expr: " << C << "\n";
-    assert(0 && "Constant expressions not yet handled!\n");
+    default:
+      std::cerr << "Offending expr: " << C << "\n";
+      assert(0 && "Constant expressions not yet handled!\n");
+    }
   }
 
   if (C->getType()->isIntegral()) {
@@ -424,6 +457,12 @@ void ISel::LoadArgumentsToVirtualRegs(Function &Fn) {
     }
     ArgOffset += 4;  // Each argument takes at least 4 bytes on the stack...
   }
+
+  // If the function takes variable number of arguments, add a frame offset for
+  // the start of the first vararg value... this is used to expand
+  // llvm.va_start.
+  if (Fn.getFunctionType()->isVarArg())
+    VarArgsFrameIndex = MFI->CreateFixedObject(1, ArgOffset);
 }
 
 
@@ -441,7 +480,7 @@ void ISel::SelectPHINodes() {
     // Loop over all of the PHI nodes in the LLVM basic block...
     unsigned NumPHIs = 0;
     for (BasicBlock::const_iterator I = BB->begin();
-         PHINode *PN = (PHINode*)dyn_cast<PHINode>(&*I); ++I) {
+         PHINode *PN = (PHINode*)dyn_cast<PHINode>(I); ++I) {
 
       // Create a new machine instr PHI node, and insert it.
       unsigned PHIReg = getReg(*PN);
@@ -454,18 +493,38 @@ void ISel::SelectPHINodes() {
        MBB->insert(MBB->begin()+NumPHIs++, LongPhiMI);
       }
 
+      // PHIValues - Map of blocks to incoming virtual registers.  We use this
+      // so that we only initialize one incoming value for a particular block,
+      // even if the block has multiple entries in the PHI node.
+      //
+      std::map<MachineBasicBlock*, unsigned> PHIValues;
+
       for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
         MachineBasicBlock *PredMBB = MBBMap[PN->getIncomingBlock(i)];
+        unsigned ValReg;
+        std::map<MachineBasicBlock*, unsigned>::iterator EntryIt =
+          PHIValues.lower_bound(PredMBB);
+
+        if (EntryIt != PHIValues.end() && EntryIt->first == PredMBB) {
+          // We already inserted an initialization of the register for this
+          // predecessor.  Recycle it.
+          ValReg = EntryIt->second;
+
+        } else {        
+          // Get the incoming value into a virtual register.  If it is not
+          // already available in a virtual register, insert the computation
+          // code into PredMBB
+          //
+          MachineBasicBlock::iterator PI = PredMBB->end();
+          while (PI != PredMBB->begin() &&
+                 TII.isTerminatorInstr((*(PI-1))->getOpcode()))
+            --PI;
+          ValReg = getReg(PN->getIncomingValue(i), PredMBB, PI);
+
+          // Remember that we inserted a value for this PHI for this predecessor
+          PHIValues.insert(EntryIt, std::make_pair(PredMBB, ValReg));
+        }
 
-        // Get the incoming value into a virtual register.  If it is not already
-        // available in a virtual register, insert the computation code into
-        // PredMBB
-        //
-       MachineBasicBlock::iterator PI = PredMBB->end();
-       while (PI != PredMBB->begin() &&
-              TII.isTerminatorInstr((*(PI-1))->getOpcode()))
-         --PI;
-       unsigned ValReg = getReg(PN->getIncomingValue(i), PredMBB, PI);
        PhiMI->addRegOperand(ValReg);
         PhiMI->addMachineBasicBlockOperand(PredMBB);
        if (LongPhiMI) {
@@ -504,9 +563,9 @@ static unsigned getSetCCNumber(unsigned Opcode) {
   case Instruction::SetEQ: return 0;
   case Instruction::SetNE: return 1;
   case Instruction::SetLT: return 2;
-  case Instruction::SetGT: return 3;
-  case Instruction::SetLE: return 4;
-  case Instruction::SetGE: return 5;
+  case Instruction::SetGE: return 3;
+  case Instruction::SetGT: return 4;
+  case Instruction::SetLE: return 5;
   }
 }
 
@@ -515,12 +574,12 @@ static unsigned getSetCCNumber(unsigned Opcode) {
 // seteq -> sete        sete
 // setne -> setne       setne
 // setlt -> setl        setb
+// setge -> setge       setae
 // setgt -> setg        seta
 // setle -> setle       setbe
-// setge -> setge       setae
 static const unsigned SetCCOpcodeTab[2][6] = {
-  {X86::SETEr, X86::SETNEr, X86::SETBr, X86::SETAr, X86::SETBEr, X86::SETAEr},
-  {X86::SETEr, X86::SETNEr, X86::SETLr, X86::SETGr, X86::SETLEr, X86::SETGEr},
+  {X86::SETEr, X86::SETNEr, X86::SETBr, X86::SETAEr, X86::SETAr, X86::SETBEr},
+  {X86::SETEr, X86::SETNEr, X86::SETLr, X86::SETGEr, X86::SETGr, X86::SETLEr},
 };
 
 bool ISel::EmitComparisonGetSignedness(unsigned OpNum, Value *Op0, Value *Op1) {
@@ -663,13 +722,19 @@ void ISel::visitReturnInst(ReturnInst &I) {
   case cShort:
   case cInt:
     promote32(X86::EAX, ValueRecord(RetReg, RetVal->getType()));
+    // Declare that EAX is live on exit
+    BuildMI(BB, X86::IMPLICIT_USE, 2).addReg(X86::EAX).addReg(X86::ESP);
     break;
   case cFP:                   // Floats & Doubles: Return in ST(0)
     BuildMI(BB, X86::FpSETRESULT, 1).addReg(RetReg);
+    // Declare that top-of-stack is live on exit
+    BuildMI(BB, X86::IMPLICIT_USE, 2).addReg(X86::ST0).addReg(X86::ESP);
     break;
   case cLong:
     BuildMI(BB, X86::MOVrr32, 1, X86::EAX).addReg(RetReg);
     BuildMI(BB, X86::MOVrr32, 1, X86::EDX).addReg(RetReg+1);
+    // Declare that EAX & EDX are live on exit
+    BuildMI(BB, X86::IMPLICIT_USE, 3).addReg(X86::EAX).addReg(X86::EDX).addReg(X86::ESP);
     break;
   default:
     visitInstruction(I);
@@ -678,14 +743,24 @@ void ISel::visitReturnInst(ReturnInst &I) {
   BuildMI(BB, X86::RET, 0);
 }
 
+// getBlockAfter - Return the basic block which occurs lexically after the
+// specified one.
+static inline BasicBlock *getBlockAfter(BasicBlock *BB) {
+  Function::iterator I = BB; ++I;  // Get iterator to next block
+  return I != BB->getParent()->end() ? &*I : 0;
+}
+
 /// visitBranchInst - Handle conditional and unconditional branches here.  Note
 /// that since code layout is frozen at this point, that if we are trying to
 /// jump to a block that is the immediate successor of the current block, we can
 /// just make a fall-through (but we don't currently).
 ///
 void ISel::visitBranchInst(BranchInst &BI) {
-  if (!BI.isConditional()) {
-    BuildMI(BB, X86::JMP, 1).addPCDisp(BI.getSuccessor(0));
+  BasicBlock *NextBB = getBlockAfter(BI.getParent());  // BB after current one
+
+  if (!BI.isConditional()) {  // Unconditional branch?
+    if (BI.getSuccessor(0) != NextBB)
+      BuildMI(BB, X86::JMP, 1).addPCDisp(BI.getSuccessor(0));
     return;
   }
 
@@ -696,8 +771,15 @@ void ISel::visitBranchInst(BranchInst &BI) {
     // computed some other way...
     unsigned condReg = getReg(BI.getCondition());
     BuildMI(BB, X86::CMPri8, 2).addReg(condReg).addZImm(0);
-    BuildMI(BB, X86::JE, 1).addPCDisp(BI.getSuccessor(1));
-    BuildMI(BB, X86::JMP, 1).addPCDisp(BI.getSuccessor(0));
+    if (BI.getSuccessor(1) == NextBB) {
+      if (BI.getSuccessor(0) != NextBB)
+        BuildMI(BB, X86::JNE, 1).addPCDisp(BI.getSuccessor(0));
+    } else {
+      BuildMI(BB, X86::JE, 1).addPCDisp(BI.getSuccessor(1));
+      
+      if (BI.getSuccessor(0) != NextBB)
+        BuildMI(BB, X86::JMP, 1).addPCDisp(BI.getSuccessor(0));
+    }
     return;
   }
 
@@ -710,16 +792,25 @@ void ISel::visitBranchInst(BranchInst &BI) {
   // seteq -> je          je
   // setne -> jne         jne
   // setlt -> jl          jb
+  // setge -> jge         jae
   // setgt -> jg          ja
   // setle -> jle         jbe
-  // setge -> jge         jae
   static const unsigned OpcodeTab[2][6] = {
-    { X86::JE, X86::JNE, X86::JB, X86::JA, X86::JBE, X86::JAE },
-    { X86::JE, X86::JNE, X86::JL, X86::JG, X86::JLE, X86::JGE },
+    { X86::JE, X86::JNE, X86::JB, X86::JAE, X86::JA, X86::JBE },
+    { X86::JE, X86::JNE, X86::JL, X86::JGE, X86::JG, X86::JLE },
   };
   
-  BuildMI(BB, OpcodeTab[isSigned][OpNum], 1).addPCDisp(BI.getSuccessor(0));
-  BuildMI(BB, X86::JMP, 1).addPCDisp(BI.getSuccessor(1));
+  if (BI.getSuccessor(0) != NextBB) {
+    BuildMI(BB, OpcodeTab[isSigned][OpNum], 1).addPCDisp(BI.getSuccessor(0));
+    if (BI.getSuccessor(1) != NextBB)
+      BuildMI(BB, X86::JMP, 1).addPCDisp(BI.getSuccessor(1));
+  } else {
+    // Change to the inverse condition...
+    if (BI.getSuccessor(1) != NextBB) {
+      OpNum ^= 1;
+      BuildMI(BB, OpcodeTab[isSigned][OpNum], 1).addPCDisp(BI.getSuccessor(1));
+    }
+  }
 }
 
 
@@ -834,6 +925,12 @@ void ISel::doCall(const ValueRecord &Ret, MachineInstr *CallMI,
 void ISel::visitCallInst(CallInst &CI) {
   MachineInstr *TheCall;
   if (Function *F = CI.getCalledFunction()) {
+    // Is it an intrinsic function call?
+    if (LLVMIntrinsic::ID ID = (LLVMIntrinsic::ID)F->getIntrinsicID()) {
+      visitIntrinsicCall(ID, CI);   // Special intrinsics are not handled here
+      return;
+    }
+
     // Emit a CALL instruction with PC-relative displacement.
     TheCall = BuildMI(X86::CALLpcrel32, 1).addGlobalAddress(F, true);
   } else {  // Emit an indirect call...
@@ -850,13 +947,50 @@ void ISel::visitCallInst(CallInst &CI) {
   doCall(ValueRecord(DestReg, CI.getType()), TheCall, Args);
 }       
 
+void ISel::visitIntrinsicCall(LLVMIntrinsic::ID ID, CallInst &CI) {
+  unsigned TmpReg1, TmpReg2;
+  switch (ID) {
+  case LLVMIntrinsic::va_start:
+    // Get the address of the first vararg value...
+    TmpReg1 = makeAnotherReg(Type::UIntTy);
+    addFrameReference(BuildMI(BB, X86::LEAr32, 5, TmpReg1), VarArgsFrameIndex);
+    TmpReg2 = getReg(CI.getOperand(1));
+    addDirectMem(BuildMI(BB, X86::MOVrm32, 5), TmpReg2).addReg(TmpReg1);
+    return;
+
+  case LLVMIntrinsic::va_end: return;   // Noop on X86
+  case LLVMIntrinsic::va_copy:
+    TmpReg1 = getReg(CI.getOperand(2));  // Get existing va_list
+    TmpReg2 = getReg(CI.getOperand(1));  // Get va_list* to store into
+    addDirectMem(BuildMI(BB, X86::MOVrm32, 5), TmpReg2).addReg(TmpReg1);
+    return;
+
+  default: assert(0 && "Unknown intrinsic for X86!");
+  }
+}
+
+
+/// visitSimpleBinary - Implement simple binary operators for integral types...
+/// OperatorClass is one of: 0 for Add, 1 for Sub, 2 for And, 3 for Or, 4 for
+/// Xor.
+void ISel::visitSimpleBinary(BinaryOperator &B, unsigned OperatorClass) {
+  unsigned DestReg = getReg(B);
+  MachineBasicBlock::iterator MI = BB->end();
+  emitSimpleBinaryOperation(BB, MI, B.getOperand(0), B.getOperand(1),
+                            OperatorClass, DestReg);
+}
 
 /// visitSimpleBinary - Implement simple binary operators for integral types...
 /// OperatorClass is one of: 0 for Add, 1 for Sub, 2 for And, 3 for Or,
 /// 4 for Xor.
 ///
-void ISel::visitSimpleBinary(BinaryOperator &B, unsigned OperatorClass) {
-  unsigned Class = getClassB(B.getType());
+/// emitSimpleBinaryOperation - Common code shared between visitSimpleBinary
+/// and constant expression support.
+void ISel::emitSimpleBinaryOperation(MachineBasicBlock *BB,
+                                     MachineBasicBlock::iterator &IP,
+                                     Value *Op0, Value *Op1,
+                                     unsigned OperatorClass,unsigned TargetReg){
+  unsigned Class = getClassB(Op0->getType());
 
   static const unsigned OpcodeTab[][4] = {
     // Arithmetic operators
@@ -877,17 +1011,16 @@ void ISel::visitSimpleBinary(BinaryOperator &B, unsigned OperatorClass) {
   
   unsigned Opcode = OpcodeTab[OperatorClass][Class];
   assert(Opcode && "Floating point arguments to logical inst?");
-  unsigned Op0r = getReg(B.getOperand(0));
-  unsigned Op1r = getReg(B.getOperand(1));
-  unsigned DestReg = getReg(B);
-  BuildMI(BB, Opcode, 2, DestReg).addReg(Op0r).addReg(Op1r);
+  unsigned Op0r = getReg(Op0, BB, IP);
+  unsigned Op1r = getReg(Op1, BB, IP);
+  BMI(BB, IP, Opcode, 2, TargetReg).addReg(Op0r).addReg(Op1r);
 
   if (isLong) {        // Handle the upper 32 bits of long values...
     static const unsigned TopTab[] = {
       X86::ADCrr32, X86::SBBrr32, X86::ANDrr32, X86::ORrr32, X86::XORrr32
     };
-    BuildMI(BB, TopTab[OperatorClass], 2,
-           DestReg+1).addReg(Op0r+1).addReg(Op1r+1);
+    BMI(BB, IP, TopTab[OperatorClass], 2,
+        TargetReg+1).addReg(Op0r+1).addReg(Op1r+1);
   }
 }
 
@@ -1178,7 +1311,7 @@ void ISel::EmitByteSwap(unsigned DestReg, unsigned SrcReg, unsigned Class) {
   // Emit the byte swap instruction...
   switch (Class) {
   case cByte:
-    // No byteswap neccesary for 8 bit value...
+    // No byteswap necessary for 8 bit value...
     BuildMI(BB, X86::MOVrr8, 1, DestReg).addReg(SrcReg);
     break;
   case cInt:
@@ -1188,7 +1321,7 @@ void ISel::EmitByteSwap(unsigned DestReg, unsigned SrcReg, unsigned Class) {
     
   case cShort:
     // For 16 bit we have to use an xchg instruction, because there is no
-    // 16-bit bswap.  XCHG is neccesarily not in SSA form, so we force things
+    // 16-bit bswap.  XCHG is necessarily not in SSA form, so we force things
     // into AX to do the xchg.
     //
     BuildMI(BB, X86::MOVrr16, 1, X86::AX).addReg(SrcReg);
@@ -1356,22 +1489,30 @@ void ISel::visitStoreInst(StoreInst &I) {
 /// visitCastInst - Here we have various kinds of copying with or without
 /// sign extension going on.
 void ISel::visitCastInst(CastInst &CI) {
-  const Type *DestTy = CI.getType();
-  Value *Src = CI.getOperand(0);
-  unsigned SrcReg = getReg(Src);
+  unsigned DestReg = getReg(CI);
+  MachineBasicBlock::iterator MI = BB->end();
+  emitCastOperation(BB, MI, CI.getOperand(0), CI.getType(), DestReg);
+}
+
+/// emitCastOperation - Common code shared between visitCastInst and
+/// constant expression cast support.
+void ISel::emitCastOperation(MachineBasicBlock *BB,
+                             MachineBasicBlock::iterator &IP,
+                             Value *Src, const Type *DestTy,
+                             unsigned DestReg) {
+  unsigned SrcReg = getReg(Src, BB, IP);
   const Type *SrcTy = Src->getType();
   unsigned SrcClass = getClassB(SrcTy);
-  unsigned DestReg = getReg(CI);
   unsigned DestClass = getClassB(DestTy);
 
   // Implement casts to bool by using compare on the operand followed by set if
   // not zero on the result.
   if (DestTy == Type::BoolTy) {
     if (SrcClass == cFP || SrcClass == cLong)
-      visitInstruction(CI);
+      abort();  // FIXME: implement cast (long & FP) to bool
     
-    BuildMI(BB, X86::CMPri8, 2).addReg(SrcReg).addZImm(0);
-    BuildMI(BB, X86::SETNEr, 1, DestReg);
+    BMI(BB, IP, X86::CMPri8, 2).addReg(SrcReg).addZImm(0);
+    BMI(BB, IP, X86::SETNEr, 1, DestReg);
     return;
   }
 
@@ -1383,11 +1524,11 @@ void ISel::visitCastInst(CastInst &CI) {
   // getClass) by using a register-to-register move.
   if (SrcClass == DestClass) {
     if (SrcClass <= cInt || (SrcClass == cFP && SrcTy == DestTy)) {
-      BuildMI(BB, RegRegMove[SrcClass], 1, DestReg).addReg(SrcReg);
+      BMI(BB, IP, RegRegMove[SrcClass], 1, DestReg).addReg(SrcReg);
     } else if (SrcClass == cFP) {
       if (SrcTy == Type::FloatTy) {  // double -> float
        assert(DestTy == Type::DoubleTy && "Unknown cFP member!");
-       BuildMI(BB, X86::FpMOV, 1, DestReg).addReg(SrcReg);
+       BMI(BB, IP, X86::FpMOV, 1, DestReg).addReg(SrcReg);
       } else {                       // float -> double
        assert(SrcTy == Type::DoubleTy && DestTy == Type::FloatTy &&
               "Unknown cFP member!");
@@ -1395,14 +1536,15 @@ void ISel::visitCastInst(CastInst &CI) {
        // reading it back.
        unsigned FltAlign = TM.getTargetData().getFloatAlignment();
         int FrameIdx = F->getFrameInfo()->CreateStackObject(4, FltAlign);
-       addFrameReference(BuildMI(BB, X86::FSTr32, 5), FrameIdx).addReg(SrcReg);
-       addFrameReference(BuildMI(BB, X86::FLDr32, 5, DestReg), FrameIdx);
+       addFrameReference(BMI(BB, IP, X86::FSTr32, 5), FrameIdx).addReg(SrcReg);
+       addFrameReference(BMI(BB, IP, X86::FLDr32, 5, DestReg), FrameIdx);
       }
     } else if (SrcClass == cLong) {
-      BuildMI(BB, X86::MOVrr32, 1, DestReg).addReg(SrcReg);
-      BuildMI(BB, X86::MOVrr32, 1, DestReg+1).addReg(SrcReg+1);
+      BMI(BB, IP, X86::MOVrr32, 1, DestReg).addReg(SrcReg);
+      BMI(BB, IP, X86::MOVrr32, 1, DestReg+1).addReg(SrcReg+1);
     } else {
-      visitInstruction(CI);
+      assert(0 && "Cannot handle this type of cast instruction!");
+      abort();
     }
     return;
   }
@@ -1420,21 +1562,21 @@ void ISel::visitCastInst(CastInst &CI) {
     };
     
     bool isUnsigned = SrcTy->isUnsigned();
-    BuildMI(BB, Opc[isUnsigned][SrcClass + DestClass - 1], 1,
-            DestReg).addReg(SrcReg);
+    BMI(BB, IP, Opc[isUnsigned][SrcClass + DestClass - 1], 1,
+        DestReg).addReg(SrcReg);
 
     if (isLong) {  // Handle upper 32 bits as appropriate...
       if (isUnsigned)     // Zero out top bits...
-       BuildMI(BB, X86::MOVir32, 1, DestReg+1).addZImm(0);
+       BMI(BB, IP, X86::MOVir32, 1, DestReg+1).addZImm(0);
       else                // Sign extend bottom half...
-       BuildMI(BB, X86::SARir32, 2, DestReg+1).addReg(DestReg).addZImm(31);
+       BMI(BB, IP, X86::SARir32, 2, DestReg+1).addReg(DestReg).addZImm(31);
     }
     return;
   }
 
   // Special case long -> int ...
   if (SrcClass == cLong && DestClass == cInt) {
-    BuildMI(BB, X86::MOVrr32, 1, DestReg).addReg(SrcReg);
+    BMI(BB, IP, X86::MOVrr32, 1, DestReg).addReg(SrcReg);
     return;
   }
   
@@ -1443,8 +1585,8 @@ void ISel::visitCastInst(CastInst &CI) {
   if ((SrcClass <= cInt || SrcClass == cLong) && DestClass <= cInt
       && SrcClass > DestClass) {
     static const unsigned AReg[] = { X86::AL, X86::AX, X86::EAX, 0, X86::EAX };
-    BuildMI(BB, RegRegMove[SrcClass], 1, AReg[SrcClass]).addReg(SrcReg);
-    BuildMI(BB, RegRegMove[DestClass], 1, DestReg).addReg(AReg[DestClass]);
+    BMI(BB, IP, RegRegMove[SrcClass], 1, AReg[SrcClass]).addReg(SrcReg);
+    BMI(BB, IP, RegRegMove[DestClass], 1, DestReg).addReg(AReg[DestClass]);
     return;
   }
 
@@ -1452,17 +1594,55 @@ void ISel::visitCastInst(CastInst &CI) {
   if (DestClass == cFP) {
     // unsigned int -> load as 64 bit int.
     // unsigned long long -> more complex
-    if (SrcTy->isUnsigned() && SrcTy != Type::UByteTy)
-      visitInstruction(CI);  // don't handle unsigned src yet!
-
-    // We don't have the facilities for directly loading byte sized data from
-    // memory.  Promote it to 16 bits.
-    if (SrcClass == cByte) {
-      unsigned TmpReg = makeAnotherReg(Type::ShortTy);
-      BuildMI(BB, SrcTy->isSigned() ? X86::MOVSXr16r8 : X86::MOVZXr16r8,
-             1, TmpReg).addReg(SrcReg);
-      SrcTy = Type::ShortTy;     // Pretend the short is our input now!
-      SrcClass = cShort;
+    if (SrcTy->isUnsigned() && SrcTy != Type::UByteTy) {
+      assert(0 && "Cannot handle this type of cast!");
+      abort();  // don't handle unsigned src yet!
+    }
+
+    // Promote the integer to a type supported by FLD.  We do this because there
+    // are no unsigned FLD instructions, so we must promote an unsigned value to
+    // a larger signed value, then use FLD on the larger value.
+    //
+    const Type *PromoteType = 0;
+    unsigned PromoteOpcode;
+    switch (SrcTy->getPrimitiveID()) {
+    case Type::BoolTyID:
+    case Type::SByteTyID:
+      // We don't have the facilities for directly loading byte sized data from
+      // memory (even signed).  Promote it to 16 bits.
+      PromoteType = Type::ShortTy;
+      PromoteOpcode = X86::MOVSXr16r8;
+      break;
+    case Type::UByteTyID:
+      PromoteType = Type::ShortTy;
+      PromoteOpcode = X86::MOVZXr16r8;
+      break;
+    case Type::UShortTyID:
+      PromoteType = Type::IntTy;
+      PromoteOpcode = X86::MOVZXr32r16;
+      break;
+    case Type::UIntTyID: {
+      // Make a 64 bit temporary... and zero out the top of it...
+      unsigned TmpReg = makeAnotherReg(Type::LongTy);
+      BMI(BB, IP, X86::MOVrr32, 1, TmpReg).addReg(SrcReg);
+      BMI(BB, IP, X86::MOVir32, 1, TmpReg+1).addZImm(0);
+      SrcTy = Type::LongTy;
+      SrcClass = cLong;
+      SrcReg = TmpReg;
+      break;
+    }
+    case Type::ULongTyID:
+      assert("FIXME: not implemented: cast ulong X to fp type!");
+    default:  // No promotion needed...
+      break;
+    }
+    
+    if (PromoteType) {
+      unsigned TmpReg = makeAnotherReg(PromoteType);
+      BMI(BB, IP, SrcTy->isSigned() ? X86::MOVSXr16r8 : X86::MOVZXr16r8,
+          1, TmpReg).addReg(SrcReg);
+      SrcTy = PromoteType;
+      SrcClass = getClass(PromoteType);
       SrcReg = TmpReg;
     }
 
@@ -1471,18 +1651,17 @@ void ISel::visitCastInst(CastInst &CI) {
       F->getFrameInfo()->CreateStackObject(SrcTy, TM.getTargetData());
 
     if (SrcClass == cLong) {
-      if (SrcTy == Type::ULongTy) visitInstruction(CI);
-      addFrameReference(BuildMI(BB, X86::MOVrm32, 5), FrameIdx).addReg(SrcReg);
-      addFrameReference(BuildMI(BB, X86::MOVrm32, 5),
+      addFrameReference(BMI(BB, IP, X86::MOVrm32, 5), FrameIdx).addReg(SrcReg);
+      addFrameReference(BMI(BB, IP, X86::MOVrm32, 5),
                        FrameIdx, 4).addReg(SrcReg+1);
     } else {
       static const unsigned Op1[] = { X86::MOVrm8, X86::MOVrm16, X86::MOVrm32 };
-      addFrameReference(BuildMI(BB, Op1[SrcClass], 5), FrameIdx).addReg(SrcReg);
+      addFrameReference(BMI(BB, IP, Op1[SrcClass], 5), FrameIdx).addReg(SrcReg);
     }
 
     static const unsigned Op2[] =
-      { 0, X86::FILDr16, X86::FILDr32, 0, X86::FILDr64 };
-    addFrameReference(BuildMI(BB, Op2[SrcClass], 5, DestReg), FrameIdx);
+      { 0/*byte*/, X86::FILDr16, X86::FILDr32, 0/*FP*/, X86::FILDr64 };
+    addFrameReference(BMI(BB, IP, Op2[SrcClass], 5, DestReg), FrameIdx);
     return;
   }
 
@@ -1492,20 +1671,20 @@ void ISel::visitCastInst(CastInst &CI) {
     // mode when truncating to an integer value.
     //
     int CWFrameIdx = F->getFrameInfo()->CreateStackObject(2, 2);
-    addFrameReference(BuildMI(BB, X86::FNSTCWm16, 4), CWFrameIdx);
+    addFrameReference(BMI(BB, IP, X86::FNSTCWm16, 4), CWFrameIdx);
 
     // Load the old value of the high byte of the control word...
     unsigned HighPartOfCW = makeAnotherReg(Type::UByteTy);
-    addFrameReference(BuildMI(BB, X86::MOVmr8, 4, HighPartOfCW), CWFrameIdx, 1);
+    addFrameReference(BMI(BB, IP, X86::MOVmr8, 4, HighPartOfCW), CWFrameIdx, 1);
 
     // Set the high part to be round to zero...
-    addFrameReference(BuildMI(BB, X86::MOVim8, 5), CWFrameIdx, 1).addZImm(12);
+    addFrameReference(BMI(BB, IP, X86::MOVim8, 5), CWFrameIdx, 1).addZImm(12);
 
     // Reload the modified control word now...
-    addFrameReference(BuildMI(BB, X86::FLDCWm16, 4), CWFrameIdx);
+    addFrameReference(BMI(BB, IP, X86::FLDCWm16, 4), CWFrameIdx);
     
     // Restore the memory image of control word to original value
-    addFrameReference(BuildMI(BB, X86::MOVrm8, 5),
+    addFrameReference(BMI(BB, IP, X86::MOVrm8, 5),
                      CWFrameIdx, 1).addReg(HighPartOfCW);
 
     // We don't have the facilities for directly storing byte sized data to
@@ -1518,7 +1697,7 @@ void ISel::visitCastInst(CastInst &CI) {
       case cByte:  StoreTy = Type::ShortTy; StoreClass = cShort; break;
       case cShort: StoreTy = Type::IntTy;   StoreClass = cInt;   break;
       case cInt:   StoreTy = Type::LongTy;  StoreClass = cLong;  break;
-      case cLong:  visitInstruction(CI); // unsigned long long -> more complex
+      case cLong:  abort(); // FIXME: unsigned long long -> more complex
       default: assert(0 && "Unknown store class!");
       }
 
@@ -1528,25 +1707,69 @@ void ISel::visitCastInst(CastInst &CI) {
 
     static const unsigned Op1[] =
       { 0, X86::FISTr16, X86::FISTr32, 0, X86::FISTPr64 };
-    addFrameReference(BuildMI(BB, Op1[StoreClass], 5), FrameIdx).addReg(SrcReg);
+    addFrameReference(BMI(BB, IP, Op1[StoreClass], 5), FrameIdx).addReg(SrcReg);
 
     if (DestClass == cLong) {
-      addFrameReference(BuildMI(BB, X86::MOVmr32, 4, DestReg), FrameIdx);
-      addFrameReference(BuildMI(BB, X86::MOVmr32, 4, DestReg+1), FrameIdx, 4);
+      addFrameReference(BMI(BB, IP, X86::MOVmr32, 4, DestReg), FrameIdx);
+      addFrameReference(BMI(BB, IP, X86::MOVmr32, 4, DestReg+1), FrameIdx, 4);
     } else {
       static const unsigned Op2[] = { X86::MOVmr8, X86::MOVmr16, X86::MOVmr32 };
-      addFrameReference(BuildMI(BB, Op2[DestClass], 4, DestReg), FrameIdx);
+      addFrameReference(BMI(BB, IP, Op2[DestClass], 4, DestReg), FrameIdx);
     }
 
     // Reload the original control word now...
-    addFrameReference(BuildMI(BB, X86::FLDCWm16, 4), CWFrameIdx);
+    addFrameReference(BMI(BB, IP, X86::FLDCWm16, 4), CWFrameIdx);
     return;
   }
 
   // Anything we haven't handled already, we can't (yet) handle at all.
-  visitInstruction (CI);
+  assert(0 && "Unhandled cast instruction!");
+  abort();
 }
 
+/// visitVarArgInst - Implement the va_arg instruction...
+///
+void ISel::visitVarArgInst(VarArgInst &I) {
+  unsigned SrcReg = getReg(I.getOperand(0));
+  unsigned DestReg = getReg(I);
+
+  // Load the va_list into a register...
+  unsigned VAList = makeAnotherReg(Type::UIntTy);
+  addDirectMem(BuildMI(BB, X86::MOVmr32, 4, VAList), SrcReg);
+
+  unsigned Size;
+  switch (I.getType()->getPrimitiveID()) {
+  default:
+    std::cerr << I;
+    assert(0 && "Error: bad type for va_arg instruction!");
+    return;
+  case Type::PointerTyID:
+  case Type::UIntTyID:
+  case Type::IntTyID:
+    Size = 4;
+    addDirectMem(BuildMI(BB, X86::MOVmr32, 4, DestReg), VAList);
+    break;
+  case Type::ULongTyID:
+  case Type::LongTyID:
+    Size = 8;
+    addDirectMem(BuildMI(BB, X86::MOVmr32, 4, DestReg), VAList);
+    addRegOffset(BuildMI(BB, X86::MOVmr32, 4, DestReg+1), VAList, 4);
+    break;
+  case Type::DoubleTyID:
+    Size = 8;
+    addDirectMem(BuildMI(BB, X86::FLDr64, 4, DestReg), VAList);
+    break;
+  }
+
+  // Increment the VAList pointer...
+  unsigned NextVAList = makeAnotherReg(Type::UIntTy);
+  BuildMI(BB, X86::ADDri32, 2, NextVAList).addReg(VAList).addZImm(Size);
+
+  // Update the VAList in memory...
+  addDirectMem(BuildMI(BB, X86::MOVrm32, 5), SrcReg).addReg(NextVAList);
+}
+
+
 // ExactLog2 - This function solves for (Val == 1 << (N-1)) and returns N.  It
 // returns zero when the input is not exactly a power of two.
 static unsigned ExactLog2(unsigned Val) {
@@ -1710,7 +1933,7 @@ void ISel::visitAllocaInst(AllocaInst &I) {
   // the stack pointer.
   BuildMI(BB, X86::MOVrr32, 1, getReg(I)).addReg(X86::ESP);
 
-  // Inform the Frame Information that we have just allocated a variable sized
+  // Inform the Frame Information that we have just allocated a variable-sized
   // object.
   F->getFrameInfo()->CreateVariableSizedObject();
 }