Codegen fabs/fabsf as FABS. Patch contributed by Morten Ofstad
[oota-llvm.git] / lib / Target / X86 / X86ISelSimple.cpp
index 0715e20c325c41eeace51d00cfeca8fc128ddf71..cd0c0d31475a21177dad7383ec7571628ce19bb5 100644 (file)
@@ -1,10 +1,10 @@
-//===-- InstSelectSimple.cpp - A simple instruction selector for x86 ------===//
-// 
+//===-- X86ISelSimple.cpp - A simple instruction selector for x86 ---------===//
+//
 //                     The LLVM Compiler Infrastructure
 //
 // This file was developed by the LLVM research group and is distributed under
 // the University of Illinois Open Source License. See LICENSE.TXT for details.
-// 
+//
 //===----------------------------------------------------------------------===//
 //
 // This file defines a simple peephole instruction selector for the x86 target
@@ -18,8 +18,8 @@
 #include "llvm/DerivedTypes.h"
 #include "llvm/Function.h"
 #include "llvm/Instructions.h"
-#include "llvm/IntrinsicLowering.h"
 #include "llvm/Pass.h"
+#include "llvm/CodeGen/IntrinsicLowering.h"
 #include "llvm/CodeGen/MachineConstantPool.h"
 #include "llvm/CodeGen/MachineFrameInfo.h"
 #include "llvm/CodeGen/MachineFunction.h"
@@ -28,8 +28,7 @@
 #include "llvm/Target/TargetMachine.h"
 #include "llvm/Support/GetElementPtrTypeIterator.h"
 #include "llvm/Support/InstVisitor.h"
-#include "llvm/Support/CFG.h"
-#include "Support/Statistic.h"
+#include "llvm/ADT/Statistic.h"
 using namespace llvm;
 
 namespace {
@@ -48,7 +47,7 @@ namespace {
 /// size of the type, and whether or not it is floating point.
 ///
 static inline TypeClass getClass(const Type *Ty) {
-  switch (Ty->getPrimitiveID()) {
+  switch (Ty->getTypeID()) {
   case Type::SByteTyID:
   case Type::UByteTyID:   return cByte;      // Byte operands are class #0
   case Type::ShortTyID:
@@ -75,7 +74,7 @@ static inline TypeClass getClassB(const Type *Ty) {
 }
 
 namespace {
-  struct ISel : public FunctionPass, InstVisitor<ISel> {
+  struct X86ISel : public FunctionPass, InstVisitor<X86ISel> {
     TargetMachine &TM;
     MachineFunction *F;                 // The function we are compiling into
     MachineBasicBlock *BB;              // The current MBB we are compiling
@@ -87,12 +86,19 @@ namespace {
     // MBBMap - Mapping between LLVM BB -> Machine BB
     std::map<const BasicBlock*, MachineBasicBlock*> MBBMap;
 
-    ISel(TargetMachine &tm) : TM(tm), F(0), BB(0) {}
+    // AllocaMap - Mapping from fixed sized alloca instructions to the
+    // FrameIndex for the alloca.
+    std::map<AllocaInst*, unsigned> AllocaMap;
+
+    X86ISel(TargetMachine &tm) : TM(tm), F(0), BB(0) {}
 
     /// runOnFunction - Top level implementation of instruction selection for
     /// the entire function.
     ///
     bool runOnFunction(Function &Fn) {
+      // Lazily create a stack slot for the return address if needed.
+      ReturnAddressIndex = 0;
+
       // First pass over the function, lower any unknown intrinsic functions
       // with the IntrinsicLowering class.
       LowerUnknownIntrinsicFunctionCalls(Fn);
@@ -105,13 +111,13 @@ namespace {
 
       BB = &F->front();
 
-      // Set up a frame object for the return address.  This is used by the
-      // llvm.returnaddress & llvm.frameaddress intrinisics.
-      ReturnAddressIndex = F->getFrameInfo()->CreateFixedObject(4, -4);
-
       // Copy incoming arguments off of the stack...
       LoadArgumentsToVirtualRegs(Fn);
 
+      // If this is main, emit special code.
+      if (Fn.hasExternalLinkage() && Fn.getName() == "main")
+        EmitSpecialCodeForMain();
+
       // Instruction select everything except PHI nodes
       visit(Fn);
 
@@ -123,6 +129,7 @@ namespace {
 
       RegMap.clear();
       MBBMap.clear();
+      AllocaMap.clear();
       F = 0;
       // We always build a machine code representation for the function
       return true;
@@ -132,6 +139,10 @@ namespace {
       return "X86 Simple Instruction Selection";
     }
 
+    /// EmitSpecialCodeForMain - Emit any code that needs to be executed only in
+    /// the main function.
+    void EmitSpecialCodeForMain();
+
     /// visitBasicBlock - This method is called when we are visiting a new basic
     /// block.  This simply creates a new MachineBasicBlock to emit code into
     /// and adds it to the current MachineFunction.  Subsequent visit* for
@@ -171,6 +182,7 @@ namespace {
     // Control flow operators
     void visitReturnInst(ReturnInst &RI);
     void visitBranchInst(BranchInst &BI);
+    void visitUnreachableInst(UnreachableInst &UI) {}
 
     struct ValueRecord {
       Value *Val;
@@ -205,8 +217,8 @@ namespace {
                             MachineBasicBlock *MBB,
                             MachineBasicBlock::iterator MBBI);
     void visitSelectInst(SelectInst &SI);
-    
-    
+
+
     // Memory Instructions
     void visitLoadInst(LoadInst &I);
     void visitStoreInst(StoreInst &I);
@@ -214,7 +226,7 @@ namespace {
     void visitAllocaInst(AllocaInst &I);
     void visitMallocInst(MallocInst &I);
     void visitFreeInst(FreeInst &I);
-    
+
     // Other operators
     void visitShiftInst(ShiftInst &I);
     void visitPHINode(PHINode &I) {}      // PHI nodes handled by second pass
@@ -233,23 +245,21 @@ namespace {
 
     /// getAddressingMode - Get the addressing mode to use to address the
     /// specified value.  The returned value should be used with addFullAddress.
-    void getAddressingMode(Value *Addr, unsigned &BaseReg, unsigned &Scale,
-                           unsigned &IndexReg, unsigned &Disp);
+    void getAddressingMode(Value *Addr, X86AddressMode &AM);
 
 
     /// getGEPIndex - This is used to fold GEP instructions into X86 addressing
     /// expressions.
     void getGEPIndex(MachineBasicBlock *MBB, MachineBasicBlock::iterator IP,
                      std::vector<Value*> &GEPOps,
-                     std::vector<const Type*> &GEPTypes, unsigned &BaseReg,
-                     unsigned &Scale, unsigned &IndexReg, unsigned &Disp);
+                     std::vector<const Type*> &GEPTypes,
+                     X86AddressMode &AM);
 
     /// isGEPFoldable - Return true if the specified GEP can be completely
     /// folded into the addressing mode of a load/store or lea instruction.
     bool isGEPFoldable(MachineBasicBlock *MBB,
                        Value *Src, User::op_iterator IdxBegin,
-                       User::op_iterator IdxEnd, unsigned &BaseReg,
-                       unsigned &Scale, unsigned &IndexReg, unsigned &Disp);
+                       User::op_iterator IdxEnd, X86AddressMode &AM);
 
     /// emitGEPOperation - Common code shared between visitGetElementPtrInst and
     /// constant expression GEP support.
@@ -285,7 +295,7 @@ namespace {
     void doMultiply(MachineBasicBlock *MBB, MachineBasicBlock::iterator MBBI,
                     unsigned DestReg, const Type *DestTy,
                     unsigned Op0Reg, unsigned Op1Reg);
-    void doMultiplyConst(MachineBasicBlock *MBB, 
+    void doMultiplyConst(MachineBasicBlock *MBB,
                          MachineBasicBlock::iterator MBBI,
                          unsigned DestReg, const Type *DestTy,
                          unsigned Op0Reg, unsigned Op1Val);
@@ -310,7 +320,14 @@ namespace {
                             MachineBasicBlock::iterator IP,
                             Value *Op, Value *ShiftAmount, bool isLeftShift,
                             const Type *ResultTy, unsigned DestReg);
-      
+
+    // Emit code for a 'SHLD DestReg, Op0, Op1, Amt' operation, where Amt is a
+    // constant.
+    void doSHLDConst(MachineBasicBlock *MBB,
+                     MachineBasicBlock::iterator MBBI,
+                     unsigned DestReg, unsigned Op0Reg, unsigned Op1Reg,
+                     unsigned Op1Val);
+
     /// emitSelectOperation - Common code shared between visitSelectInst and the
     /// constant expression support.
     void emitSelectOperation(MachineBasicBlock *MBB,
@@ -325,6 +342,9 @@ namespace {
                                 MachineBasicBlock::iterator MBBI,
                                 Constant *C, unsigned Reg);
 
+    void emitUCOMr(MachineBasicBlock *MBB, MachineBasicBlock::iterator MBBI,
+                   unsigned LHS, unsigned RHS);
+
     /// makeAnotherReg - This method returns the next register number we haven't
     /// yet used.
     ///
@@ -351,9 +371,7 @@ namespace {
       return F->getSSARegMap()->createVirtualRegister(RC);
     }
 
-    /// getReg - This method turns an LLVM value into a register number.  This
-    /// is guaranteed to produce the same register number for a particular value
-    /// every time it is queried.
+    /// getReg - This method turns an LLVM value into a register number.
     ///
     unsigned getReg(Value &V) { return getReg(&V); }  // Allow references
     unsigned getReg(Value *V) {
@@ -362,43 +380,102 @@ namespace {
       return getReg(V, BB, It);
     }
     unsigned getReg(Value *V, MachineBasicBlock *MBB,
-                    MachineBasicBlock::iterator IPt) {
-      // If this operand is a constant, emit the code to copy the constant into
-      // the register here...
-      //
-      if (Constant *C = dyn_cast<Constant>(V)) {
-        unsigned Reg = makeAnotherReg(V->getType());
-        copyConstantToRegister(MBB, IPt, C, Reg);
-        return Reg;
-      } else if (GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
-        unsigned Reg = makeAnotherReg(V->getType());
-        // Move the address of the global into the register
-        BuildMI(*MBB, IPt, X86::MOV32ri, 1, Reg).addGlobalAddress(GV);
-        return Reg;
-      } else if (CastInst *CI = dyn_cast<CastInst>(V)) {
-        // Do not emit noop casts at all.
-        if (getClassB(CI->getType()) == getClassB(CI->getOperand(0)->getType()))
-          return getReg(CI->getOperand(0), MBB, IPt);
-      }
-
-      unsigned &Reg = RegMap[V];
-      if (Reg == 0) {
-        Reg = makeAnotherReg(V->getType());
-        RegMap[V] = Reg;
-      }
+                    MachineBasicBlock::iterator IPt);
 
-      return Reg;
-    }
+    /// getFixedSizedAllocaFI - Return the frame index for a fixed sized alloca
+    /// that is to be statically allocated with the initial stack frame
+    /// adjustment.
+    unsigned getFixedSizedAllocaFI(AllocaInst *AI);
   };
 }
 
+/// dyn_castFixedAlloca - If the specified value is a fixed size alloca
+/// instruction in the entry block, return it.  Otherwise, return a null
+/// pointer.
+static AllocaInst *dyn_castFixedAlloca(Value *V) {
+  if (AllocaInst *AI = dyn_cast<AllocaInst>(V)) {
+    BasicBlock *BB = AI->getParent();
+    if (isa<ConstantUInt>(AI->getArraySize()) && BB ==&BB->getParent()->front())
+      return AI;
+  }
+  return 0;
+}
+
+/// getReg - This method turns an LLVM value into a register number.
+///
+unsigned X86ISel::getReg(Value *V, MachineBasicBlock *MBB,
+                         MachineBasicBlock::iterator IPt) {
+  // If this operand is a constant, emit the code to copy the constant into
+  // the register here...
+  if (Constant *C = dyn_cast<Constant>(V)) {
+    unsigned Reg = makeAnotherReg(V->getType());
+    copyConstantToRegister(MBB, IPt, C, Reg);
+    return Reg;
+  } else if (CastInst *CI = dyn_cast<CastInst>(V)) {
+    // Do not emit noop casts at all, unless it's a double -> float cast.
+    if (getClassB(CI->getType()) == getClassB(CI->getOperand(0)->getType()) &&
+        (CI->getType() != Type::FloatTy ||
+         CI->getOperand(0)->getType() != Type::DoubleTy))
+      return getReg(CI->getOperand(0), MBB, IPt);
+  } else if (AllocaInst *AI = dyn_castFixedAlloca(V)) {
+    // If the alloca address couldn't be folded into the instruction addressing,
+    // emit an explicit LEA as appropriate.
+    unsigned Reg = makeAnotherReg(V->getType());
+    unsigned FI = getFixedSizedAllocaFI(AI);
+    addFrameReference(BuildMI(*MBB, IPt, X86::LEA32r, 4, Reg), FI);
+    return Reg;
+  }
+
+  unsigned &Reg = RegMap[V];
+  if (Reg == 0) {
+    Reg = makeAnotherReg(V->getType());
+    RegMap[V] = Reg;
+  }
+
+  return Reg;
+}
+
+/// getFixedSizedAllocaFI - Return the frame index for a fixed sized alloca
+/// that is to be statically allocated with the initial stack frame
+/// adjustment.
+unsigned X86ISel::getFixedSizedAllocaFI(AllocaInst *AI) {
+  // Already computed this?
+  std::map<AllocaInst*, unsigned>::iterator I = AllocaMap.lower_bound(AI);
+  if (I != AllocaMap.end() && I->first == AI) return I->second;
+
+  const Type *Ty = AI->getAllocatedType();
+  ConstantUInt *CUI = cast<ConstantUInt>(AI->getArraySize());
+  unsigned TySize = TM.getTargetData().getTypeSize(Ty);
+  TySize *= CUI->getValue();   // Get total allocated size...
+  unsigned Alignment = TM.getTargetData().getTypeAlignment(Ty);
+
+  // Create a new stack object using the frame manager...
+  int FrameIdx = F->getFrameInfo()->CreateStackObject(TySize, Alignment);
+  AllocaMap.insert(I, std::make_pair(AI, FrameIdx));
+  return FrameIdx;
+}
+
+
 /// copyConstantToRegister - Output the instructions required to put the
 /// specified constant into the specified register.
 ///
-void ISel::copyConstantToRegister(MachineBasicBlock *MBB,
-                                  MachineBasicBlock::iterator IP,
-                                  Constant *C, unsigned R) {
-  if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
+void X86ISel::copyConstantToRegister(MachineBasicBlock *MBB,
+                                     MachineBasicBlock::iterator IP,
+                                     Constant *C, unsigned R) {
+  if (isa<UndefValue>(C)) {
+    switch (getClassB(C->getType())) {
+    case cFP:
+      // FIXME: SHOULD TEACH STACKIFIER ABOUT UNDEF VALUES!
+      BuildMI(*MBB, IP, X86::FLD0, 0, R);
+      return;
+    case cLong:
+      BuildMI(*MBB, IP, X86::IMPLICIT_DEF, 0, R+1);
+      // FALL THROUGH
+    default:
+      BuildMI(*MBB, IP, X86::IMPLICIT_DEF, 0, R);
+      return;
+    }
+  } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
     unsigned Class = 0;
     switch (CE->getOpcode()) {
     case Instruction::GetElementPtr:
@@ -450,7 +527,7 @@ void ISel::copyConstantToRegister(MachineBasicBlock *MBB,
       return;
 
     default:
-      std::cerr << "Offending expr: " << C << "\n";
+      std::cerr << "Offending expr: " << *C << "\n";
       assert(0 && "Constant expression not yet handled!\n");
     }
   }
@@ -483,12 +560,33 @@ void ISel::copyConstantToRegister(MachineBasicBlock *MBB,
       BuildMI(*MBB, IP, X86::FLD0, 0, R);
     else if (CFP->isExactlyValue(+1.0))
       BuildMI(*MBB, IP, X86::FLD1, 0, R);
-    else {
-      // Otherwise we need to spill the constant to memory...
+    else if (CFP->isExactlyValue(-0.0)) {
+      unsigned Tmp = makeAnotherReg(Type::DoubleTy);
+      BuildMI(*MBB, IP, X86::FLD0, 0, Tmp);
+      BuildMI(*MBB, IP, X86::FCHS, 1, R).addReg(Tmp);
+    } else if (CFP->isExactlyValue(-1.0)) {
+      unsigned Tmp = makeAnotherReg(Type::DoubleTy);
+      BuildMI(*MBB, IP, X86::FLD1, 0, Tmp);
+      BuildMI(*MBB, IP, X86::FCHS, 1, R).addReg(Tmp);
+    } else {  // FIXME: PI, other native values
+      // FIXME: 2*PI -> LDPI + FADD
+
+      // Otherwise we need to spill the constant to memory.
       MachineConstantPool *CP = F->getConstantPool();
-      unsigned CPI = CP->getConstantPoolIndex(CFP);
+
       const Type *Ty = CFP->getType();
 
+      // If a FP immediate is precise when represented as a float, we put it
+      // into the constant pool as a float, even if it's is statically typed as
+      // a double.
+      if (Ty == Type::DoubleTy)
+        if (CFP->isExactlyValue((float)CFP->getValue())) {
+          Ty = Type::FloatTy;
+          CFP = cast<ConstantFP>(ConstantExpr::getCast(CFP, Ty));
+        }
+
+      unsigned CPI = CP->getConstantPoolIndex(CFP);
+
       assert(Ty == Type::FloatTy || Ty == Type::DoubleTy && "Unknown FP type!");
       unsigned LoadOpcode = Ty == Type::FloatTy ? X86::FLD32m : X86::FLD64m;
       addConstantPoolReference(BuildMI(*MBB, IP, LoadOpcode, 4, R), CPI);
@@ -497,10 +595,10 @@ void ISel::copyConstantToRegister(MachineBasicBlock *MBB,
   } else if (isa<ConstantPointerNull>(C)) {
     // Copy zero (null pointer) to the register.
     BuildMI(*MBB, IP, X86::MOV32ri, 1, R).addImm(0);
-  } else if (ConstantPointerRef *CPR = dyn_cast<ConstantPointerRef>(C)) {
-    BuildMI(*MBB, IP, X86::MOV32ri, 1, R).addGlobalAddress(CPR->getValue());
+  } else if (GlobalValue *GV = dyn_cast<GlobalValue>(C)) {
+    BuildMI(*MBB, IP, X86::MOV32ri, 1, R).addGlobalAddress(GV);
   } else {
-    std::cerr << "Offending constant: " << C << "\n";
+    std::cerr << "Offending constant: " << *C << "\n";
     assert(0 && "Type not handled yet!");
   }
 }
@@ -508,19 +606,20 @@ void ISel::copyConstantToRegister(MachineBasicBlock *MBB,
 /// LoadArgumentsToVirtualRegs - Load all of the arguments to this function from
 /// the stack into virtual registers.
 ///
-void ISel::LoadArgumentsToVirtualRegs(Function &Fn) {
+void X86ISel::LoadArgumentsToVirtualRegs(Function &Fn) {
   // Emit instructions to load the arguments...  On entry to a function on the
   // X86, the stack frame looks like this:
   //
   // [ESP] -- return address
   // [ESP + 4] -- first argument (leftmost lexically)
   // [ESP + 8] -- second argument, if first argument is four bytes in size
-  //    ... 
+  //    ...
   //
   unsigned ArgOffset = 0;   // Frame mechanisms handle retaddr slot
   MachineFrameInfo *MFI = F->getFrameInfo();
 
-  for (Function::aiterator I = Fn.abegin(), E = Fn.aend(); I != E; ++I) {
+  for (Function::arg_iterator I = Fn.arg_begin(), E = Fn.arg_end();
+       I != E; ++I) {
     bool ArgLive = !I->use_empty();
     unsigned Reg = ArgLive ? getReg(*I) : 0;
     int FI;          // Frame object index
@@ -578,15 +677,48 @@ void ISel::LoadArgumentsToVirtualRegs(Function &Fn) {
   // llvm.va_start.
   if (Fn.getFunctionType()->isVarArg())
     VarArgsFrameIndex = MFI->CreateFixedObject(1, ArgOffset);
+
+  // Finally, inform the compiler what our live-outs will be, aka, what we will
+  // be returning in registers.
+  if (Fn.getReturnType() != Type::VoidTy)
+    switch (getClassB(Fn.getReturnType())) {
+    default: assert(0 && "Unknown type!");
+    case cByte:
+    case cShort:
+    case cInt:
+      F->addLiveOut(X86::EAX);
+      break;
+    case cLong:
+      F->addLiveOut(X86::EAX);
+      F->addLiveOut(X86::EDX);
+      break;
+    case cFP:
+      F->addLiveOut(X86::ST0);
+      break;
+    }
 }
 
+/// EmitSpecialCodeForMain - Emit any code that needs to be executed only in
+/// the main function.
+void X86ISel::EmitSpecialCodeForMain() {
+  // Switch the FPU to 64-bit precision mode for better compatibility and speed.
+  int CWFrameIdx = F->getFrameInfo()->CreateStackObject(2, 2);
+  addFrameReference(BuildMI(BB, X86::FNSTCW16m, 4), CWFrameIdx);
+
+  // Set the high part to be 64-bit precision.
+  addFrameReference(BuildMI(BB, X86::MOV8mi, 5),
+                    CWFrameIdx, 1).addImm(2);
+
+  // Reload the modified control word now.
+  addFrameReference(BuildMI(BB, X86::FLDCW16m, 4), CWFrameIdx);
+}
 
 /// SelectPHINodes - Insert machine code to generate phis.  This is tricky
 /// because we have to generate our sources into the source basic blocks, not
 /// the current one.
 ///
-void ISel::SelectPHINodes() {
-  const TargetInstrInfo &TII = TM.getInstrInfo();
+void X86ISel::SelectPHINodes() {
+  const TargetInstrInfo &TII = *TM.getInstrInfo();
   const Function &LF = *F->getFunction();  // The LLVM function...
   for (Function::const_iterator I = LF.begin(), E = LF.end(); I != E; ++I) {
     const BasicBlock *BB = I;
@@ -594,8 +726,8 @@ void ISel::SelectPHINodes() {
 
     // Loop over all of the PHI nodes in the LLVM basic block...
     MachineBasicBlock::iterator PHIInsertPoint = MBB.begin();
-    for (BasicBlock::const_iterator I = BB->begin();
-         PHINode *PN = const_cast<PHINode*>(dyn_cast<PHINode>(I)); ++I) {
+    for (BasicBlock::const_iterator I = BB->begin(); isa<PHINode>(I); ++I) {
+      PHINode *PN = const_cast<PHINode*>(dyn_cast<PHINode>(I));
 
       // Create a new machine instr PHI node, and insert it.
       unsigned PHIReg = getReg(*PN);
@@ -624,34 +756,30 @@ void ISel::SelectPHINodes() {
           // predecessor.  Recycle it.
           ValReg = EntryIt->second;
 
-        } else {        
+        } else {
           // Get the incoming value into a virtual register.
           //
           Value *Val = PN->getIncomingValue(i);
 
           // If this is a constant or GlobalValue, we may have to insert code
           // into the basic block to compute it into a virtual register.
-          if (isa<Constant>(Val) || isa<GlobalValue>(Val)) {
-            if (isa<ConstantExpr>(Val)) {
-              // Because we don't want to clobber any values which might be in
-              // physical registers with the computation of this constant (which
-              // might be arbitrarily complex if it is a constant expression),
-              // just insert the computation at the top of the basic block.
-              MachineBasicBlock::iterator PI = PredMBB->begin();
-              
-              // Skip over any PHI nodes though!
-              while (PI != PredMBB->end() && PI->getOpcode() == X86::PHI)
-                ++PI;
-              
-              ValReg = getReg(Val, PredMBB, PI);
-            } else {
-              // Simple constants get emitted at the end of the basic block,
-              // before any terminator instructions.  We "know" that the code to
-              // move a constant into a register will never clobber any flags.
-              ValReg = getReg(Val, PredMBB, PredMBB->getFirstTerminator());
-            }
+          if ((isa<Constant>(Val) && !isa<ConstantExpr>(Val))) {
+            // Simple constants get emitted at the end of the basic block,
+            // before any terminator instructions.  We "know" that the code to
+            // move a constant into a register will never clobber any flags.
+            ValReg = getReg(Val, PredMBB, PredMBB->getFirstTerminator());
           } else {
-            ValReg = getReg(Val);
+            // Because we don't want to clobber any values which might be in
+            // physical registers with the computation of this constant (which
+            // might be arbitrarily complex if it is a constant expression),
+            // just insert the computation at the top of the basic block.
+            MachineBasicBlock::iterator PI = PredMBB->begin();
+
+            // Skip over any PHI nodes though!
+            while (PI != PredMBB->end() && PI->getOpcode() == X86::PHI)
+              ++PI;
+
+            ValReg = getReg(Val, PredMBB, PI);
           }
 
           // Remember that we inserted a value for this PHI for this predecessor
@@ -684,8 +812,9 @@ void ISel::SelectPHINodes() {
 /// Note that this kill instruction will eventually be eliminated when
 /// restrictions in the stackifier are relaxed.
 ///
-static bool RequiresFPRegKill(const BasicBlock *BB) {
+static bool RequiresFPRegKill(const MachineBasicBlock *MBB) {
 #if 0
+  const BasicBlock *BB = MBB->getBasicBlock ();
   for (succ_const_iterator SI = succ_begin(BB), E = succ_end(BB); SI!=E; ++SI) {
     const BasicBlock *Succ = *SI;
     pred_const_iterator PI = pred_begin(Succ), PE = pred_end(Succ);
@@ -726,7 +855,7 @@ static bool RequiresFPRegKill(const BasicBlock *BB) {
 // break critical edges as needed (to make a place to put compensation code),
 // but this will require some infrastructure improvements as well.
 //
-void ISel::InsertFPRegKills() {
+void X86ISel::InsertFPRegKills() {
   SSARegMap &RegMap = *F->getSSARegMap();
 
   for (MachineFunction::iterator BB = F->begin(), E = F->end(); BB != E; ++BB) {
@@ -735,20 +864,24 @@ void ISel::InsertFPRegKills() {
       MachineOperand& MO = I->getOperand(i);
         if (MO.isRegister() && MO.getReg()) {
           unsigned Reg = MO.getReg();
-          if (MRegisterInfo::isVirtualRegister(Reg))
-            if (RegMap.getRegClass(Reg)->getSize() == 10)
+          if (MRegisterInfo::isVirtualRegister(Reg)) {
+            unsigned RegSize = RegMap.getRegClass(Reg)->getSize();
+            if (RegSize == 10 || RegSize == 8)
               goto UsesFPReg;
+          }
         }
       }
     // If we haven't found an FP register use or def in this basic block, check
     // to see if any of our successors has an FP PHI node, which will cause a
     // copy to be inserted into this block.
-    for (succ_const_iterator SI = succ_begin(BB->getBasicBlock()),
-           E = succ_end(BB->getBasicBlock()); SI != E; ++SI) {
-      MachineBasicBlock *SBB = MBBMap[*SI];
+    for (MachineBasicBlock::const_succ_iterator SI = BB->succ_begin(),
+         SE = BB->succ_end(); SI != SE; ++SI) {
+      MachineBasicBlock *SBB = *SI;
       for (MachineBasicBlock::iterator I = SBB->begin();
            I != SBB->end() && I->getOpcode() == X86::PHI; ++I) {
-        if (RegMap.getRegClass(I->getOperand(0).getReg())->getSize() == 10)
+        const TargetRegisterClass *RC =
+          RegMap.getRegClass(I->getOperand(0).getReg());
+        if (RC->getSize() == 10 || RC->getSize() == 8)
           goto UsesFPReg;
       }
     }
@@ -756,8 +889,7 @@ void ISel::InsertFPRegKills() {
   UsesFPReg:
     // Okay, this block uses an FP register.  If the block has successors (ie,
     // it's not an unwind/return), insert the FP_REG_KILL instruction.
-    if (BB->getBasicBlock()->getTerminator()->getNumSuccessors() &&
-        RequiresFPRegKill(BB->getBasicBlock())) {
+    if (BB->succ_size() && RequiresFPRegKill(BB)) {
       BuildMI(*BB, BB->getFirstTerminator(), X86::FP_REG_KILL, 0);
       ++NumFPKill;
     }
@@ -765,22 +897,48 @@ void ISel::InsertFPRegKills() {
 }
 
 
+void X86ISel::getAddressingMode(Value *Addr, X86AddressMode &AM) {
+  AM.BaseType = X86AddressMode::RegBase;
+  AM.Base.Reg = 0; AM.Scale = 1; AM.IndexReg = 0; AM.Disp = 0;
+  if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Addr)) {
+    if (isGEPFoldable(BB, GEP->getOperand(0), GEP->op_begin()+1, GEP->op_end(),
+                       AM))
+      return;
+  } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Addr)) {
+    if (CE->getOpcode() == Instruction::GetElementPtr)
+      if (isGEPFoldable(BB, CE->getOperand(0), CE->op_begin()+1, CE->op_end(),
+                        AM))
+        return;
+  } else if (AllocaInst *AI = dyn_castFixedAlloca(Addr)) {
+    AM.BaseType = X86AddressMode::FrameIndexBase;
+    AM.Base.FrameIndex = getFixedSizedAllocaFI(AI);
+    return;
+  } else if (GlobalValue *GV = dyn_cast<GlobalValue>(Addr)) {
+    AM.GV = GV;
+    return;
+  }
+
+  // If it's not foldable, reset addr mode.
+  AM.BaseType = X86AddressMode::RegBase;
+  AM.Base.Reg = getReg(Addr);
+  AM.Scale = 1; AM.IndexReg = 0; AM.Disp = 0;
+}
+
 // canFoldSetCCIntoBranchOrSelect - Return the setcc instruction if we can fold
 // it into the conditional branch or select instruction which is the only user
 // of the cc instruction.  This is the case if the conditional branch is the
-// only user of the setcc, and if the setcc is in the same basic block as the
-// conditional branch.  We also don't handle long arguments below, so we reject
-// them here as well.
+// only user of the setcc.  We also don't handle long arguments below, so we
+// reject them here as well.
 //
 static SetCondInst *canFoldSetCCIntoBranchOrSelect(Value *V) {
   if (SetCondInst *SCI = dyn_cast<SetCondInst>(V))
     if (SCI->hasOneUse()) {
       Instruction *User = cast<Instruction>(SCI->use_back());
       if ((isa<BranchInst>(User) || isa<SelectInst>(User)) &&
-          SCI->getParent() == User->getParent() &&
           (getClassB(SCI->getOperand(0)->getType()) != cLong ||
            SCI->getOpcode() == Instruction::SetEQ ||
-           SCI->getOpcode() == Instruction::SetNE))
+           SCI->getOpcode() == Instruction::SetNE) &&
+          (isa<BranchInst>(User) || User->getOperand(0) == V))
         return SCI;
     }
   return 0;
@@ -819,18 +977,38 @@ static const unsigned SetCCOpcodeTab[2][8] = {
     X86::SETSr, X86::SETNSr },
 };
 
+/// emitUCOMr - In the future when we support processors before the P6, this
+/// wraps the logic for emitting an FUCOMr vs FUCOMIr.
+void X86ISel::emitUCOMr(MachineBasicBlock *MBB, MachineBasicBlock::iterator IP,
+                        unsigned LHS, unsigned RHS) {
+  if (0) { // for processors prior to the P6
+    BuildMI(*MBB, IP, X86::FUCOMr, 2).addReg(LHS).addReg(RHS);
+    BuildMI(*MBB, IP, X86::FNSTSW8r, 0);
+    BuildMI(*MBB, IP, X86::SAHF, 1);
+  } else {
+    BuildMI(*MBB, IP, X86::FUCOMIr, 2).addReg(LHS).addReg(RHS);
+  }
+}
+
 // EmitComparison - This function emits a comparison of the two operands,
 // returning the extended setcc code to use.
-unsigned ISel::EmitComparison(unsigned OpNum, Value *Op0, Value *Op1,
-                              MachineBasicBlock *MBB,
-                              MachineBasicBlock::iterator IP) {
+unsigned X86ISel::EmitComparison(unsigned OpNum, Value *Op0, Value *Op1,
+                                 MachineBasicBlock *MBB,
+                                 MachineBasicBlock::iterator IP) {
   // The arguments are already supposed to be of the same type.
   const Type *CompTy = Op0->getType();
   unsigned Class = getClassB(CompTy);
-  unsigned Op0r = getReg(Op0, MBB, IP);
 
   // Special case handling of: cmp R, i
-  if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
+  if (isa<ConstantPointerNull>(Op1)) {
+    unsigned Op0r = getReg(Op0, MBB, IP);
+    if (OpNum < 2)    // seteq/setne -> test
+      BuildMI(*MBB, IP, X86::TEST32rr, 2).addReg(Op0r).addReg(Op0r);
+    else
+      BuildMI(*MBB, IP, X86::CMP32ri, 2).addReg(Op0r).addImm(0);
+    return OpNum;
+
+  } else if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
     if (Class == cByte || Class == cShort || Class == cInt) {
       unsigned Op1v = CI->getRawValue();
 
@@ -841,6 +1019,28 @@ unsigned ISel::EmitComparison(unsigned OpNum, Value *Op0, Value *Op1,
       // can't handle unsigned comparisons against zero unless they are == or
       // !=.  These should have been strength reduced already anyway.
       if (Op1v == 0 && (CompTy->isSigned() || OpNum < 2)) {
+
+        // If this is a comparison against zero and the LHS is an and of a
+        // register with a constant, use the test to do the and.
+        if (Instruction *Op0I = dyn_cast<Instruction>(Op0))
+          if (Op0I->getOpcode() == Instruction::And && Op0->hasOneUse() &&
+              isa<ConstantInt>(Op0I->getOperand(1))) {
+            static const unsigned TESTTab[] = {
+              X86::TEST8ri, X86::TEST16ri, X86::TEST32ri
+            };
+
+            // Emit test X, i
+            unsigned LHS = getReg(Op0I->getOperand(0), MBB, IP);
+            unsigned Imm =
+              cast<ConstantInt>(Op0I->getOperand(1))->getRawValue();
+            BuildMI(*MBB, IP, TESTTab[Class], 2).addReg(LHS).addImm(Imm);
+
+            if (OpNum == 2) return 6;   // Map jl -> js
+            if (OpNum == 3) return 7;   // Map jg -> jns
+            return OpNum;
+          }
+
+        unsigned Op0r = getReg(Op0, MBB, IP);
         static const unsigned TESTTab[] = {
           X86::TEST8rr, X86::TEST16rr, X86::TEST32rr
         };
@@ -855,9 +1055,11 @@ unsigned ISel::EmitComparison(unsigned OpNum, Value *Op0, Value *Op1,
         X86::CMP8ri, X86::CMP16ri, X86::CMP32ri
       };
 
+      unsigned Op0r = getReg(Op0, MBB, IP);
       BuildMI(*MBB, IP, CMPTab[Class], 2).addReg(Op0r).addImm(Op1v);
       return OpNum;
     } else {
+      unsigned Op0r = getReg(Op0, MBB, IP);
       assert(Class == cLong && "Unknown integer class!");
       unsigned LowCst = CI->getRawValue();
       unsigned HiCst = CI->getRawValue() >> 32;
@@ -880,9 +1082,9 @@ unsigned ISel::EmitComparison(unsigned OpNum, Value *Op0, Value *Op1,
         // each, then uses a conditional move to handle the overflow case.  For
         // example, a setlt for long would generate code like this:
         //
-        // AL = lo(op1) < lo(op2)   // Signedness depends on operands
-        // BL = hi(op1) < hi(op2)   // Always unsigned comparison
-        // dest = hi(op1) == hi(op2) ? AL : BL;
+        // AL = lo(op1) < lo(op2)   // Always unsigned comparison
+        // BL = hi(op1) < hi(op2)   // Signedness depends on operands
+        // dest = hi(op1) == hi(op2) ? BL : AL;
         //
 
         // FIXME: This would be much better if we had hierarchical register
@@ -904,6 +1106,8 @@ unsigned ISel::EmitComparison(unsigned OpNum, Value *Op0, Value *Op1,
     }
   }
 
+  unsigned Op0r = getReg(Op0, MBB, IP);
+
   // Special case handling of comparison against +/- 0.0
   if (ConstantFP *CFP = dyn_cast<ConstantFP>(Op1))
     if (CFP->isExactlyValue(+0.0) || CFP->isExactlyValue(-0.0)) {
@@ -929,13 +1133,7 @@ unsigned ISel::EmitComparison(unsigned OpNum, Value *Op0, Value *Op1,
     BuildMI(*MBB, IP, X86::CMP32rr, 2).addReg(Op0r).addReg(Op1r);
     break;
   case cFP:
-    if (0) { // for processors prior to the P6
-      BuildMI(*MBB, IP, X86::FpUCOM, 2).addReg(Op0r).addReg(Op1r);
-      BuildMI(*MBB, IP, X86::FNSTSW8r, 0);
-      BuildMI(*MBB, IP, X86::SAHF, 1);
-    } else {
-      BuildMI(*MBB, IP, X86::FpUCOMI, 2).addReg(Op0r).addReg(Op1r);
-    }
+    emitUCOMr(MBB, IP, Op0r, Op1r);
     break;
 
   case cLong:
@@ -954,7 +1152,7 @@ unsigned ISel::EmitComparison(unsigned OpNum, Value *Op0, Value *Op1,
       //
       // AL = lo(op1) < lo(op2)   // Signedness depends on operands
       // BL = hi(op1) < hi(op2)   // Always unsigned comparison
-      // dest = hi(op1) == hi(op2) ? AL : BL;
+      // dest = hi(op1) == hi(op2) ? BL : AL;
       //
 
       // FIXME: This would be much better if we had hierarchical register
@@ -978,9 +1176,9 @@ unsigned ISel::EmitComparison(unsigned OpNum, Value *Op0, Value *Op1,
 }
 
 /// SetCC instructions - Here we just emit boilerplate code to set a byte-sized
-/// register, then move it to wherever the result should be. 
+/// register, then move it to wherever the result should be.
 ///
-void ISel::visitSetCondInst(SetCondInst &I) {
+void X86ISel::visitSetCondInst(SetCondInst &I) {
   if (canFoldSetCCIntoBranchOrSelect(&I))
     return;  // Fold this into a branch or select.
 
@@ -993,10 +1191,10 @@ void ISel::visitSetCondInst(SetCondInst &I) {
 /// emitSetCCOperation - Common code shared between visitSetCondInst and
 /// constant expression support.
 ///
-void ISel::emitSetCCOperation(MachineBasicBlock *MBB,
-                              MachineBasicBlock::iterator IP,
-                              Value *Op0, Value *Op1, unsigned Opcode,
-                              unsigned TargetReg) {
+void X86ISel::emitSetCCOperation(MachineBasicBlock *MBB,
+                                 MachineBasicBlock::iterator IP,
+                                 Value *Op0, Value *Op1, unsigned Opcode,
+                                 unsigned TargetReg) {
   unsigned OpNum = getSetCCNumber(Opcode);
   OpNum = EmitComparison(OpNum, Op0, Op1, MBB, IP);
 
@@ -1014,21 +1212,21 @@ void ISel::emitSetCCOperation(MachineBasicBlock *MBB,
   }
 }
 
-void ISel::visitSelectInst(SelectInst &SI) {
+void X86ISel::visitSelectInst(SelectInst &SI) {
   unsigned DestReg = getReg(SI);
   MachineBasicBlock::iterator MII = BB->end();
   emitSelectOperation(BB, MII, SI.getCondition(), SI.getTrueValue(),
                       SI.getFalseValue(), DestReg);
 }
+
 /// emitSelect - Common code shared between visitSelectInst and the constant
 /// expression support.
-void ISel::emitSelectOperation(MachineBasicBlock *MBB,
-                               MachineBasicBlock::iterator IP,
-                               Value *Cond, Value *TrueVal, Value *FalseVal,
-                               unsigned DestReg) {
+void X86ISel::emitSelectOperation(MachineBasicBlock *MBB,
+                                  MachineBasicBlock::iterator IP,
+                                  Value *Cond, Value *TrueVal, Value *FalseVal,
+                                  unsigned DestReg) {
   unsigned SelectClass = getClassB(TrueVal->getType());
-  
+
   // We don't support 8-bit conditional moves.  If we have incoming constants,
   // transform them into 16-bit constants to avoid having a run-time conversion.
   if (SelectClass == cByte) {
@@ -1053,14 +1251,14 @@ void ISel::emitSelectOperation(MachineBasicBlock *MBB,
   unsigned Opcode;
   if (SetCondInst *SCI = canFoldSetCCIntoBranchOrSelect(Cond)) {
     // We successfully folded the setcc into the select instruction.
-    
+
     unsigned OpNum = getSetCCNumber(SCI->getOpcode());
     OpNum = EmitComparison(OpNum, SCI->getOperand(0), SCI->getOperand(1), MBB,
                            IP);
 
     const Type *CompTy = SCI->getOperand(0)->getType();
     bool isSigned = CompTy->isSigned() && getClassB(CompTy) != cFP;
-  
+
     // LLVM  -> X86 signed  X86 unsigned
     // -----    ----------  ------------
     // seteq -> cmovNE      cmovNE
@@ -1072,7 +1270,7 @@ void ISel::emitSelectOperation(MachineBasicBlock *MBB,
     // ----
     //          cmovNS              // Used by comparison with 0 optimization
     //          cmovS
-    
+
     switch (SelectClass) {
     default: assert(0 && "Unknown value class!");
     case cFP: {
@@ -1098,7 +1296,7 @@ void ISel::emitSelectOperation(MachineBasicBlock *MBB,
           // Long comparisons end up in the BL register.
           CondReg = X86::BL;
         }
-        
+
         BuildMI(*MBB, IP, X86::TEST8rr, 2).addReg(CondReg).addReg(CondReg);
         Opcode = X86::FCMOVE;
       }
@@ -1186,8 +1384,8 @@ void ISel::emitSelectOperation(MachineBasicBlock *MBB,
 /// promote32 - Emit instructions to turn a narrow operand into a 32-bit-wide
 /// operand, in the specified target register.
 ///
-void ISel::promote32(unsigned targetReg, const ValueRecord &VR) {
-  bool isUnsigned = VR.Ty->isUnsigned();
+void X86ISel::promote32(unsigned targetReg, const ValueRecord &VR) {
+  bool isUnsigned = VR.Ty->isUnsigned() || VR.Ty == Type::BoolTy;
 
   Value *Val = VR.Val;
   const Type *Ty = VR.Ty;
@@ -1201,7 +1399,7 @@ void ISel::promote32(unsigned targetReg, const ValueRecord &VR) {
     // copy.
     if (ConstantInt *CI = dyn_cast<ConstantInt>(Val)) {
       int TheVal = CI->getRawValue() & 0xFFFFFFFF;
-    BuildMI(BB, X86::MOV32ri, 1, targetReg).addImm(TheVal);
+      BuildMI(BB, X86::MOV32ri, 1, targetReg).addImm(TheVal);
       return;
     }
   }
@@ -1244,7 +1442,7 @@ void ISel::promote32(unsigned targetReg, const ValueRecord &VR) {
 ///   ret long, ulong  : Move value into EAX/EDX and return
 ///   ret float/double : Top of FP stack
 ///
-void ISel::visitReturnInst(ReturnInst &I) {
+void X86ISel::visitReturnInst(ReturnInst &I) {
   if (I.getNumOperands() == 0) {
     BuildMI(BB, X86::RET, 0); // Just emit a 'ret' instruction
     return;
@@ -1256,23 +1454,16 @@ void ISel::visitReturnInst(ReturnInst &I) {
   case cShort:
   case cInt:
     promote32(X86::EAX, ValueRecord(RetVal));
-    // 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)
     unsigned RetReg = getReg(RetVal);
     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: {
     unsigned RetReg = getReg(RetVal);
     BuildMI(BB, X86::MOV32rr, 1, X86::EAX).addReg(RetReg);
     BuildMI(BB, X86::MOV32rr, 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:
@@ -1294,12 +1485,17 @@ static inline BasicBlock *getBlockAfter(BasicBlock *BB) {
 /// 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) {
+void X86ISel::visitBranchInst(BranchInst &BI) {
+  // Update machine-CFG edges
+  BB->addSuccessor (MBBMap[BI.getSuccessor(0)]);
+  if (BI.isConditional())
+    BB->addSuccessor (MBBMap[BI.getSuccessor(1)]);
+
   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));
+      BuildMI(BB, X86::JMP, 1).addMBB(MBBMap[BI.getSuccessor(0)]);
     return;
   }
 
@@ -1312,12 +1508,12 @@ void ISel::visitBranchInst(BranchInst &BI) {
     BuildMI(BB, X86::TEST8rr, 2).addReg(condReg).addReg(condReg);
     if (BI.getSuccessor(1) == NextBB) {
       if (BI.getSuccessor(0) != NextBB)
-        BuildMI(BB, X86::JNE, 1).addPCDisp(BI.getSuccessor(0));
+        BuildMI(BB, X86::JNE, 1).addMBB(MBBMap[BI.getSuccessor(0)]);
     } else {
-      BuildMI(BB, X86::JE, 1).addPCDisp(BI.getSuccessor(1));
-      
+      BuildMI(BB, X86::JE, 1).addMBB(MBBMap[BI.getSuccessor(1)]);
+
       if (BI.getSuccessor(0) != NextBB)
-        BuildMI(BB, X86::JMP, 1).addPCDisp(BI.getSuccessor(0));
+        BuildMI(BB, X86::JMP, 1).addMBB(MBBMap[BI.getSuccessor(0)]);
     }
     return;
   }
@@ -1328,7 +1524,7 @@ void ISel::visitBranchInst(BranchInst &BI) {
 
   const Type *CompTy = SCI->getOperand(0)->getType();
   bool isSigned = CompTy->isSigned() && getClassB(CompTy) != cFP;
-  
+
 
   // LLVM  -> X86 signed  X86 unsigned
   // -----    ----------  ------------
@@ -1347,16 +1543,18 @@ void ISel::visitBranchInst(BranchInst &BI) {
     { X86::JE, X86::JNE, X86::JL, X86::JGE, X86::JG, X86::JLE,
       X86::JS, X86::JNS },
   };
-  
+
   if (BI.getSuccessor(0) != NextBB) {
-    BuildMI(BB, OpcodeTab[isSigned][OpNum], 1).addPCDisp(BI.getSuccessor(0));
+    BuildMI(BB, OpcodeTab[isSigned][OpNum], 1)
+      .addMBB(MBBMap[BI.getSuccessor(0)]);
     if (BI.getSuccessor(1) != NextBB)
-      BuildMI(BB, X86::JMP, 1).addPCDisp(BI.getSuccessor(1));
+      BuildMI(BB, X86::JMP, 1).addMBB(MBBMap[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));
+      BuildMI(BB, OpcodeTab[isSigned][OpNum], 1)
+        .addMBB(MBBMap[BI.getSuccessor(1)]);
     }
   }
 }
@@ -1366,9 +1564,8 @@ void ISel::visitBranchInst(BranchInst &BI) {
 /// and the return value as appropriate.  For the actual function call itself,
 /// it inserts the specified CallMI instruction into the stream.
 ///
-void ISel::doCall(const ValueRecord &Ret, MachineInstr *CallMI,
-                  const std::vector<ValueRecord> &Args) {
-
+void X86ISel::doCall(const ValueRecord &Ret, MachineInstr *CallMI,
+                     const std::vector<ValueRecord> &Args) {
   // Count how many bytes are to be pushed on the stack...
   unsigned NumBytes = 0;
 
@@ -1394,6 +1591,12 @@ void ISel::doCall(const ValueRecord &Ret, MachineInstr *CallMI,
       unsigned ArgReg;
       switch (getClassB(Args[i].Ty)) {
       case cByte:
+        if (Args[i].Val && isa<ConstantBool>(Args[i].Val)) {
+          addRegOffset(BuildMI(BB, X86::MOV32mi, 5), X86::ESP, ArgOffset)
+            .addImm(Args[i].Val == ConstantBool::True);
+          break;
+        }
+        // FALL THROUGH
       case cShort:
         if (Args[i].Val && isa<ConstantInt>(Args[i].Val)) {
           // Zero/Sign extend constant, then stuff into memory.
@@ -1414,6 +1617,12 @@ void ISel::doCall(const ValueRecord &Ret, MachineInstr *CallMI,
           unsigned Val = cast<ConstantInt>(Args[i].Val)->getRawValue();
           addRegOffset(BuildMI(BB, X86::MOV32mi, 5),
                        X86::ESP, ArgOffset).addImm(Val);
+        } else if (Args[i].Val && isa<ConstantPointerNull>(Args[i].Val)) {
+          addRegOffset(BuildMI(BB, X86::MOV32mi, 5),
+                       X86::ESP, ArgOffset).addImm(0);
+        } else if (Args[i].Val && isa<GlobalValue>(Args[i].Val)) {
+          addRegOffset(BuildMI(BB, X86::MOV32mi, 5), X86::ESP, ArgOffset)
+            .addGlobalAddress(cast<GlobalValue>(Args[i].Val));
         } else {
           ArgReg = Args[i].Val ? getReg(Args[i].Val) : Args[i].Reg;
           addRegOffset(BuildMI(BB, X86::MOV32mr, 5),
@@ -1436,17 +1645,42 @@ void ISel::doCall(const ValueRecord &Ret, MachineInstr *CallMI,
         }
         ArgOffset += 4;        // 8 byte entry, not 4.
         break;
-        
+
       case cFP:
-        ArgReg = Args[i].Val ? getReg(Args[i].Val) : Args[i].Reg;
-        if (Args[i].Ty == Type::FloatTy) {
-          addRegOffset(BuildMI(BB, X86::FST32m, 5),
-                       X86::ESP, ArgOffset).addReg(ArgReg);
+        if (ConstantFP *CFP = dyn_cast_or_null<ConstantFP>(Args[i].Val)) {
+          // Store constant FP values with integer instructions to avoid having
+          // to load the constants from the constant pool then do a store.
+          if (CFP->getType() == Type::FloatTy) {
+            union {
+              unsigned I;
+              float    F;
+            } V;
+            V.F = CFP->getValue();
+            addRegOffset(BuildMI(BB, X86::MOV32mi, 5),
+                         X86::ESP, ArgOffset).addImm(V.I);
+          } else {
+            union {
+              uint64_t I;
+              double   F;
+            } V;
+            V.F = CFP->getValue();
+            addRegOffset(BuildMI(BB, X86::MOV32mi, 5),
+                          X86::ESP, ArgOffset).addImm((unsigned)V.I);
+            addRegOffset(BuildMI(BB, X86::MOV32mi, 5),
+                         X86::ESP, ArgOffset+4).addImm(unsigned(V.I >> 32));
+            ArgOffset += 4;       // 8 byte entry, not 4.
+          }
         } else {
-          assert(Args[i].Ty == Type::DoubleTy && "Unknown FP type!");
-          addRegOffset(BuildMI(BB, X86::FST64m, 5),
-                       X86::ESP, ArgOffset).addReg(ArgReg);
-          ArgOffset += 4;       // 8 byte entry, not 4.
+          ArgReg = Args[i].Val ? getReg(Args[i].Val) : Args[i].Reg;
+          if (Args[i].Ty == Type::FloatTy) {
+            addRegOffset(BuildMI(BB, X86::FST32m, 5),
+                         X86::ESP, ArgOffset).addReg(ArgReg);
+          } else {
+            assert(Args[i].Ty == Type::DoubleTy && "Unknown FP type!");
+            addRegOffset(BuildMI(BB, X86::FST64m, 5),
+                         X86::ESP, ArgOffset).addReg(ArgReg);
+            ArgOffset += 4;       // 8 byte entry, not 4.
+          }
         }
         break;
 
@@ -1494,13 +1728,22 @@ void ISel::doCall(const ValueRecord &Ret, MachineInstr *CallMI,
 
 
 /// visitCallInst - Push args on stack and do a procedure call instruction.
-void ISel::visitCallInst(CallInst &CI) {
+void X86ISel::visitCallInst(CallInst &CI) {
   MachineInstr *TheCall;
   if (Function *F = CI.getCalledFunction()) {
     // Is it an intrinsic function call?
     if (Intrinsic::ID ID = (Intrinsic::ID)F->getIntrinsicID()) {
       visitIntrinsicCall(ID, CI);   // Special intrinsics are not handled here
       return;
+    } else if (F->getName() == "fabs" || F->getName() == "fabsf") {
+      if (CI.getNumOperands() == 2 &&   // Basic sanity checks.
+          CI.getOperand(1)->getType()->isFloatingPoint() &&
+          CI.getType() == CI.getOperand(1)->getType()) {
+        unsigned op1Reg = getReg(CI.getOperand(1));
+        unsigned DestReg = getReg(CI);
+        BuildMI(BB, X86::FABS, 1, DestReg).addReg(op1Reg);
+        return;
+      }
     }
 
     // Emit a CALL instruction with PC-relative displacement.
@@ -1516,14 +1759,13 @@ void ISel::visitCallInst(CallInst &CI) {
 
   unsigned DestReg = CI.getType() != Type::VoidTy ? getReg(CI) : 0;
   doCall(ValueRecord(DestReg, CI.getType()), TheCall, Args);
-}         
-
+}
 
 /// LowerUnknownIntrinsicFunctionCalls - This performs a prepass over the
 /// function, lowering any calls to unknown intrinsic functions into the
 /// equivalent LLVM code.
 ///
-void ISel::LowerUnknownIntrinsicFunctionCalls(Function &F) {
+void X86ISel::LowerUnknownIntrinsicFunctionCalls(Function &F) {
   for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
     for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; )
       if (CallInst *CI = dyn_cast<CallInst>(I++))
@@ -1537,6 +1779,7 @@ void ISel::LowerUnknownIntrinsicFunctionCalls(Function &F) {
           case Intrinsic::frameaddress:
           case Intrinsic::memcpy:
           case Intrinsic::memset:
+          case Intrinsic::isunordered:
           case Intrinsic::readport:
           case Intrinsic::writeport:
             // We directly implement these intrinsics
@@ -1544,20 +1787,18 @@ void ISel::LowerUnknownIntrinsicFunctionCalls(Function &F) {
           case Intrinsic::readio: {
             // On X86, memory operations are in-order.  Lower this intrinsic
             // into a volatile load.
-            Instruction *Before = CI->getPrev();
-            LoadInst * LI = new LoadInst (CI->getOperand(1), "", true, CI);
-            CI->replaceAllUsesWith (LI);
-            BB->getInstList().erase (CI);
+            LoadInst * LI = new LoadInst(CI->getOperand(1), "", true, CI);
+            CI->replaceAllUsesWith(LI);
+            BB->getInstList().erase(CI);
             break;
           }
           case Intrinsic::writeio: {
             // On X86, memory operations are in-order.  Lower this intrinsic
             // into a volatile store.
-            Instruction *Before = CI->getPrev();
-            StoreInst * LI = new StoreInst (CI->getOperand(1),
-                                            CI->getOperand(2), true, CI);
-            CI->replaceAllUsesWith (LI);
-            BB->getInstList().erase (CI);
+            StoreInst *LI = new StoreInst(CI->getOperand(1),
+                                          CI->getOperand(2), true, CI);
+            CI->replaceAllUsesWith(LI);
+            BB->getInstList().erase(CI);
             break;
           }
           default:
@@ -1565,15 +1806,14 @@ void ISel::LowerUnknownIntrinsicFunctionCalls(Function &F) {
             Instruction *Before = CI->getPrev();
             TM.getIntrinsicLowering().LowerIntrinsicCall(CI);
             if (Before) {        // Move iterator to instruction after call
-              I = Before;  ++I;
+              I = Before; ++I;
             } else {
               I = BB->begin();
             }
           }
-
 }
 
-void ISel::visitIntrinsicCall(Intrinsic::ID ID, CallInst &CI) {
+void X86ISel::visitIntrinsicCall(Intrinsic::ID ID, CallInst &CI) {
   unsigned TmpReg1, TmpReg2;
   switch (ID) {
   case Intrinsic::vastart:
@@ -1593,6 +1833,11 @@ void ISel::visitIntrinsicCall(Intrinsic::ID ID, CallInst &CI) {
   case Intrinsic::frameaddress:
     TmpReg1 = getReg(CI);
     if (cast<Constant>(CI.getOperand(1))->isNullValue()) {
+      if (ReturnAddressIndex == 0) {
+        // Set up a frame object for the return address.
+        ReturnAddressIndex = F->getFrameInfo()->CreateFixedObject(4, -4);
+      }
+
       if (ID == Intrinsic::returnaddress) {
         // Just load the return address
         addFrameReference(BuildMI(BB, X86::MOV32rm, 4, TmpReg1),
@@ -1607,6 +1852,14 @@ void ISel::visitIntrinsicCall(Intrinsic::ID ID, CallInst &CI) {
     }
     return;
 
+  case Intrinsic::isunordered:
+    TmpReg1 = getReg(CI.getOperand(1));
+    TmpReg2 = getReg(CI.getOperand(2));
+    emitUCOMr(BB, BB->end(), TmpReg2, TmpReg1);
+    TmpReg2 = getReg(CI);
+    BuildMI(BB, X86::SETPr, 0, TmpReg2);
+    return;
+
   case Intrinsic::memcpy: {
     assert(CI.getNumOperands() == 5 && "Illegal llvm.memcpy call!");
     unsigned Align = 1;
@@ -1817,7 +2070,7 @@ void ISel::visitIntrinsicCall(Intrinsic::ID ID, CallInst &CI) {
     BuildMI(BB, Opc[Class], 0);
     return;
   }
-    
+
   default: assert(0 && "Error: unknown intrinsics should have been lowered!");
   }
 }
@@ -1848,18 +2101,37 @@ static bool isSafeToFoldLoadIntoInstruction(LoadInst &LI, Instruction &User) {
 /// 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) {
+void X86ISel::visitSimpleBinary(BinaryOperator &B, unsigned OperatorClass) {
   unsigned DestReg = getReg(B);
   MachineBasicBlock::iterator MI = BB->end();
   Value *Op0 = B.getOperand(0), *Op1 = B.getOperand(1);
+  unsigned Class = getClassB(B.getType());
+
+  // If this is AND X, C, and it is only used by a setcc instruction, it will
+  // be folded.  There is no need to emit this instruction.
+  if (B.hasOneUse() && OperatorClass == 2 && isa<ConstantInt>(Op1))
+    if (Class == cByte || Class == cShort || Class == cInt) {
+      Instruction *Use = cast<Instruction>(B.use_back());
+      if (isa<SetCondInst>(Use) &&
+          Use->getOperand(1) == Constant::getNullValue(B.getType())) {
+        switch (getSetCCNumber(Use->getOpcode())) {
+        case 0:
+        case 1:
+          return;
+        default:
+          if (B.getType()->isSigned()) return;
+        }
+      }
+    }
 
   // Special case: op Reg, load [mem]
-  if (isa<LoadInst>(Op0) && !isa<LoadInst>(Op1))
+  if (isa<LoadInst>(Op0) && !isa<LoadInst>(Op1) && Class != cLong &&
+      Op0->hasOneUse() &&
+      isSafeToFoldLoadIntoInstruction(*cast<LoadInst>(Op0), B))
     if (!B.swapOperands())
       std::swap(Op0, Op1);  // Make sure any loads are in the RHS.
 
-  unsigned Class = getClassB(B.getType());
-  if (isa<LoadInst>(Op1) && Class != cLong &&
+  if (isa<LoadInst>(Op1) && Class != cLong && Op1->hasOneUse() &&
       isSafeToFoldLoadIntoInstruction(*cast<LoadInst>(Op1), B)) {
 
     unsigned Opcode;
@@ -1868,7 +2140,7 @@ void ISel::visitSimpleBinary(BinaryOperator &B, unsigned OperatorClass) {
         // Arithmetic operators
         { X86::ADD8rm, X86::ADD16rm, X86::ADD32rm },  // ADD
         { X86::SUB8rm, X86::SUB16rm, X86::SUB32rm },  // SUB
-        
+
         // Bitwise operators
         { X86::AND8rm, X86::AND16rm, X86::AND32rm },  // AND
         { X86:: OR8rm, X86:: OR16rm, X86:: OR32rm },  // OR
@@ -1885,32 +2157,41 @@ void ISel::visitSimpleBinary(BinaryOperator &B, unsigned OperatorClass) {
       Opcode = OpcodeTab[OperatorClass][Ty == Type::DoubleTy];
     }
 
-    unsigned BaseReg, Scale, IndexReg, Disp;
-    getAddressingMode(cast<LoadInst>(Op1)->getOperand(0), BaseReg,
-                      Scale, IndexReg, Disp);
-
     unsigned Op0r = getReg(Op0);
-    addFullAddress(BuildMI(BB, Opcode, 2, DestReg).addReg(Op0r),
-                   BaseReg, Scale, IndexReg, Disp);
+    if (AllocaInst *AI =
+        dyn_castFixedAlloca(cast<LoadInst>(Op1)->getOperand(0))) {
+      unsigned FI = getFixedSizedAllocaFI(AI);
+      addFrameReference(BuildMI(BB, Opcode, 5, DestReg).addReg(Op0r), FI);
+
+    } else {
+      X86AddressMode AM;
+      getAddressingMode(cast<LoadInst>(Op1)->getOperand(0), AM);
+
+      addFullAddress(BuildMI(BB, Opcode, 5, DestReg).addReg(Op0r), AM);
+    }
     return;
   }
 
   // If this is a floating point subtract, check to see if we can fold the first
   // operand in.
   if (Class == cFP && OperatorClass == 1 &&
-      isa<LoadInst>(Op0) && 
+      isa<LoadInst>(Op0) &&
       isSafeToFoldLoadIntoInstruction(*cast<LoadInst>(Op0), B)) {
     const Type *Ty = Op0->getType();
     assert(Ty == Type::FloatTy || Ty == Type::DoubleTy && "Unknown FP type!");
     unsigned Opcode = Ty == Type::FloatTy ? X86::FSUBR32m : X86::FSUBR64m;
 
-    unsigned BaseReg, Scale, IndexReg, Disp;
-    getAddressingMode(cast<LoadInst>(Op0)->getOperand(0), BaseReg,
-                      Scale, IndexReg, Disp);
-
     unsigned Op1r = getReg(Op1);
-    addFullAddress(BuildMI(BB, Opcode, 2, DestReg).addReg(Op1r),
-                   BaseReg, Scale, IndexReg, Disp);
+    if (AllocaInst *AI =
+        dyn_castFixedAlloca(cast<LoadInst>(Op0)->getOperand(0))) {
+      unsigned FI = getFixedSizedAllocaFI(AI);
+      addFrameReference(BuildMI(BB, Opcode, 5, DestReg).addReg(Op1r), FI);
+    } else {
+      X86AddressMode AM;
+      getAddressingMode(cast<LoadInst>(Op0)->getOperand(0), AM);
+
+      addFullAddress(BuildMI(BB, Opcode, 5, DestReg).addReg(Op1r), AM);
+    }
     return;
   }
 
@@ -1920,11 +2201,10 @@ void ISel::visitSimpleBinary(BinaryOperator &B, unsigned OperatorClass) {
 
 /// emitBinaryFPOperation - This method handles emission of floating point
 /// Add (0), Sub (1), Mul (2), and Div (3) operations.
-void ISel::emitBinaryFPOperation(MachineBasicBlock *BB,
-                                 MachineBasicBlock::iterator IP,
-                                 Value *Op0, Value *Op1,
-                                 unsigned OperatorClass, unsigned DestReg) {
-
+void X86ISel::emitBinaryFPOperation(MachineBasicBlock *BB,
+                                    MachineBasicBlock::iterator IP,
+                                    Value *Op0, Value *Op1,
+                                    unsigned OperatorClass, unsigned DestReg) {
   // Special case: op Reg, <const fp>
   if (ConstantFP *Op1C = dyn_cast<ConstantFP>(Op1))
     if (!Op1C->isExactlyValue(+0.0) && !Op1C->isExactlyValue(+1.0)) {
@@ -1945,7 +2225,7 @@ void ISel::emitBinaryFPOperation(MachineBasicBlock *BB,
                                        DestReg).addReg(Op0r), CPI);
       return;
     }
-  
+
   // Special case: R1 = op <const fp>, R2
   if (ConstantFP *CFP = dyn_cast<ConstantFP>(Op0))
     if (CFP->isExactlyValue(-0.0) && OperatorClass == 1) {
@@ -1965,7 +2245,7 @@ void ISel::emitBinaryFPOperation(MachineBasicBlock *BB,
         { X86::FADD32m, X86::FSUBR32m, X86::FMUL32m, X86::FDIVR32m }, // Float
         { X86::FADD64m, X86::FSUBR64m, X86::FMUL64m, X86::FDIVR64m }, // Double
       };
-      
+
       assert(Ty == Type::FloatTy||Ty == Type::DoubleTy && "Unknown FP type!");
       unsigned Opcode = OpcodeTab[Ty != Type::FloatTy][OperatorClass];
       unsigned Op1r = getReg(Op1, BB, IP);
@@ -1992,10 +2272,11 @@ void ISel::emitBinaryFPOperation(MachineBasicBlock *BB,
 /// emitSimpleBinaryOperation - Common code shared between visitSimpleBinary
 /// and constant expression support.
 ///
-void ISel::emitSimpleBinaryOperation(MachineBasicBlock *MBB,
-                                     MachineBasicBlock::iterator IP,
-                                     Value *Op0, Value *Op1,
-                                     unsigned OperatorClass, unsigned DestReg) {
+void X86ISel::emitSimpleBinaryOperation(MachineBasicBlock *MBB,
+                                        MachineBasicBlock::iterator IP,
+                                        Value *Op0, Value *Op1,
+                                        unsigned OperatorClass,
+                                        unsigned DestReg) {
   unsigned Class = getClassB(Op0->getType());
 
   if (Class == cFP) {
@@ -2004,24 +2285,40 @@ void ISel::emitSimpleBinaryOperation(MachineBasicBlock *MBB,
     return;
   }
 
-  // sub 0, X -> neg X
   if (ConstantInt *CI = dyn_cast<ConstantInt>(Op0))
-    if (OperatorClass == 1 && CI->isNullValue()) {
-      unsigned op1Reg = getReg(Op1, MBB, IP);
+    if (OperatorClass == 1) {
       static unsigned const NEGTab[] = {
         X86::NEG8r, X86::NEG16r, X86::NEG32r, 0, X86::NEG32r
       };
-      BuildMI(*MBB, IP, NEGTab[Class], 1, DestReg).addReg(op1Reg);
-      
-      if (Class == cLong) {
-        // We just emitted: Dl = neg Sl
-        // Now emit       : T  = addc Sh, 0
-        //                : Dh = neg T
-        unsigned T = makeAnotherReg(Type::IntTy);
-        BuildMI(*MBB, IP, X86::ADC32ri, 2, T).addReg(op1Reg+1).addImm(0);
-        BuildMI(*MBB, IP, X86::NEG32r, 1, DestReg+1).addReg(T);
+
+      // sub 0, X -> neg X
+      if (CI->isNullValue()) {
+        unsigned op1Reg = getReg(Op1, MBB, IP);
+        BuildMI(*MBB, IP, NEGTab[Class], 1, DestReg).addReg(op1Reg);
+
+        if (Class == cLong) {
+          // We just emitted: Dl = neg Sl
+          // Now emit       : T  = addc Sh, 0
+          //                : Dh = neg T
+          unsigned T = makeAnotherReg(Type::IntTy);
+          BuildMI(*MBB, IP, X86::ADC32ri, 2, T).addReg(op1Reg+1).addImm(0);
+          BuildMI(*MBB, IP, X86::NEG32r, 1, DestReg+1).addReg(T);
+        }
+        return;
+      } else if (Op1->hasOneUse() && Class != cLong) {
+        // sub C, X -> tmp = neg X; DestReg = add tmp, C.  This is better
+        // than copying C into a temporary register, because of register
+        // pressure (tmp and destreg can share a register.
+        static unsigned const ADDRITab[] = {
+          X86::ADD8ri, X86::ADD16ri, X86::ADD32ri, 0, X86::ADD32ri
+        };
+        unsigned op1Reg = getReg(Op1, MBB, IP);
+        unsigned Tmp = makeAnotherReg(Op0->getType());
+        BuildMI(*MBB, IP, NEGTab[Class], 1, Tmp).addReg(op1Reg);
+        BuildMI(*MBB, IP, ADDRITab[Class], 2,
+                DestReg).addReg(Tmp).addImm(CI->getRawValue());
+        return;
       }
-      return;
     }
 
   // Special case: op Reg, <const int>
@@ -2056,18 +2353,18 @@ void ISel::emitSimpleBinaryOperation(MachineBasicBlock *MBB,
       BuildMI(*MBB, IP, INCTab[Class], 1, DestReg).addReg(Op0r);
       return;
     }
-  
+
     static const unsigned OpcodeTab[][5] = {
       // Arithmetic operators
       { X86::ADD8ri, X86::ADD16ri, X86::ADD32ri, 0, X86::ADD32ri },  // ADD
       { X86::SUB8ri, X86::SUB16ri, X86::SUB32ri, 0, X86::SUB32ri },  // SUB
-    
+
       // Bitwise operators
       { X86::AND8ri, X86::AND16ri, X86::AND32ri, 0, X86::AND32ri },  // AND
       { X86:: OR8ri, X86:: OR16ri, X86:: OR32ri, 0, X86::OR32ri  },  // OR
       { X86::XOR8ri, X86::XOR16ri, X86::XOR32ri, 0, X86::XOR32ri },  // XOR
     };
-  
+
     unsigned Opcode = OpcodeTab[OperatorClass][Class];
     unsigned Op1l = cast<ConstantInt>(Op1C)->getRawValue();
 
@@ -2075,11 +2372,11 @@ void ISel::emitSimpleBinaryOperation(MachineBasicBlock *MBB,
       BuildMI(*MBB, IP, Opcode, 2, DestReg).addReg(Op0r).addImm(Op1l);
       return;
     }
-    
+
     // If this is a long value and the high or low bits have a special
     // property, emit some special cases.
     unsigned Op1h = cast<ConstantInt>(Op1C)->getRawValue() >> 32LL;
-    
+
     // If the constant is zero in the low 32-bits, just copy the low part
     // across and apply the normal 32-bit operation to the high parts.  There
     // will be no carry or borrow into the top.
@@ -2092,7 +2389,7 @@ void ISel::emitSimpleBinaryOperation(MachineBasicBlock *MBB,
         .addReg(Op0r+1).addImm(Op1h);
       return;
     }
-    
+
     // If this is a logical operation and the top 32-bits are zero, just
     // operate on the lower 32.
     if (Op1h == 0 && OperatorClass > 1) {
@@ -2104,15 +2401,15 @@ void ISel::emitSimpleBinaryOperation(MachineBasicBlock *MBB,
         BuildMI(*MBB, IP, X86::MOV32ri, 1, DestReg+1).addImm(0);
       return;
     }
-    
+
     // TODO: We could handle lots of other special cases here, such as AND'ing
     // with 0xFFFFFFFF00000000 -> noop, etc.
-    
+
     // Otherwise, code generate the full operation with a constant.
     static const unsigned TopTab[] = {
       X86::ADC32ri, X86::SBB32ri, X86::AND32ri, X86::OR32ri, X86::XOR32ri
     };
-    
+
     BuildMI(*MBB, IP, Opcode, 2, DestReg).addReg(Op0r).addImm(Op1l);
     BuildMI(*MBB, IP, TopTab[OperatorClass], 2, DestReg+1)
       .addReg(Op0r+1).addImm(Op1h);
@@ -2124,18 +2421,18 @@ void ISel::emitSimpleBinaryOperation(MachineBasicBlock *MBB,
     // Arithmetic operators
     { X86::ADD8rr, X86::ADD16rr, X86::ADD32rr, 0, X86::ADD32rr },  // ADD
     { X86::SUB8rr, X86::SUB16rr, X86::SUB32rr, 0, X86::SUB32rr },  // SUB
-      
+
     // Bitwise operators
     { X86::AND8rr, X86::AND16rr, X86::AND32rr, 0, X86::AND32rr },  // AND
     { X86:: OR8rr, X86:: OR16rr, X86:: OR32rr, 0, X86:: OR32rr },  // OR
     { X86::XOR8rr, X86::XOR16rr, X86::XOR32rr, 0, X86::XOR32rr },  // XOR
   };
-    
+
   unsigned Opcode = OpcodeTab[OperatorClass][Class];
   unsigned Op0r = getReg(Op0, MBB, IP);
   unsigned Op1r = getReg(Op1, MBB, IP);
   BuildMI(*MBB, IP, Opcode, 2, DestReg).addReg(Op0r).addReg(Op1r);
-    
+
   if (Class == cLong) {        // Handle the upper 32 bits of long values...
     static const unsigned TopTab[] = {
       X86::ADC32rr, X86::SBB32rr, X86::AND32rr, X86::OR32rr, X86::XOR32rr
@@ -2149,9 +2446,10 @@ void ISel::emitSimpleBinaryOperation(MachineBasicBlock *MBB,
 /// registers op0Reg and op1Reg, and put the result in DestReg.  The type of the
 /// result should be given as DestTy.
 ///
-void ISel::doMultiply(MachineBasicBlock *MBB, MachineBasicBlock::iterator MBBI,
-                      unsigned DestReg, const Type *DestTy,
-                      unsigned op0Reg, unsigned op1Reg) {
+void X86ISel::doMultiply(MachineBasicBlock *MBB,
+                         MachineBasicBlock::iterator MBBI,
+                         unsigned DestReg, const Type *DestTy,
+                         unsigned op0Reg, unsigned op1Reg) {
   unsigned Class = getClass(DestTy);
   switch (Class) {
   case cInt:
@@ -2173,10 +2471,9 @@ void ISel::doMultiply(MachineBasicBlock *MBB, MachineBasicBlock::iterator MBBI,
 // 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) {
-  if (Val == 0) return 0;
+  if (Val == 0 || (Val & (Val-1))) return 0;
   unsigned Count = 0;
   while (Val != 1) {
-    if (Val & 1) return 0;
     Val >>= 1;
     ++Count;
   }
@@ -2186,21 +2483,65 @@ static unsigned ExactLog2(unsigned Val) {
 
 /// doMultiplyConst - This function is specialized to efficiently codegen an 8,
 /// 16, or 32-bit integer multiply by a constant.
-void ISel::doMultiplyConst(MachineBasicBlock *MBB,
-                           MachineBasicBlock::iterator IP,
-                           unsigned DestReg, const Type *DestTy,
-                           unsigned op0Reg, unsigned ConstRHS) {
+void X86ISel::doMultiplyConst(MachineBasicBlock *MBB,
+                              MachineBasicBlock::iterator IP,
+                              unsigned DestReg, const Type *DestTy,
+                              unsigned op0Reg, unsigned ConstRHS) {
   static const unsigned MOVrrTab[] = {X86::MOV8rr, X86::MOV16rr, X86::MOV32rr};
   static const unsigned MOVriTab[] = {X86::MOV8ri, X86::MOV16ri, X86::MOV32ri};
+  static const unsigned ADDrrTab[] = {X86::ADD8rr, X86::ADD16rr, X86::ADD32rr};
+  static const unsigned NEGrTab[]  = {X86::NEG8r , X86::NEG16r , X86::NEG32r };
 
   unsigned Class = getClass(DestTy);
-
-  if (ConstRHS == 0) {
+  unsigned TmpReg;
+
+  // Handle special cases here.
+  switch (ConstRHS) {
+  case -2:
+    TmpReg = makeAnotherReg(DestTy);
+    BuildMI(*MBB, IP, NEGrTab[Class], 1, TmpReg).addReg(op0Reg);
+    BuildMI(*MBB, IP, ADDrrTab[Class], 1,DestReg).addReg(TmpReg).addReg(TmpReg);
+    return;
+  case -1:
+    BuildMI(*MBB, IP, NEGrTab[Class], 1, DestReg).addReg(op0Reg);
+    return;
+  case 0:
     BuildMI(*MBB, IP, MOVriTab[Class], 1, DestReg).addImm(0);
     return;
-  } else if (ConstRHS == 1) {
+  case 1:
     BuildMI(*MBB, IP, MOVrrTab[Class], 1, DestReg).addReg(op0Reg);
     return;
+  case 2:
+    BuildMI(*MBB, IP, ADDrrTab[Class], 1,DestReg).addReg(op0Reg).addReg(op0Reg);
+    return;
+  case 3:
+  case 5:
+  case 9:
+    if (Class == cInt) {
+      X86AddressMode AM;
+      AM.BaseType = X86AddressMode::RegBase;
+      AM.Base.Reg = op0Reg;
+      AM.Scale = ConstRHS-1;
+      AM.IndexReg = op0Reg;
+      AM.Disp = 0;
+      addFullAddress(BuildMI(*MBB, IP, X86::LEA32r, 5, DestReg), AM);
+      return;
+    }
+  case -3:
+  case -5:
+  case -9:
+    if (Class == cInt) {
+      TmpReg = makeAnotherReg(DestTy);
+      X86AddressMode AM;
+      AM.BaseType = X86AddressMode::RegBase;
+      AM.Base.Reg = op0Reg;
+      AM.Scale = -ConstRHS-1;
+      AM.IndexReg = op0Reg;
+      AM.Disp = 0;
+      addFullAddress(BuildMI(*MBB, IP, X86::LEA32r, 5, TmpReg), AM);
+      BuildMI(*MBB, IP, NEGrTab[Class], 1, DestReg).addReg(TmpReg);
+      return;
+    }
   }
 
   // If the element size is exactly a power of 2, use a shift to get it.
@@ -2208,17 +2549,35 @@ void ISel::doMultiplyConst(MachineBasicBlock *MBB,
     switch (Class) {
     default: assert(0 && "Unknown class for this function!");
     case cByte:
-      BuildMI(*MBB, IP, X86::SHL32ri,2, DestReg).addReg(op0Reg).addImm(Shift-1);
+      BuildMI(*MBB, IP, X86::SHL8ri,2, DestReg).addReg(op0Reg).addImm(Shift-1);
       return;
     case cShort:
-      BuildMI(*MBB, IP, X86::SHL32ri,2, DestReg).addReg(op0Reg).addImm(Shift-1);
+      BuildMI(*MBB, IP, X86::SHL16ri,2, DestReg).addReg(op0Reg).addImm(Shift-1);
       return;
     case cInt:
       BuildMI(*MBB, IP, X86::SHL32ri,2, DestReg).addReg(op0Reg).addImm(Shift-1);
       return;
     }
   }
-  
+
+  // If the element size is a negative power of 2, use a shift/neg to get it.
+  if (unsigned Shift = ExactLog2(-ConstRHS)) {
+    TmpReg = makeAnotherReg(DestTy);
+    BuildMI(*MBB, IP, NEGrTab[Class], 1, TmpReg).addReg(op0Reg);
+    switch (Class) {
+    default: assert(0 && "Unknown class for this function!");
+    case cByte:
+      BuildMI(*MBB, IP, X86::SHL8ri,2, DestReg).addReg(TmpReg).addImm(Shift-1);
+      return;
+    case cShort:
+      BuildMI(*MBB, IP, X86::SHL16ri,2, DestReg).addReg(TmpReg).addImm(Shift-1);
+      return;
+    case cInt:
+      BuildMI(*MBB, IP, X86::SHL32ri,2, DestReg).addReg(TmpReg).addImm(Shift-1);
+      return;
+    }
+  }
+
   if (Class == cShort) {
     BuildMI(*MBB, IP, X86::IMUL16rri,2,DestReg).addReg(op0Reg).addImm(ConstRHS);
     return;
@@ -2228,9 +2587,9 @@ void ISel::doMultiplyConst(MachineBasicBlock *MBB,
   }
 
   // Most general case, emit a normal multiply...
-  unsigned TmpReg = makeAnotherReg(DestTy);
+  TmpReg = makeAnotherReg(DestTy);
   BuildMI(*MBB, IP, MOVriTab[Class], 1, TmpReg).addImm(ConstRHS);
-  
+
   // Emit a MUL to multiply the register holding the index by
   // elementSize, putting the result in OffsetReg.
   doMultiply(MBB, IP, DestReg, DestTy, op0Reg, TmpReg);
@@ -2239,7 +2598,7 @@ void ISel::doMultiplyConst(MachineBasicBlock *MBB,
 /// visitMul - Multiplies are not simple binary operators because they must deal
 /// with the EAX register explicitly.
 ///
-void ISel::visitMul(BinaryOperator &I) {
+void X86ISel::visitMul(BinaryOperator &I) {
   unsigned ResultReg = getReg(I);
 
   Value *Op0 = I.getOperand(0);
@@ -2255,14 +2614,17 @@ void ISel::visitMul(BinaryOperator &I) {
         const Type *Ty = Op0->getType();
         assert(Ty == Type::FloatTy||Ty == Type::DoubleTy && "Unknown FP type!");
         unsigned Opcode = Ty == Type::FloatTy ? X86::FMUL32m : X86::FMUL64m;
-        
-        unsigned BaseReg, Scale, IndexReg, Disp;
-        getAddressingMode(LI->getOperand(0), BaseReg,
-                          Scale, IndexReg, Disp);
-        
+
         unsigned Op0r = getReg(Op0);
-        addFullAddress(BuildMI(BB, Opcode, 2, ResultReg).addReg(Op0r),
-                       BaseReg, Scale, IndexReg, Disp);
+        if (AllocaInst *AI = dyn_castFixedAlloca(LI->getOperand(0))) {
+          unsigned FI = getFixedSizedAllocaFI(AI);
+          addFrameReference(BuildMI(BB, Opcode, 5, ResultReg).addReg(Op0r), FI);
+        } else {
+          X86AddressMode AM;
+          getAddressingMode(LI->getOperand(0), AM);
+
+          addFullAddress(BuildMI(BB, Opcode, 5, ResultReg).addReg(Op0r), AM);
+        }
         return;
       }
   }
@@ -2271,8 +2633,9 @@ void ISel::visitMul(BinaryOperator &I) {
   emitMultiply(BB, IP, Op0, Op1, ResultReg);
 }
 
-void ISel::emitMultiply(MachineBasicBlock *MBB, MachineBasicBlock::iterator IP,
-                        Value *Op0, Value *Op1, unsigned DestReg) {
+void X86ISel::emitMultiply(MachineBasicBlock *MBB,
+                           MachineBasicBlock::iterator IP,
+                           Value *Op0, Value *Op1, unsigned DestReg) {
   MachineBasicBlock &BB = *MBB;
   TypeClass Class = getClass(Op0->getType());
 
@@ -2301,14 +2664,14 @@ void ISel::emitMultiply(MachineBasicBlock *MBB, MachineBasicBlock::iterator IP,
   if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
     unsigned CLow = CI->getRawValue();
     unsigned CHi  = CI->getRawValue() >> 32;
-    
+
     if (CLow == 0) {
       // If the low part of the constant is all zeros, things are simple.
       BuildMI(BB, IP, X86::MOV32ri, 1, DestReg).addImm(0);
       doMultiplyConst(&BB, IP, DestReg+1, Type::UIntTy, Op0Reg, CHi);
       return;
     }
-    
+
     // Multiply the two low parts... capturing carry into EDX
     unsigned OverflowReg = 0;
     if (CLow == 1) {
@@ -2319,15 +2682,15 @@ void ISel::emitMultiply(MachineBasicBlock *MBB, MachineBasicBlock::iterator IP,
       BuildMI(BB, IP, X86::MOV32ri, 1, Op1RegL).addImm(CLow);
       BuildMI(BB, IP, X86::MOV32rr, 1, X86::EAX).addReg(Op0Reg);
       BuildMI(BB, IP, X86::MUL32r, 1).addReg(Op1RegL);  // AL*BL
-      
+
       BuildMI(BB, IP, X86::MOV32rr, 1, DestReg).addReg(X86::EAX);   // AL*BL
       BuildMI(BB, IP, X86::MOV32rr, 1,
               OverflowReg).addReg(X86::EDX);                    // AL*BL >> 32
     }
-    
+
     unsigned AHBLReg = makeAnotherReg(Type::UIntTy);   // AH*BL
     doMultiplyConst(&BB, IP, AHBLReg, Type::UIntTy, Op0Reg+1, CLow);
-    
+
     unsigned AHBLplusOverflowReg;
     if (OverflowReg) {
       AHBLplusOverflowReg = makeAnotherReg(Type::UIntTy);
@@ -2336,13 +2699,13 @@ void ISel::emitMultiply(MachineBasicBlock *MBB, MachineBasicBlock::iterator IP,
     } else {
       AHBLplusOverflowReg = AHBLReg;
     }
-    
+
     if (CHi == 0) {
       BuildMI(BB, IP, X86::MOV32rr, 1, DestReg+1).addReg(AHBLplusOverflowReg);
     } else {
       unsigned ALBHReg = makeAnotherReg(Type::UIntTy); // AL*BH
       doMultiplyConst(&BB, IP, ALBHReg, Type::UIntTy, Op0Reg, CHi);
-      
+
       BuildMI(BB, IP, X86::ADD32rr, 2,      // AL*BH + AH*BL + (AL*BL >> 32)
               DestReg+1).addReg(AHBLplusOverflowReg).addReg(ALBHReg);
     }
@@ -2355,24 +2718,24 @@ void ISel::emitMultiply(MachineBasicBlock *MBB, MachineBasicBlock::iterator IP,
   // Multiply the two low parts... capturing carry into EDX
   BuildMI(BB, IP, X86::MOV32rr, 1, X86::EAX).addReg(Op0Reg);
   BuildMI(BB, IP, X86::MUL32r, 1).addReg(Op1Reg);  // AL*BL
-  
+
   unsigned OverflowReg = makeAnotherReg(Type::UIntTy);
   BuildMI(BB, IP, X86::MOV32rr, 1, DestReg).addReg(X86::EAX);     // AL*BL
   BuildMI(BB, IP, X86::MOV32rr, 1,
           OverflowReg).addReg(X86::EDX); // AL*BL >> 32
-  
+
   unsigned AHBLReg = makeAnotherReg(Type::UIntTy);   // AH*BL
   BuildMI(BB, IP, X86::IMUL32rr, 2,
           AHBLReg).addReg(Op0Reg+1).addReg(Op1Reg);
-  
+
   unsigned AHBLplusOverflowReg = makeAnotherReg(Type::UIntTy);
   BuildMI(BB, IP, X86::ADD32rr, 2,                // AH*BL+(AL*BL >> 32)
           AHBLplusOverflowReg).addReg(AHBLReg).addReg(OverflowReg);
-  
+
   unsigned ALBHReg = makeAnotherReg(Type::UIntTy); // AL*BH
   BuildMI(BB, IP, X86::IMUL32rr, 2,
           ALBHReg).addReg(Op0Reg).addReg(Op1Reg+1);
-  
+
   BuildMI(BB, IP, X86::ADD32rr, 2,      // AL*BH + AH*BL + (AL*BL >> 32)
           DestReg+1).addReg(AHBLplusOverflowReg).addReg(ALBHReg);
 }
@@ -2383,7 +2746,7 @@ void ISel::emitMultiply(MachineBasicBlock *MBB, MachineBasicBlock::iterator IP,
 /// select the result from a different register.  Note that both of these
 /// instructions work differently for signed and unsigned operands.
 ///
-void ISel::visitDivRem(BinaryOperator &I) {
+void X86ISel::visitDivRem(BinaryOperator &I) {
   unsigned ResultReg = getReg(I);
   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
 
@@ -2394,14 +2757,17 @@ void ISel::visitDivRem(BinaryOperator &I) {
         const Type *Ty = Op0->getType();
         assert(Ty == Type::FloatTy||Ty == Type::DoubleTy && "Unknown FP type!");
         unsigned Opcode = Ty == Type::FloatTy ? X86::FDIV32m : X86::FDIV64m;
-        
-        unsigned BaseReg, Scale, IndexReg, Disp;
-        getAddressingMode(LI->getOperand(0), BaseReg,
-                          Scale, IndexReg, Disp);
-        
+
         unsigned Op0r = getReg(Op0);
-        addFullAddress(BuildMI(BB, Opcode, 2, ResultReg).addReg(Op0r),
-                       BaseReg, Scale, IndexReg, Disp);
+        if (AllocaInst *AI = dyn_castFixedAlloca(LI->getOperand(0))) {
+          unsigned FI = getFixedSizedAllocaFI(AI);
+          addFrameReference(BuildMI(BB, Opcode, 5, ResultReg).addReg(Op0r), FI);
+        } else {
+          X86AddressMode AM;
+          getAddressingMode(LI->getOperand(0), AM);
+
+          addFullAddress(BuildMI(BB, Opcode, 5, ResultReg).addReg(Op0r), AM);
+        }
         return;
       }
 
@@ -2410,14 +2776,16 @@ void ISel::visitDivRem(BinaryOperator &I) {
         const Type *Ty = Op0->getType();
         assert(Ty == Type::FloatTy||Ty == Type::DoubleTy && "Unknown FP type!");
         unsigned Opcode = Ty == Type::FloatTy ? X86::FDIVR32m : X86::FDIVR64m;
-        
-        unsigned BaseReg, Scale, IndexReg, Disp;
-        getAddressingMode(LI->getOperand(0), BaseReg,
-                          Scale, IndexReg, Disp);
-        
+
         unsigned Op1r = getReg(Op1);
-        addFullAddress(BuildMI(BB, Opcode, 2, ResultReg).addReg(Op1r),
-                       BaseReg, Scale, IndexReg, Disp);
+        if (AllocaInst *AI = dyn_castFixedAlloca(LI->getOperand(0))) {
+          unsigned FI = getFixedSizedAllocaFI(AI);
+          addFrameReference(BuildMI(BB, Opcode, 5, ResultReg).addReg(Op1r), FI);
+        } else {
+          X86AddressMode AM;
+          getAddressingMode(LI->getOperand(0), AM);
+          addFullAddress(BuildMI(BB, Opcode, 5, ResultReg).addReg(Op1r), AM);
+        }
         return;
       }
   }
@@ -2428,10 +2796,10 @@ void ISel::visitDivRem(BinaryOperator &I) {
                       I.getOpcode() == Instruction::Div, ResultReg);
 }
 
-void ISel::emitDivRemOperation(MachineBasicBlock *BB,
-                               MachineBasicBlock::iterator IP,
-                               Value *Op0, Value *Op1, bool isDiv,
-                               unsigned ResultReg) {
+void X86ISel::emitDivRemOperation(MachineBasicBlock *BB,
+                                  MachineBasicBlock::iterator IP,
+                                  Value *Op0, Value *Op1, bool isDiv,
+                                  unsigned ResultReg) {
   const Type *Ty = Op0->getType();
   unsigned Class = getClass(Ty);
   switch (Class) {
@@ -2470,18 +2838,124 @@ void ISel::emitDivRemOperation(MachineBasicBlock *BB,
   default: assert(0 && "Unknown class!");
   }
 
-  static const unsigned Regs[]     ={ X86::AL    , X86::AX     , X86::EAX     };
   static const unsigned MovOpcode[]={ X86::MOV8rr, X86::MOV16rr, X86::MOV32rr };
-  static const unsigned SarOpcode[]={ X86::SAR8ri, X86::SAR16ri, X86::SAR32ri };
+  static const unsigned NEGOpcode[]={ X86::NEG8r,  X86::NEG16r,  X86::NEG32r };
+  static const unsigned SAROpcode[]={ X86::SAR8ri, X86::SAR16ri, X86::SAR32ri };
+  static const unsigned SHROpcode[]={ X86::SHR8ri, X86::SHR16ri, X86::SHR32ri };
+  static const unsigned ADDOpcode[]={ X86::ADD8rr, X86::ADD16rr, X86::ADD32rr };
+
+  // Special case signed division by power of 2.
+  if (ConstantSInt *CI = dyn_cast<ConstantSInt>(Op1))
+    if (isDiv) {
+      assert(Class != cLong && "This doesn't handle 64-bit divides!");
+      int V = CI->getValue();
+
+      if (V == 1) {       // X /s 1 => X
+        unsigned Op0Reg = getReg(Op0, BB, IP);
+        BuildMI(*BB, IP, MovOpcode[Class], 1, ResultReg).addReg(Op0Reg);
+        return;
+      }
+
+      if (V == -1) {      // X /s -1 => -X
+        unsigned Op0Reg = getReg(Op0, BB, IP);
+        BuildMI(*BB, IP, NEGOpcode[Class], 1, ResultReg).addReg(Op0Reg);
+        return;
+      }
+
+      if (V == 2 || V == -2) {      // X /s 2
+        static const unsigned CMPOpcode[] = {
+          X86::CMP8ri, X86::CMP16ri, X86::CMP32ri
+        };
+        static const unsigned SBBOpcode[] = {
+          X86::SBB8ri, X86::SBB16ri, X86::SBB32ri
+        };
+        unsigned Op0Reg = getReg(Op0, BB, IP);
+        unsigned SignBit = 1 << (CI->getType()->getPrimitiveSize()*8-1);
+        BuildMI(*BB, IP, CMPOpcode[Class], 2).addReg(Op0Reg).addImm(SignBit);
+
+        unsigned TmpReg = makeAnotherReg(Op0->getType());
+        BuildMI(*BB, IP, SBBOpcode[Class], 2, TmpReg).addReg(Op0Reg).addImm(-1);
+
+        unsigned TmpReg2 = V == 2 ? ResultReg : makeAnotherReg(Op0->getType());
+        BuildMI(*BB, IP, SAROpcode[Class], 2, TmpReg2).addReg(TmpReg).addImm(1);
+        if (V == -2) {
+          BuildMI(*BB, IP, NEGOpcode[Class], 1, ResultReg).addReg(TmpReg2);
+        }
+        return;
+      }
+
+      bool isNeg = false;
+      if (V < 0) {         // Not a positive power of 2?
+        V = -V;
+        isNeg = true;      // Maybe it's a negative power of 2.
+      }
+      if (unsigned Log = ExactLog2(V)) {
+        --Log;
+        unsigned Op0Reg = getReg(Op0, BB, IP);
+        unsigned TmpReg = makeAnotherReg(Op0->getType());
+        BuildMI(*BB, IP, SAROpcode[Class], 2, TmpReg)
+          .addReg(Op0Reg).addImm(Log-1);
+        unsigned TmpReg2 = makeAnotherReg(Op0->getType());
+        BuildMI(*BB, IP, SHROpcode[Class], 2, TmpReg2)
+          .addReg(TmpReg).addImm(32-Log);
+        unsigned TmpReg3 = makeAnotherReg(Op0->getType());
+        BuildMI(*BB, IP, ADDOpcode[Class], 2, TmpReg3)
+          .addReg(Op0Reg).addReg(TmpReg2);
+
+        unsigned TmpReg4 = isNeg ? makeAnotherReg(Op0->getType()) : ResultReg;
+        BuildMI(*BB, IP, SAROpcode[Class], 2, TmpReg4)
+          .addReg(TmpReg3).addImm(Log);
+        if (isNeg)
+          BuildMI(*BB, IP, NEGOpcode[Class], 1, ResultReg).addReg(TmpReg4);
+        return;
+      }
+    } else {    // X % C
+      assert(Class != cLong && "This doesn't handle 64-bit remainder!");
+      int V = CI->getValue();
+
+      if (V == 2 || V == -2) {       // X % 2, X % -2
+        static const unsigned SExtOpcode[] = { X86::CBW, X86::CWD, X86::CDQ };
+        static const unsigned BaseReg[]    = { X86::AL , X86::AX , X86::EAX };
+        static const unsigned SExtReg[]    = { X86::AH , X86::DX , X86::EDX };
+        static const unsigned ANDOpcode[]  = {
+          X86::AND8ri, X86::AND16ri, X86::AND32ri
+        };
+        static const unsigned XOROpcode[]  = {
+          X86::XOR8rr, X86::XOR16rr, X86::XOR32rr
+        };
+        static const unsigned SUBOpcode[]  = {
+          X86::SUB8rr, X86::SUB16rr, X86::SUB32rr
+        };
+
+        // Sign extend result into reg of -1 or 0.
+        unsigned Op0Reg = getReg(Op0, BB, IP);
+        BuildMI(*BB, IP, MovOpcode[Class], 1, BaseReg[Class]).addReg(Op0Reg);
+        BuildMI(*BB, IP, SExtOpcode[Class], 0);
+        unsigned TmpReg0 = makeAnotherReg(Op0->getType());
+        BuildMI(*BB, IP, MovOpcode[Class], 1, TmpReg0).addReg(SExtReg[Class]);
+
+        unsigned TmpReg1 = makeAnotherReg(Op0->getType());
+        BuildMI(*BB, IP, ANDOpcode[Class], 2, TmpReg1).addReg(Op0Reg).addImm(1);
+
+        unsigned TmpReg2 = makeAnotherReg(Op0->getType());
+        BuildMI(*BB, IP, XOROpcode[Class], 2,
+                TmpReg2).addReg(TmpReg1).addReg(TmpReg0);
+        BuildMI(*BB, IP, SUBOpcode[Class], 2,
+                ResultReg).addReg(TmpReg2).addReg(TmpReg0);
+        return;
+      }
+    }
+
+  static const unsigned Regs[]     ={ X86::AL    , X86::AX     , X86::EAX     };
   static const unsigned ClrOpcode[]={ X86::MOV8ri, X86::MOV16ri, X86::MOV32ri };
   static const unsigned ExtRegs[]  ={ X86::AH    , X86::DX     , X86::EDX     };
+  static const unsigned SExOpcode[]={ X86::CBW   , X86::CWD    , X86::CDQ     };
 
   static const unsigned DivOpcode[][4] = {
     { X86::DIV8r , X86::DIV16r , X86::DIV32r , 0 },  // Unsigned division
     { X86::IDIV8r, X86::IDIV16r, X86::IDIV32r, 0 },  // Signed division
   };
 
-  bool isSigned   = Ty->isSigned();
   unsigned Reg    = Regs[Class];
   unsigned ExtReg = ExtRegs[Class];
 
@@ -2490,22 +2964,23 @@ void ISel::emitDivRemOperation(MachineBasicBlock *BB,
   unsigned Op1Reg = getReg(Op1, BB, IP);
   BuildMI(*BB, IP, MovOpcode[Class], 1, Reg).addReg(Op0Reg);
 
-  if (isSigned) {
-    // Emit a sign extension instruction...
-    unsigned ShiftResult = makeAnotherReg(Op0->getType());
-    BuildMI(*BB, IP, SarOpcode[Class], 2,ShiftResult).addReg(Op0Reg).addImm(31);
-    BuildMI(*BB, IP, MovOpcode[Class], 1, ExtReg).addReg(ShiftResult);
+  if (Ty->isSigned()) {
+    // Emit a sign extension instruction.
+    BuildMI(*BB, IP, SExOpcode[Class], 0);
+
+    // Emit the appropriate divide or remainder instruction...
+    BuildMI(*BB, IP, DivOpcode[1][Class], 1).addReg(Op1Reg);
   } else {
     // If unsigned, emit a zeroing instruction... (reg = 0)
     BuildMI(*BB, IP, ClrOpcode[Class], 2, ExtReg).addImm(0);
-  }
 
-  // Emit the appropriate divide or remainder instruction...
-  BuildMI(*BB, IP, DivOpcode[isSigned][Class], 1).addReg(Op1Reg);
+    // Emit the appropriate divide or remainder instruction...
+    BuildMI(*BB, IP, DivOpcode[0][Class], 1).addReg(Op1Reg);
+  }
 
   // Figure out which register we want to pick the result out of...
   unsigned DestReg = isDiv ? Reg : ExtReg;
-  
+
   // Put the result into the destination register...
   BuildMI(*BB, IP, MovOpcode[Class], 1, ResultReg).addReg(DestReg);
 }
@@ -2516,78 +2991,123 @@ void ISel::emitDivRemOperation(MachineBasicBlock *BB,
 /// shift values equal to 1. Even the general case is sort of special,
 /// because the shift amount has to be in CL, not just any old register.
 ///
-void ISel::visitShiftInst(ShiftInst &I) {
+void X86ISel::visitShiftInst(ShiftInst &I) {
   MachineBasicBlock::iterator IP = BB->end ();
   emitShiftOperation (BB, IP, I.getOperand (0), I.getOperand (1),
                       I.getOpcode () == Instruction::Shl, I.getType (),
                       getReg (I));
 }
 
+/// Emit code for a 'SHLD DestReg, Op0, Op1, Amt' operation, where Amt is a
+/// constant.
+void X86ISel::doSHLDConst(MachineBasicBlock *MBB,
+                          MachineBasicBlock::iterator IP,
+                          unsigned DestReg, unsigned Op0Reg, unsigned Op1Reg,
+                          unsigned Amt) {
+  // SHLD is a very inefficient operation on every processor, try to do
+  // somethign simpler for common values of 'Amt'.
+  if (Amt == 0) {
+    BuildMI(*MBB, IP, X86::MOV32rr, 1, DestReg).addReg(Op0Reg);
+  } else if (Amt == 1) {
+    unsigned Tmp = makeAnotherReg(Type::UIntTy);
+    BuildMI(*MBB, IP, X86::ADD32rr, 2, Tmp).addReg(Op1Reg).addReg(Op1Reg);
+    BuildMI(*MBB, IP, X86::ADC32rr, 2, DestReg).addReg(Op0Reg).addReg(Op0Reg);
+  } else if (Amt == 2 || Amt == 3) {
+    // On the P4 and Athlon it is cheaper to replace shld ..., 2|3 with a
+    // shift/lea pair.  NOTE: This should not be done on the P6 family!
+    unsigned Tmp = makeAnotherReg(Type::UIntTy);
+    BuildMI(*MBB, IP, X86::SHR32ri, 2, Tmp).addReg(Op1Reg).addImm(32-Amt);
+    X86AddressMode AM;
+    AM.BaseType = X86AddressMode::RegBase;
+    AM.Base.Reg = Tmp;
+    AM.Scale = 1 << Amt;
+    AM.IndexReg = Op0Reg;
+    AM.Disp = 0;
+    addFullAddress(BuildMI(*MBB, IP, X86::LEA32r, 4, DestReg), AM);
+  } else {
+    // NOTE: It is always cheaper on the P4 to emit SHLD as two shifts and an OR
+    // than it is to emit a real SHLD.
+
+    BuildMI(*MBB, IP, X86::SHLD32rri8, 3,
+            DestReg).addReg(Op0Reg).addReg(Op1Reg).addImm(Amt);
+  }
+}
+
 /// emitShiftOperation - Common code shared between visitShiftInst and
 /// constant expression support.
-void ISel::emitShiftOperation(MachineBasicBlock *MBB,
-                              MachineBasicBlock::iterator IP,
-                              Value *Op, Value *ShiftAmount, bool isLeftShift,
-                              const Type *ResultTy, unsigned DestReg) {
+void X86ISel::emitShiftOperation(MachineBasicBlock *MBB,
+                                 MachineBasicBlock::iterator IP,
+                                 Value *Op, Value *ShiftAmount,
+                                 bool isLeftShift, const Type *ResultTy,
+                                 unsigned DestReg) {
   unsigned SrcReg = getReg (Op, MBB, IP);
   bool isSigned = ResultTy->isSigned ();
   unsigned Class = getClass (ResultTy);
-  
-  static const unsigned ConstantOperand[][4] = {
-    { X86::SHR8ri, X86::SHR16ri, X86::SHR32ri, X86::SHRD32rri8 },  // SHR
-    { X86::SAR8ri, X86::SAR16ri, X86::SAR32ri, X86::SHRD32rri8 },  // SAR
-    { X86::SHL8ri, X86::SHL16ri, X86::SHL32ri, X86::SHLD32rri8 },  // SHL
-    { X86::SHL8ri, X86::SHL16ri, X86::SHL32ri, X86::SHLD32rri8 },  // SAL = SHL
+
+  static const unsigned ConstantOperand[][3] = {
+    { X86::SHR8ri, X86::SHR16ri, X86::SHR32ri },  // SHR
+    { X86::SAR8ri, X86::SAR16ri, X86::SAR32ri },  // SAR
+    { X86::SHL8ri, X86::SHL16ri, X86::SHL32ri },  // SHL
+    { X86::SHL8ri, X86::SHL16ri, X86::SHL32ri },  // SAL = SHL
   };
 
-  static const unsigned NonConstantOperand[][4] = {
+  static const unsigned NonConstantOperand[][3] = {
     { X86::SHR8rCL, X86::SHR16rCL, X86::SHR32rCL },  // SHR
     { X86::SAR8rCL, X86::SAR16rCL, X86::SAR32rCL },  // SAR
     { X86::SHL8rCL, X86::SHL16rCL, X86::SHL32rCL },  // SHL
     { X86::SHL8rCL, X86::SHL16rCL, X86::SHL32rCL },  // SAL = SHL
   };
 
-  // Longs, as usual, are handled specially...
+  // Longs, as usual, are handled specially.
   if (Class == cLong) {
-    // If we have a constant shift, we can generate much more efficient code
-    // than otherwise...
-    //
     if (ConstantUInt *CUI = dyn_cast<ConstantUInt>(ShiftAmount)) {
       unsigned Amount = CUI->getValue();
-      if (Amount < 32) {
+      if (Amount == 1 && isLeftShift) {   // X << 1 == X+X
+        BuildMI(*MBB, IP, X86::ADD32rr, 2,
+                DestReg).addReg(SrcReg).addReg(SrcReg);
+        BuildMI(*MBB, IP, X86::ADC32rr, 2,
+                DestReg+1).addReg(SrcReg+1).addReg(SrcReg+1);
+      } else if (Amount < 32) {
         const unsigned *Opc = ConstantOperand[isLeftShift*2+isSigned];
         if (isLeftShift) {
-          BuildMI(*MBB, IP, Opc[3], 3, 
-              DestReg+1).addReg(SrcReg+1).addReg(SrcReg).addImm(Amount);
+          doSHLDConst(MBB, IP, DestReg+1, SrcReg+1, SrcReg, Amount);
           BuildMI(*MBB, IP, Opc[2], 2, DestReg).addReg(SrcReg).addImm(Amount);
         } else {
-          BuildMI(*MBB, IP, Opc[3], 3,
-              DestReg).addReg(SrcReg  ).addReg(SrcReg+1).addImm(Amount);
+          BuildMI(*MBB, IP, X86::SHRD32rri8, 3,
+                  DestReg).addReg(SrcReg  ).addReg(SrcReg+1).addImm(Amount);
           BuildMI(*MBB, IP, Opc[2],2,DestReg+1).addReg(SrcReg+1).addImm(Amount);
         }
-      } else {                 // Shifting more than 32 bits
-        Amount -= 32;
+      } else if (Amount == 32) {
         if (isLeftShift) {
-          if (Amount != 0) {
-            BuildMI(*MBB, IP, X86::SHL32ri, 2,
-                    DestReg + 1).addReg(SrcReg).addImm(Amount);
-          } else {
-            BuildMI(*MBB, IP, X86::MOV32rr, 1, DestReg+1).addReg(SrcReg);
-          }
+          BuildMI(*MBB, IP, X86::MOV32rr, 1, DestReg+1).addReg(SrcReg);
           BuildMI(*MBB, IP, X86::MOV32ri, 1, DestReg).addImm(0);
         } else {
-          if (Amount != 0) {
-            BuildMI(*MBB, IP, isSigned ? X86::SAR32ri : X86::SHR32ri, 2,
-                    DestReg).addReg(SrcReg+1).addImm(Amount);
+          BuildMI(*MBB, IP, X86::MOV32rr, 1, DestReg).addReg(SrcReg+1);
+          if (!isSigned) {
+            BuildMI(*MBB, IP, X86::MOV32ri, 1, DestReg+1).addImm(0);
           } else {
-            BuildMI(*MBB, IP, X86::MOV32rr, 1, DestReg).addReg(SrcReg+1);
+            BuildMI(*MBB, IP, X86::SAR32ri, 2,
+                    DestReg+1).addReg(SrcReg).addImm(31);
           }
-          BuildMI(*MBB, IP, X86::MOV32ri, 1, DestReg+1).addImm(0);
+        }
+      } else {                 // Shifting more than 32 bits
+        Amount -= 32;
+        if (isLeftShift) {
+          BuildMI(*MBB, IP, X86::SHL32ri, 2,
+                  DestReg + 1).addReg(SrcReg).addImm(Amount);
+          BuildMI(*MBB, IP, X86::MOV32ri, 1, DestReg).addImm(0);
+        } else {
+          BuildMI(*MBB, IP, isSigned ? X86::SAR32ri : X86::SHR32ri, 2,
+                  DestReg).addReg(SrcReg+1).addImm(Amount);
+          if (isSigned)
+            BuildMI(*MBB, IP, X86::SAR32ri, 2,
+                    DestReg+1).addReg(SrcReg+1).addImm(31);
+          else
+            BuildMI(*MBB, IP, X86::MOV32ri, 1, DestReg+1).addImm(0);
         }
       }
     } else {
       unsigned TmpReg = makeAnotherReg(Type::IntTy);
-
       if (!isLeftShift && isSigned) {
         // If this is a SHR of a Long, then we need to do funny sign extension
         // stuff.  TmpReg gets the value to use as the high-part if we are
@@ -2616,7 +3136,7 @@ void ISel::emitShiftOperation(MachineBasicBlock *MBB,
         BuildMI(*MBB, IP, X86::TEST8ri, 2).addReg(X86::CL).addImm(32);
 
         // DestHi = (>32) ? TmpReg3 : TmpReg2;
-        BuildMI(*MBB, IP, X86::CMOVNE32rr, 2, 
+        BuildMI(*MBB, IP, X86::CMOVNE32rr, 2,
                 DestReg+1).addReg(TmpReg2).addReg(TmpReg3);
         // DestLo = (>32) ? TmpReg : TmpReg3;
         BuildMI(*MBB, IP, X86::CMOVNE32rr, 2,
@@ -2633,11 +3153,11 @@ void ISel::emitShiftOperation(MachineBasicBlock *MBB,
         BuildMI(*MBB, IP, X86::TEST8ri, 2).addReg(X86::CL).addImm(32);
 
         // DestLo = (>32) ? TmpReg3 : TmpReg2;
-        BuildMI(*MBB, IP, X86::CMOVNE32rr, 2, 
+        BuildMI(*MBB, IP, X86::CMOVNE32rr, 2,
                 DestReg).addReg(TmpReg2).addReg(TmpReg3);
 
         // DestHi = (>32) ? TmpReg : TmpReg3;
-        BuildMI(*MBB, IP, X86::CMOVNE32rr, 2, 
+        BuildMI(*MBB, IP, X86::CMOVNE32rr, 2,
                 DestReg+1).addReg(TmpReg3).addReg(TmpReg);
       }
     }
@@ -2648,9 +3168,14 @@ void ISel::emitShiftOperation(MachineBasicBlock *MBB,
     // The shift amount is constant, guaranteed to be a ubyte. Get its value.
     assert(CUI->getType() == Type::UByteTy && "Shift amount not a ubyte?");
 
-    const unsigned *Opc = ConstantOperand[isLeftShift*2+isSigned];
-    BuildMI(*MBB, IP, Opc[Class], 2,
-        DestReg).addReg(SrcReg).addImm(CUI->getValue());
+    if (CUI->getValue() == 1 && isLeftShift) {    // X << 1 -> X+X
+      static const int AddOpC[] = { X86::ADD8rr, X86::ADD16rr, X86::ADD32rr };
+      BuildMI(*MBB, IP, AddOpC[Class], 2,DestReg).addReg(SrcReg).addReg(SrcReg);
+    } else {
+      const unsigned *Opc = ConstantOperand[isLeftShift*2+isSigned];
+      BuildMI(*MBB, IP, Opc[Class], 2,
+              DestReg).addReg(SrcReg).addImm(CUI->getValue());
+    }
   } else {                  // The shift amount is non-constant.
     unsigned ShiftAmountReg = getReg (ShiftAmount, MBB, IP);
     BuildMI(*MBB, IP, X86::MOV8rr, 1, X86::CL).addReg(ShiftAmountReg);
@@ -2661,31 +3186,11 @@ void ISel::emitShiftOperation(MachineBasicBlock *MBB,
 }
 
 
-void ISel::getAddressingMode(Value *Addr, unsigned &BaseReg, unsigned &Scale,
-                             unsigned &IndexReg, unsigned &Disp) {
-  BaseReg = 0; Scale = 1; IndexReg = 0; Disp = 0;
-  if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Addr)) {
-    if (isGEPFoldable(BB, GEP->getOperand(0), GEP->op_begin()+1, GEP->op_end(),
-                       BaseReg, Scale, IndexReg, Disp))
-      return;
-  } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Addr)) {
-    if (CE->getOpcode() == Instruction::GetElementPtr)
-      if (isGEPFoldable(BB, CE->getOperand(0), CE->op_begin()+1, CE->op_end(),
-                        BaseReg, Scale, IndexReg, Disp))
-        return;
-  }
-
-  // If it's not foldable, reset addr mode.
-  BaseReg = getReg(Addr);
-  Scale = 1; IndexReg = 0; Disp = 0;
-}
-
-
 /// visitLoadInst - Implement LLVM load instructions in terms of the x86 'mov'
 /// instruction.  The load and store instructions are the only place where we
 /// need to worry about the memory layout of the target machine.
 ///
-void ISel::visitLoadInst(LoadInst &I) {
+void X86ISel::visitLoadInst(LoadInst &I) {
   // Check to see if this load instruction is going to be folded into a binary
   // instruction, like add.  If so, we don't want to emit it.  Wouldn't a real
   // pattern matching instruction selector be nice?
@@ -2696,17 +3201,22 @@ void ISel::visitLoadInst(LoadInst &I) {
     case Instruction::Cast:
       // If this is a cast from a signed-integer type to a floating point type,
       // fold the cast here.
-      if (getClass(User->getType()) == cFP &&
+      if (getClassB(User->getType()) == cFP &&
           (I.getType() == Type::ShortTy || I.getType() == Type::IntTy ||
            I.getType() == Type::LongTy)) {
         unsigned DestReg = getReg(User);
         static const unsigned Opcode[] = {
           0/*BYTE*/, X86::FILD16m, X86::FILD32m, 0/*FP*/, X86::FILD64m
         };
-        unsigned BaseReg = 0, Scale = 1, IndexReg = 0, Disp = 0;
-        getAddressingMode(I.getOperand(0), BaseReg, Scale, IndexReg, Disp);
-        addFullAddress(BuildMI(BB, Opcode[Class], 5, DestReg),
-                       BaseReg, Scale, IndexReg, Disp);
+
+        if (AllocaInst *AI = dyn_castFixedAlloca(I.getOperand(0))) {
+          unsigned FI = getFixedSizedAllocaFI(AI);
+          addFrameReference(BuildMI(BB, Opcode[Class], 4, DestReg), FI);
+        } else {
+          X86AddressMode AM;
+          getAddressingMode(I.getOperand(0), AM);
+          addFullAddress(BuildMI(BB, Opcode[Class], 4, DestReg), AM);
+        }
         return;
       } else {
         User = 0;
@@ -2731,9 +3241,10 @@ void ISel::visitLoadInst(LoadInst &I) {
       // Okay, we found a user.  If the load is the first operand and there is
       // no second operand load, reverse the operand ordering.  Note that this
       // can fail for a subtract (ie, no change will be made).
+      bool Swapped = false;
       if (!isa<LoadInst>(User->getOperand(1)))
-        cast<BinaryOperator>(User)->swapOperands();
-      
+        Swapped = !cast<BinaryOperator>(User)->swapOperands();
+
       // Okay, now that everything is set up, if this load is used by the second
       // operand, and if there are no instructions that invalidate the load
       // before the binary operator, eliminate the load.
@@ -2749,36 +3260,50 @@ void ISel::visitLoadInst(LoadInst &I) {
            User->getOpcode() == Instruction::Div) &&
           isSafeToFoldLoadIntoInstruction(I, *User))
         return;  // Eliminate the load!
-    }
-  }
 
-  unsigned DestReg = getReg(I);
-  unsigned BaseReg = 0, Scale = 1, IndexReg = 0, Disp = 0;
-  getAddressingMode(I.getOperand(0), BaseReg, Scale, IndexReg, Disp);
-
-  if (Class == cLong) {
-    addFullAddress(BuildMI(BB, X86::MOV32rm, 4, DestReg),
-                   BaseReg, Scale, IndexReg, Disp);
-    addFullAddress(BuildMI(BB, X86::MOV32rm, 4, DestReg+1),
-                   BaseReg, Scale, IndexReg, Disp+4);
-    return;
+      // If we swapped the operands to the instruction, but couldn't fold the
+      // load anyway, swap them back.  We don't want to break add X, int
+      // folding.
+      if (Swapped) cast<BinaryOperator>(User)->swapOperands();
+    }
   }
 
   static const unsigned Opcodes[] = {
-    X86::MOV8rm, X86::MOV16rm, X86::MOV32rm, X86::FLD32m
+    X86::MOV8rm, X86::MOV16rm, X86::MOV32rm, X86::FLD32m, X86::MOV32rm
   };
   unsigned Opcode = Opcodes[Class];
   if (I.getType() == Type::DoubleTy) Opcode = X86::FLD64m;
-  addFullAddress(BuildMI(BB, Opcode, 4, DestReg),
-                 BaseReg, Scale, IndexReg, Disp);
+
+  unsigned DestReg = getReg(I);
+
+  if (AllocaInst *AI = dyn_castFixedAlloca(I.getOperand(0))) {
+    unsigned FI = getFixedSizedAllocaFI(AI);
+    if (Class == cLong) {
+      addFrameReference(BuildMI(BB, X86::MOV32rm, 4, DestReg), FI);
+      addFrameReference(BuildMI(BB, X86::MOV32rm, 4, DestReg+1), FI, 4);
+    } else {
+      addFrameReference(BuildMI(BB, Opcode, 4, DestReg), FI);
+    }
+  } else {
+    X86AddressMode AM;
+    getAddressingMode(I.getOperand(0), AM);
+
+    if (Class == cLong) {
+      addFullAddress(BuildMI(BB, X86::MOV32rm, 4, DestReg), AM);
+      AM.Disp += 4;
+      addFullAddress(BuildMI(BB, X86::MOV32rm, 4, DestReg+1), AM);
+    } else {
+      addFullAddress(BuildMI(BB, Opcode, 4, DestReg), AM);
+    }
+  }
 }
 
 /// visitStoreInst - Implement LLVM store instructions in terms of the x86 'mov'
 /// instruction.
 ///
-void ISel::visitStoreInst(StoreInst &I) {
-  unsigned BaseReg, Scale, IndexReg, Disp;
-  getAddressingMode(I.getOperand(1), BaseReg, Scale, IndexReg, Disp);
+void X86ISel::visitStoreInst(StoreInst &I) {
+  X86AddressMode AM;
+  getAddressingMode(I.getOperand(1), AM);
 
   const Type *ValTy = I.getOperand(0)->getType();
   unsigned Class = getClassB(ValTy);
@@ -2786,38 +3311,63 @@ void ISel::visitStoreInst(StoreInst &I) {
   if (ConstantInt *CI = dyn_cast<ConstantInt>(I.getOperand(0))) {
     uint64_t Val = CI->getRawValue();
     if (Class == cLong) {
-      addFullAddress(BuildMI(BB, X86::MOV32mi, 5),
-                     BaseReg, Scale, IndexReg, Disp).addImm(Val & ~0U);
-      addFullAddress(BuildMI(BB, X86::MOV32mi, 5),
-                     BaseReg, Scale, IndexReg, Disp+4).addImm(Val>>32);
+      addFullAddress(BuildMI(BB, X86::MOV32mi, 5), AM).addImm(Val & ~0U);
+      AM.Disp += 4;
+      addFullAddress(BuildMI(BB, X86::MOV32mi, 5), AM).addImm(Val>>32);
     } else {
       static const unsigned Opcodes[] = {
         X86::MOV8mi, X86::MOV16mi, X86::MOV32mi
       };
       unsigned Opcode = Opcodes[Class];
-      addFullAddress(BuildMI(BB, Opcode, 5),
-                     BaseReg, Scale, IndexReg, Disp).addImm(Val);
+      addFullAddress(BuildMI(BB, Opcode, 5), AM).addImm(Val);
     }
+  } else if (isa<ConstantPointerNull>(I.getOperand(0))) {
+    addFullAddress(BuildMI(BB, X86::MOV32mi, 5), AM).addImm(0);
+  } else if (GlobalValue *GV = dyn_cast<GlobalValue>(I.getOperand(0))) {
+    addFullAddress(BuildMI(BB, X86::MOV32mi, 5), AM).addGlobalAddress(GV);
   } else if (ConstantBool *CB = dyn_cast<ConstantBool>(I.getOperand(0))) {
-    addFullAddress(BuildMI(BB, X86::MOV8mi, 5),
-                   BaseReg, Scale, IndexReg, Disp).addImm(CB->getValue());
-  } else {    
-    if (Class == cLong) {
-      unsigned ValReg = getReg(I.getOperand(0));
-      addFullAddress(BuildMI(BB, X86::MOV32mr, 5),
-                     BaseReg, Scale, IndexReg, Disp).addReg(ValReg);
-      addFullAddress(BuildMI(BB, X86::MOV32mr, 5),
-                     BaseReg, Scale, IndexReg, Disp+4).addReg(ValReg+1);
+    addFullAddress(BuildMI(BB, X86::MOV8mi, 5), AM).addImm(CB->getValue());
+  } else if (ConstantFP *CFP = dyn_cast<ConstantFP>(I.getOperand(0))) {
+    // Store constant FP values with integer instructions to avoid having to
+    // load the constants from the constant pool then do a store.
+    if (CFP->getType() == Type::FloatTy) {
+      union {
+        unsigned I;
+        float    F;
+      } V;
+      V.F = CFP->getValue();
+      addFullAddress(BuildMI(BB, X86::MOV32mi, 5), AM).addImm(V.I);
     } else {
-      unsigned ValReg = getReg(I.getOperand(0));
-      static const unsigned Opcodes[] = {
-        X86::MOV8mr, X86::MOV16mr, X86::MOV32mr, X86::FST32m
-      };
-      unsigned Opcode = Opcodes[Class];
-      if (ValTy == Type::DoubleTy) Opcode = X86::FST64m;
-      addFullAddress(BuildMI(BB, Opcode, 1+4),
-                     BaseReg, Scale, IndexReg, Disp).addReg(ValReg);
+      union {
+        uint64_t I;
+        double   F;
+      } V;
+      V.F = CFP->getValue();
+      addFullAddress(BuildMI(BB, X86::MOV32mi, 5), AM).addImm((unsigned)V.I);
+      AM.Disp += 4;
+      addFullAddress(BuildMI(BB, X86::MOV32mi, 5), AM).addImm(
+                                                          unsigned(V.I >> 32));
     }
+
+  } else if (Class == cLong) {
+    unsigned ValReg = getReg(I.getOperand(0));
+    addFullAddress(BuildMI(BB, X86::MOV32mr, 5), AM).addReg(ValReg);
+    AM.Disp += 4;
+    addFullAddress(BuildMI(BB, X86::MOV32mr, 5), AM).addReg(ValReg+1);
+  } else {
+    // FIXME: stop emitting these two instructions:
+    //    movl $global,%eax
+    //    movl %eax,(%ebx)
+    // when one instruction will suffice.  That includes when the global
+    // has an offset applied to it.
+    unsigned ValReg = getReg(I.getOperand(0));
+    static const unsigned Opcodes[] = {
+      X86::MOV8mr, X86::MOV16mr, X86::MOV32mr, X86::FST32m
+    };
+    unsigned Opcode = Opcodes[Class];
+    if (ValTy == Type::DoubleTy) Opcode = X86::FST64m;
+
+    addFullAddress(BuildMI(BB, Opcode, 1+4), AM).addReg(ValReg);
   }
 }
 
@@ -2825,15 +3375,20 @@ 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) {
+void X86ISel::visitCastInst(CastInst &CI) {
   Value *Op = CI.getOperand(0);
 
   unsigned SrcClass = getClassB(Op->getType());
   unsigned DestClass = getClassB(CI.getType());
   // Noop casts are not emitted: getReg will return the source operand as the
   // register to use for any uses of the noop cast.
-  if (DestClass == SrcClass)
-    return;
+  if (DestClass == SrcClass) {
+    // The only detail in this plan is that casts from double -> float are
+    // truncating operations that we have to codegen through memory (despite
+    // the fact that the source/dest registers are the same class).
+    if (CI.getType() != Type::FloatTy || Op->getType() != Type::DoubleTy)
+      return;
+  }
 
   // If this is a cast from a 32-bit integer to a Long type, and the only uses
   // of the case are GEP instructions, then the cast does not need to be
@@ -2844,7 +3399,7 @@ void ISel::visitCastInst(CastInst &CI) {
       if (!isa<GetElementPtrInst>(*I)) {
         AllUsesAreGEPs = false;
         break;
-      }        
+      }
 
     // No need to codegen this cast if all users are getelementptr instrs...
     if (AllUsesAreGEPs) return;
@@ -2866,10 +3421,10 @@ void ISel::visitCastInst(CastInst &CI) {
 /// 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) {
+void X86ISel::emitCastOperation(MachineBasicBlock *BB,
+                                MachineBasicBlock::iterator IP,
+                                Value *Src, const Type *DestTy,
+                                unsigned DestReg) {
   const Type *SrcTy = Src->getType();
   unsigned SrcClass = getClassB(SrcTy);
   unsigned DestClass = getClassB(DestTy);
@@ -2926,7 +3481,8 @@ void ISel::emitCastOperation(MachineBasicBlock *BB,
         // reading it back.
         unsigned FltAlign = TM.getTargetData().getFloatAlignment();
         int FrameIdx = F->getFrameInfo()->CreateStackObject(4, FltAlign);
-        addFrameReference(BuildMI(*BB, IP, X86::FST32m, 5), FrameIdx).addReg(SrcReg);
+        addFrameReference(BuildMI(*BB, IP, X86::FST32m, 5),
+                         FrameIdx).addReg(SrcReg);
         addFrameReference(BuildMI(*BB, IP, X86::FLD32m, 5, DestReg), FrameIdx);
       }
     } else if (SrcClass == cLong) {
@@ -2950,8 +3506,8 @@ void ISel::emitCastOperation(MachineBasicBlock *BB,
       { X86::MOVSX16rr8, X86::MOVSX32rr8, X86::MOVSX32rr16, X86::MOV32rr }, // s
       { X86::MOVZX16rr8, X86::MOVZX32rr8, X86::MOVZX32rr16, X86::MOV32rr }  // u
     };
-    
-    bool isUnsigned = SrcTy->isUnsigned();
+
+    bool isUnsigned = SrcTy->isUnsigned() || SrcTy == Type::BoolTy;
     BuildMI(*BB, IP, Opc[isUnsigned][SrcClass + DestClass - 1], 1,
         DestReg).addReg(SrcReg);
 
@@ -2969,7 +3525,7 @@ void ISel::emitCastOperation(MachineBasicBlock *BB,
     BuildMI(*BB, IP, X86::MOV32rr, 1, DestReg).addReg(SrcReg);
     return;
   }
-  
+
   // Handle cast of LARGER int to SMALLER int using a move to EAX followed by a
   // move out of AX or AL.
   if ((SrcClass <= cInt || SrcClass == cLong) && DestClass <= cInt
@@ -2989,7 +3545,7 @@ void ISel::emitCastOperation(MachineBasicBlock *BB,
     const Type *PromoteType = 0;
     unsigned PromoteOpcode = 0;
     unsigned RealDestReg = DestReg;
-    switch (SrcTy->getPrimitiveID()) {
+    switch (SrcTy->getTypeID()) {
     case Type::BoolTyID:
     case Type::SByteTyID:
       // We don't have the facilities for directly loading byte sized data from
@@ -3005,24 +3561,15 @@ void ISel::emitCastOperation(MachineBasicBlock *BB,
       PromoteType = Type::IntTy;
       PromoteOpcode = X86::MOVZX32rr16;
       break;
-    case Type::UIntTyID: {
-      // Make a 64 bit temporary... and zero out the top of it...
-      unsigned TmpReg = makeAnotherReg(Type::LongTy);
-      BuildMI(*BB, IP, X86::MOV32rr, 1, TmpReg).addReg(SrcReg);
-      BuildMI(*BB, IP, X86::MOV32ri, 1, TmpReg+1).addImm(0);
-      SrcTy = Type::LongTy;
-      SrcClass = cLong;
-      SrcReg = TmpReg;
-      break;
-    }
     case Type::ULongTyID:
+    case Type::UIntTyID:
       // Don't fild into the read destination.
       DestReg = makeAnotherReg(Type::DoubleTy);
       break;
     default:  // No promotion needed...
       break;
     }
-    
+
     if (PromoteType) {
       unsigned TmpReg = makeAnotherReg(PromoteType);
       BuildMI(*BB, IP, PromoteOpcode, 1, TmpReg).addReg(SrcReg);
@@ -3050,10 +3597,28 @@ void ISel::emitCastOperation(MachineBasicBlock *BB,
       { 0/*byte*/, X86::FILD16m, X86::FILD32m, 0/*FP*/, X86::FILD64m };
     addFrameReference(BuildMI(*BB, IP, Op2[SrcClass], 5, DestReg), FrameIdx);
 
-    // We need special handling for unsigned 64-bit integer sources.  If the
-    // input number has the "sign bit" set, then we loaded it incorrectly as a
-    // negative 64-bit number.  In this case, add an offset value.
-    if (SrcTy == Type::ULongTy) {
+    if (SrcTy == Type::UIntTy) {
+      // If this is a cast from uint -> double, we need to be careful about if
+      // the "sign" bit is set.  If so, we don't want to make a negative number,
+      // we want to make a positive number.  Emit code to add an offset if the
+      // sign bit is set.
+
+      // Compute whether the sign bit is set by shifting the reg right 31 bits.
+      unsigned IsNeg = makeAnotherReg(Type::IntTy);
+      BuildMI(*BB, IP, X86::SHR32ri, 2, IsNeg).addReg(SrcReg).addImm(31);
+
+      // Create a CP value that has the offset in one word and 0 in the other.
+      static ConstantInt *TheOffset = ConstantUInt::get(Type::ULongTy,
+                                                        0x4f80000000000000ULL);
+      unsigned CPI = F->getConstantPool()->getConstantPoolIndex(TheOffset);
+      BuildMI(*BB, IP, X86::FADD32m, 5, RealDestReg).addReg(DestReg)
+        .addConstantPoolIndex(CPI).addZImm(4).addReg(IsNeg).addSImm(0);
+
+    } else if (SrcTy == Type::ULongTy) {
+      // We need special handling for unsigned 64-bit integer sources.  If the
+      // input number has the "sign bit" set, then we loaded it incorrectly as a
+      // negative 64-bit number.  In this case, add an offset value.
+
       // Emit a test instruction to see if the dynamic input value was signed.
       BuildMI(*BB, IP, X86::TEST32rr, 2).addReg(SrcReg+1).addReg(SrcReg+1);
 
@@ -3062,11 +3627,11 @@ void ISel::emitCastOperation(MachineBasicBlock *BB,
       MachineConstantPool *CP = F->getConstantPool();
       unsigned Zero = makeAnotherReg(Type::IntTy);
       Constant *Null = Constant::getNullValue(Type::UIntTy);
-      addConstantPoolReference(BuildMI(*BB, IP, X86::LEA32r, 5, Zero), 
+      addConstantPoolReference(BuildMI(*BB, IP, X86::LEA32r, 5, Zero),
                                CP->getConstantPoolIndex(Null));
       unsigned Offset = makeAnotherReg(Type::IntTy);
       Constant *OffsetCst = ConstantUInt::get(Type::UIntTy, 0x5f800000);
-                                             
+
       addConstantPoolReference(BuildMI(*BB, IP, X86::LEA32r, 5, Offset),
                                CP->getConstantPoolIndex(OffsetCst));
       unsigned Addr = makeAnotherReg(Type::IntTy);
@@ -3103,7 +3668,7 @@ void ISel::emitCastOperation(MachineBasicBlock *BB,
 
     // Reload the modified control word now...
     addFrameReference(BuildMI(*BB, IP, X86::FLDCW16m, 4), CWFrameIdx);
-    
+
     // Restore the memory image of control word to original value
     addFrameReference(BuildMI(*BB, IP, X86::MOV8mr, 5),
                       CWFrameIdx, 1).addReg(HighPartOfCW);
@@ -3155,12 +3720,12 @@ void ISel::emitCastOperation(MachineBasicBlock *BB,
 
 /// visitVANextInst - Implement the va_next instruction...
 ///
-void ISel::visitVANextInst(VANextInst &I) {
+void X86ISel::visitVANextInst(VANextInst &I) {
   unsigned VAList = getReg(I.getOperand(0));
   unsigned DestReg = getReg(I);
 
   unsigned Size;
-  switch (I.getArgType()->getPrimitiveID()) {
+  switch (I.getArgType()->getTypeID()) {
   default:
     std::cerr << I;
     assert(0 && "Error: bad type for va_next instruction!");
@@ -3181,11 +3746,11 @@ void ISel::visitVANextInst(VANextInst &I) {
   BuildMI(BB, X86::ADD32ri, 2, DestReg).addReg(VAList).addImm(Size);
 }
 
-void ISel::visitVAArgInst(VAArgInst &I) {
+void X86ISel::visitVAArgInst(VAArgInst &I) {
   unsigned VAList = getReg(I.getOperand(0));
   unsigned DestReg = getReg(I);
 
-  switch (I.getType()->getPrimitiveID()) {
+  switch (I.getType()->getTypeID()) {
   default:
     std::cerr << I;
     assert(0 && "Error: bad type for va_next instruction!");
@@ -3208,11 +3773,11 @@ void ISel::visitVAArgInst(VAArgInst &I) {
 
 /// visitGetElementPtrInst - instruction-select GEP instructions
 ///
-void ISel::visitGetElementPtrInst(GetElementPtrInst &I) {
+void X86ISel::visitGetElementPtrInst(GetElementPtrInst &I) {
   // If this GEP instruction will be folded into all of its users, we don't need
   // to explicitly calculate it!
-  unsigned A, B, C, D;
-  if (isGEPFoldable(0, I.getOperand(0), I.op_begin()+1, I.op_end(), A,B,C,D)) {
+  X86AddressMode AM;
+  if (isGEPFoldable(0, I.getOperand(0), I.op_begin()+1, I.op_end(), AM)) {
     // Check all of the users of the instruction to see if they are loads and
     // stores.
     bool AllWillFold = true;
@@ -3245,17 +3810,19 @@ void ISel::visitGetElementPtrInst(GetElementPtrInst &I) {
 ///
 /// Note that there is one fewer entry in GEPTypes than there is in GEPOps.
 ///
-void ISel::getGEPIndex(MachineBasicBlock *MBB, MachineBasicBlock::iterator IP,
-                       std::vector<Value*> &GEPOps,
-                       std::vector<const Type*> &GEPTypes, unsigned &BaseReg,
-                       unsigned &Scale, unsigned &IndexReg, unsigned &Disp) {
+void X86ISel::getGEPIndex(MachineBasicBlock *MBB,
+                          MachineBasicBlock::iterator IP,
+                          std::vector<Value*> &GEPOps,
+                          std::vector<const Type*> &GEPTypes,
+                          X86AddressMode &AM) {
   const TargetData &TD = TM.getTargetData();
 
   // Clear out the state we are working with...
-  BaseReg = 0;    // No base register
-  Scale = 1;      // Unit scale
-  IndexReg = 0;   // No index register
-  Disp = 0;       // No displacement
+  AM.BaseType = X86AddressMode::RegBase;
+  AM.Base.Reg = 0;   // No base register
+  AM.Scale = 1;      // Unit scale
+  AM.IndexReg = 0;   // No index register
+  AM.Disp = 0;       // No displacement
 
   // While there are GEP indexes that can be folded into the current address,
   // keep processing them.
@@ -3264,12 +3831,12 @@ void ISel::getGEPIndex(MachineBasicBlock *MBB, MachineBasicBlock::iterator IP,
       // It's a struct access.  CUI is the index into the structure,
       // which names the field. This index must have unsigned type.
       const ConstantUInt *CUI = cast<ConstantUInt>(GEPOps.back());
-      
+
       // Use the TargetData structure to pick out what the layout of the
       // structure is in memory.  Since the structure index must be constant, we
       // can get its value and use it to find the right byte offset from the
       // StructLayout class's list of structure member offsets.
-      Disp += TD.getStructLayout(StTy)->MemberOffsets[CUI->getValue()];
+      AM.Disp += TD.getStructLayout(StTy)->MemberOffsets[CUI->getValue()];
       GEPOps.pop_back();        // Consume a GEP operand
       GEPTypes.pop_back();
     } else {
@@ -3284,18 +3851,18 @@ void ISel::getGEPIndex(MachineBasicBlock *MBB, MachineBasicBlock::iterator IP,
       // If idx is a constant, fold it into the offset.
       unsigned TypeSize = TD.getTypeSize(SqTy->getElementType());
       if (ConstantSInt *CSI = dyn_cast<ConstantSInt>(idx)) {
-        Disp += TypeSize*CSI->getValue();
+        AM.Disp += TypeSize*CSI->getValue();
       } else if (ConstantUInt *CUI = dyn_cast<ConstantUInt>(idx)) {
-        Disp += TypeSize*CUI->getValue();
+        AM.Disp += TypeSize*CUI->getValue();
       } else {
         // If the index reg is already taken, we can't handle this index.
-        if (IndexReg) return;
+        if (AM.IndexReg) return;
 
-        // If this is a size that we can handle, then add the index as 
+        // If this is a size that we can handle, then add the index as
         switch (TypeSize) {
         case 1: case 2: case 4: case 8:
           // These are all acceptable scales on X86.
-          Scale = TypeSize;
+          AM.Scale = TypeSize;
           break;
         default:
           // Otherwise, we can't handle this scale
@@ -3307,7 +3874,7 @@ void ISel::getGEPIndex(MachineBasicBlock *MBB, MachineBasicBlock::iterator IP,
               CI->getOperand(0)->getType() == Type::UIntTy)
             idx = CI->getOperand(0);
 
-        IndexReg = MBB ? getReg(idx, MBB, IP) : 1;
+        AM.IndexReg = MBB ? getReg(idx, MBB, IP) : 1;
       }
 
       GEPOps.pop_back();        // Consume a GEP operand
@@ -3315,56 +3882,78 @@ void ISel::getGEPIndex(MachineBasicBlock *MBB, MachineBasicBlock::iterator IP,
     }
   }
 
-  // GEPTypes is empty, which means we have a single operand left.  See if we
-  // can set it as the base register.
+  // GEPTypes is empty, which means we have a single operand left.  Set it as
+  // the base register.
   //
-  // FIXME: When addressing modes are more powerful/correct, we could load
-  // global addresses directly as 32-bit immediates.
-  assert(BaseReg == 0);
-  BaseReg = MBB ? getReg(GEPOps[0], MBB, IP) : 1;
+  assert(AM.Base.Reg == 0);
+
+  if (AllocaInst *AI = dyn_castFixedAlloca(GEPOps.back())) {
+    AM.BaseType = X86AddressMode::FrameIndexBase;
+    AM.Base.FrameIndex = getFixedSizedAllocaFI(AI);
+    GEPOps.pop_back();
+    return;
+  }
+
+  if (GlobalValue *GV = dyn_cast<GlobalValue>(GEPOps.back())) {
+    AM.GV = GV;
+    GEPOps.pop_back();
+    return;
+  }
+
+  AM.Base.Reg = MBB ? getReg(GEPOps[0], MBB, IP) : 1;
   GEPOps.pop_back();        // Consume the last GEP operand
 }
 
 
 /// isGEPFoldable - Return true if the specified GEP can be completely
 /// folded into the addressing mode of a load/store or lea instruction.
-bool ISel::isGEPFoldable(MachineBasicBlock *MBB,
-                         Value *Src, User::op_iterator IdxBegin,
-                         User::op_iterator IdxEnd, unsigned &BaseReg,
-                         unsigned &Scale, unsigned &IndexReg, unsigned &Disp) {
-  if (ConstantPointerRef *CPR = dyn_cast<ConstantPointerRef>(Src))
-    Src = CPR->getValue();
+bool X86ISel::isGEPFoldable(MachineBasicBlock *MBB,
+                            Value *Src, User::op_iterator IdxBegin,
+                            User::op_iterator IdxEnd, X86AddressMode &AM) {
 
   std::vector<Value*> GEPOps;
   GEPOps.resize(IdxEnd-IdxBegin+1);
   GEPOps[0] = Src;
   std::copy(IdxBegin, IdxEnd, GEPOps.begin()+1);
-  
-  std::vector<const Type*> GEPTypes;
-  GEPTypes.assign(gep_type_begin(Src->getType(), IdxBegin, IdxEnd),
-                  gep_type_end(Src->getType(), IdxBegin, IdxEnd));
+
+  std::vector<const Type*>
+    GEPTypes(gep_type_begin(Src->getType(), IdxBegin, IdxEnd),
+             gep_type_end(Src->getType(), IdxBegin, IdxEnd));
 
   MachineBasicBlock::iterator IP;
   if (MBB) IP = MBB->end();
-  getGEPIndex(MBB, IP, GEPOps, GEPTypes, BaseReg, Scale, IndexReg, Disp);
+  getGEPIndex(MBB, IP, GEPOps, GEPTypes, AM);
 
   // We can fold it away iff the getGEPIndex call eliminated all operands.
   return GEPOps.empty();
 }
 
-void ISel::emitGEPOperation(MachineBasicBlock *MBB,
-                            MachineBasicBlock::iterator IP,
-                            Value *Src, User::op_iterator IdxBegin,
-                            User::op_iterator IdxEnd, unsigned TargetReg) {
+void X86ISel::emitGEPOperation(MachineBasicBlock *MBB,
+                               MachineBasicBlock::iterator IP,
+                               Value *Src, User::op_iterator IdxBegin,
+                               User::op_iterator IdxEnd, unsigned TargetReg) {
   const TargetData &TD = TM.getTargetData();
-  if (ConstantPointerRef *CPR = dyn_cast<ConstantPointerRef>(Src))
-    Src = CPR->getValue();
+
+  // If this is a getelementptr null, with all constant integer indices, just
+  // replace it with TargetReg = 42.
+  if (isa<ConstantPointerNull>(Src)) {
+    User::op_iterator I = IdxBegin;
+    for (; I != IdxEnd; ++I)
+      if (!isa<ConstantInt>(*I))
+        break;
+    if (I == IdxEnd) {   // All constant indices
+      unsigned Offset = TD.getIndexedOffset(Src->getType(),
+                                         std::vector<Value*>(IdxBegin, IdxEnd));
+      BuildMI(*MBB, IP, X86::MOV32ri, 1, TargetReg).addImm(Offset);
+      return;
+    }
+  }
 
   std::vector<Value*> GEPOps;
   GEPOps.resize(IdxEnd-IdxBegin+1);
   GEPOps[0] = Src;
   std::copy(IdxBegin, IdxEnd, GEPOps.begin()+1);
-  
+
   std::vector<const Type*> GEPTypes;
   GEPTypes.assign(gep_type_begin(Src->getType(), IdxBegin, IdxEnd),
                   gep_type_end(Src->getType(), IdxBegin, IdxEnd));
@@ -3372,23 +3961,26 @@ void ISel::emitGEPOperation(MachineBasicBlock *MBB,
   // Keep emitting instructions until we consume the entire GEP instruction.
   while (!GEPOps.empty()) {
     unsigned OldSize = GEPOps.size();
-    unsigned BaseReg, Scale, IndexReg, Disp;
-    getGEPIndex(MBB, IP, GEPOps, GEPTypes, BaseReg, Scale, IndexReg, Disp);
-    
+    X86AddressMode AM;
+    getGEPIndex(MBB, IP, GEPOps, GEPTypes, AM);
+
     if (GEPOps.size() != OldSize) {
       // getGEPIndex consumed some of the input.  Build an LEA instruction here.
       unsigned NextTarget = 0;
       if (!GEPOps.empty()) {
-        assert(BaseReg == 0 &&
+        assert(AM.Base.Reg == 0 &&
            "getGEPIndex should have left the base register open for chaining!");
-        NextTarget = BaseReg = makeAnotherReg(Type::UIntTy);
+        NextTarget = AM.Base.Reg = makeAnotherReg(Type::UIntTy);
       }
 
-      if (IndexReg == 0 && Disp == 0)
-        BuildMI(*MBB, IP, X86::MOV32rr, 1, TargetReg).addReg(BaseReg);
+      if (AM.BaseType == X86AddressMode::RegBase &&
+          AM.IndexReg == 0 && AM.Disp == 0 && !AM.GV)
+        BuildMI(*MBB, IP, X86::MOV32rr, 1, TargetReg).addReg(AM.Base.Reg);
+      else if (AM.BaseType == X86AddressMode::RegBase && AM.Base.Reg == 0 &&
+               AM.IndexReg == 0 && AM.Disp == 0)
+        BuildMI(*MBB, IP, X86::MOV32ri, 1, TargetReg).addGlobalAddress(AM.GV);
       else
-        addFullAddress(BuildMI(*MBB, IP, X86::LEA32r, 5, TargetReg),
-                       BaseReg, Scale, IndexReg, Disp);
+        addFullAddress(BuildMI(*MBB, IP, X86::LEA32r, 5, TargetReg), AM);
       --IP;
       TargetReg = NextTarget;
     } else if (GEPTypes.empty()) {
@@ -3470,35 +4062,24 @@ void ISel::emitGEPOperation(MachineBasicBlock *MBB,
   }
 }
 
-
 /// visitAllocaInst - If this is a fixed size alloca, allocate space from the
 /// frame manager, otherwise do it the hard way.
 ///
-void ISel::visitAllocaInst(AllocaInst &I) {
+void X86ISel::visitAllocaInst(AllocaInst &I) {
+  // If this is a fixed size alloca in the entry block for the function, we
+  // statically stack allocate the space, so we don't need to do anything here.
+  //
+  if (dyn_castFixedAlloca(&I)) return;
+
   // Find the data size of the alloca inst's getAllocatedType.
   const Type *Ty = I.getAllocatedType();
   unsigned TySize = TM.getTargetData().getTypeSize(Ty);
 
-  // If this is a fixed size alloca in the entry block for the function,
-  // statically stack allocate the space.
-  //
-  if (ConstantUInt *CUI = dyn_cast<ConstantUInt>(I.getArraySize())) {
-    if (I.getParent() == I.getParent()->getParent()->begin()) {
-      TySize *= CUI->getValue();   // Get total allocated size...
-      unsigned Alignment = TM.getTargetData().getTypeAlignment(Ty);
-      
-      // Create a new stack object using the frame manager...
-      int FrameIdx = F->getFrameInfo()->CreateStackObject(TySize, Alignment);
-      addFrameReference(BuildMI(BB, X86::LEA32r, 5, getReg(I)), FrameIdx);
-      return;
-    }
-  }
-  
   // Create a register to hold the temporary result of multiplying the type size
   // constant by the variable amount.
   unsigned TotalSizeReg = makeAnotherReg(Type::UIntTy);
   unsigned SrcReg1 = getReg(I.getArraySize());
-  
+
   // TotalSizeReg = mul <numelements>, <TypeSize>
   MachineBasicBlock::iterator MBBI = BB->end();
   doMultiplyConst(BB, MBBI, TotalSizeReg, Type::UIntTy, SrcReg1, TySize);
@@ -3510,7 +4091,7 @@ void ISel::visitAllocaInst(AllocaInst &I) {
   // AlignedSize = and <AddedSize>, ~15
   unsigned AlignedSize = makeAnotherReg(Type::UIntTy);
   BuildMI(BB, X86::AND32ri, 2, AlignedSize).addReg(AddedSizeReg).addImm(~15);
-  
+
   // Subtract size from stack pointer, thereby allocating some space.
   BuildMI(BB, X86::SUB32rr, 2, X86::ESP).addReg(X86::ESP).addReg(AlignedSize);
 
@@ -3526,7 +4107,7 @@ void ISel::visitAllocaInst(AllocaInst &I) {
 /// visitMallocInst - Malloc instructions are code generated into direct calls
 /// to the library malloc.
 ///
-void ISel::visitMallocInst(MallocInst &I) {
+void X86ISel::visitMallocInst(MallocInst &I) {
   unsigned AllocSize = TM.getTargetData().getTypeSize(I.getAllocatedType());
   unsigned Arg;
 
@@ -3550,18 +4131,18 @@ void ISel::visitMallocInst(MallocInst &I) {
 /// visitFreeInst - Free instructions are code gen'd to call the free libc
 /// function.
 ///
-void ISel::visitFreeInst(FreeInst &I) {
+void X86ISel::visitFreeInst(FreeInst &I) {
   std::vector<ValueRecord> Args;
   Args.push_back(ValueRecord(I.getOperand(0)));
   MachineInstr *TheCall = BuildMI(X86::CALLpcrel32,
                                   1).addExternalSymbol("free", true);
   doCall(ValueRecord(0, Type::VoidTy), TheCall, Args);
 }
-   
+
 /// createX86SimpleInstructionSelector - This pass converts an LLVM function
 /// into a machine code representation is a very simple peep-hole fashion.  The
 /// generated code sucks but the implementation is nice and simple.
 ///
 FunctionPass *llvm::createX86SimpleInstructionSelector(TargetMachine &TM) {
-  return new ISel(TM);
+  return new X86ISel(TM);
 }