Apply feedback from previous patch.
[oota-llvm.git] / lib / Target / CBackend / CBackend.cpp
index 55fade53627be1368f4e99e14a3d9f8e3af6dc54..0221174e5cfd6f0f65562cb257a36154dc083d4d 100644 (file)
@@ -18,9 +18,9 @@
 #include "llvm/DerivedTypes.h"
 #include "llvm/Module.h"
 #include "llvm/Instructions.h"
+#include "llvm/ParameterAttributes.h"
 #include "llvm/Pass.h"
 #include "llvm/PassManager.h"
-#include "llvm/SymbolTable.h"
 #include "llvm/TypeSymbolTable.h"
 #include "llvm/Intrinsics.h"
 #include "llvm/IntrinsicInst.h"
@@ -32,6 +32,7 @@
 #include "llvm/Transforms/Scalar.h"
 #include "llvm/Target/TargetMachineRegistry.h"
 #include "llvm/Target/TargetAsmInfo.h"
+#include "llvm/Target/TargetData.h"
 #include "llvm/Support/CallSite.h"
 #include "llvm/Support/CFG.h"
 #include "llvm/Support/GetElementPtrTypeIterator.h"
@@ -55,6 +56,10 @@ namespace {
   /// external functions with the same name.
   ///
   class CBackendNameAllUsedStructsAndMergeFunctions : public ModulePass {
+  public:
+    static char ID;
+    CBackendNameAllUsedStructsAndMergeFunctions() 
+      : ModulePass((intptr_t)&ID) {}
     void getAnalysisUsage(AnalysisUsage &AU) const {
       AU.addRequired<FindUsedTypes>();
     }
@@ -66,20 +71,27 @@ namespace {
     virtual bool runOnModule(Module &M);
   };
 
+  char CBackendNameAllUsedStructsAndMergeFunctions::ID = 0;
+
   /// CWriter - This class is the main chunk of code that converts an LLVM
   /// module to a C translation unit.
   class CWriter : public FunctionPass, public InstVisitor<CWriter> {
     std::ostream &Out;
-    IntrinsicLowering IL;
+    IntrinsicLowering *IL;
     Mangler *Mang;
     LoopInfo *LI;
     const Module *TheModule;
     const TargetAsmInfo* TAsm;
+    const TargetData* TD;
     std::map<const Type *, std::string> TypeNames;
-
     std::map<const ConstantFP *, unsigned> FPConstantMap;
+    std::set<Function*> intrinsicPrototypesAlreadyGenerated;
+
   public:
-    CWriter(std::ostream &o) : Out(o), TAsm(0) {}
+    static char ID;
+    CWriter(std::ostream &o) 
+      : FunctionPass((intptr_t)&ID), Out(o), IL(0), Mang(0), LI(0), 
+        TheModule(0), TAsm(0), TD(0) {}
 
     virtual const char *getPassName() const { return "C backend"; }
 
@@ -99,9 +111,6 @@ namespace {
       // Output all floating point constants that cannot be printed accurately.
       printFloatingPointConstants(F);
 
-      // Ensure that no local symbols conflict with global symbols.
-      F.renameLocalSymbols();
-
       printFunction(F);
       FPConstantMap.clear();
       return false;
@@ -118,7 +127,7 @@ namespace {
                             bool isSigned = false,
                             const std::string &VariableName = "",
                             bool IgnoreName = false);
-    std::ostream &printPrimitiveType(std::ostream &Out, const Type *Ty, 
+    std::ostream &printSimpleType(std::ostream &Out, const Type *Ty, 
                                      bool isSigned, 
                                      const std::string &NameSoFar = "");
 
@@ -152,7 +161,7 @@ namespace {
     void printConstantWithCast(Constant *CPV, unsigned Opcode);
     bool printConstExprCast(const ConstantExpr *CE);
     void printConstantArray(ConstantArray *CPA);
-    void printConstantPacked(ConstantPacked *CP);
+    void printConstantVector(ConstantVector *CP);
 
     // isInlinableInst - Attempt to inline instructions into their uses to build
     // trees as much as possible.  To do this, we have to consistently decide
@@ -225,7 +234,6 @@ namespace {
     void visitSelectInst(SelectInst &I);
     void visitCallInst (CallInst &I);
     void visitInlineAsm(CallInst &I);
-    void visitShiftInst(ShiftInst &I) { visitBinaryOperator(I); }
 
     void visitMallocInst(MallocInst &I);
     void visitAllocaInst(AllocaInst &I);
@@ -241,7 +249,7 @@ namespace {
     }
 
     void outputLValue(Instruction *I) {
-      Out << "  " << Mang->getValueName(I) << " = ";
+      Out << "  " << GetValueName(I) << " = ";
     }
 
     bool isGotoCodeNecessary(BasicBlock *From, BasicBlock *To);
@@ -251,9 +259,13 @@ namespace {
                             unsigned Indent);
     void printIndexingExpression(Value *Ptr, gep_type_iterator I,
                                  gep_type_iterator E);
+
+    std::string GetValueName(const Value *Operand);
   };
 }
 
+char CWriter::ID = 0;
+
 /// This method inserts names for any unnamed structure types that are used by
 /// the program, and removes names from structure types that are not used by the
 /// program.
@@ -269,13 +281,19 @@ bool CBackendNameAllUsedStructsAndMergeFunctions::runOnModule(Module &M) {
   for (TypeSymbolTable::iterator TI = TST.begin(), TE = TST.end();
        TI != TE; ) {
     TypeSymbolTable::iterator I = TI++;
-
-    // If this is not used, remove it from the symbol table.
-    std::set<const Type *>::iterator UTI = UT.find(I->second);
-    if (UTI == UT.end())
+    
+    // If this isn't a struct type, remove it from our set of types to name.
+    // This simplifies emission later.
+    if (!isa<StructType>(I->second) && !isa<OpaqueType>(I->second)) {
       TST.remove(I);
-    else
-      UT.erase(UTI);    // Only keep one name for this type.
+    } else {
+      // If this is not used, remove it from the symbol table.
+      std::set<const Type *>::iterator UTI = UT.find(I->second);
+      if (UTI == UT.end())
+        TST.remove(I);
+      else
+        UT.erase(UTI);    // Only keep one name for this type.
+    }
   }
 
   // UT now contains types that are not named.  Loop over it, naming
@@ -299,7 +317,7 @@ bool CBackendNameAllUsedStructsAndMergeFunctions::runOnModule(Module &M) {
   std::map<std::string, GlobalValue*> ExtSymbols;
   for (Module::iterator I = M.begin(), E = M.end(); I != E;) {
     Function *GV = I++;
-    if (GV->isExternal() && GV->hasName()) {
+    if (GV->isDeclaration() && GV->hasName()) {
       std::pair<std::map<std::string, GlobalValue*>::iterator, bool> X
         = ExtSymbols.insert(std::make_pair(GV->getName(), GV));
       if (!X.second) {
@@ -315,7 +333,7 @@ bool CBackendNameAllUsedStructsAndMergeFunctions::runOnModule(Module &M) {
   for (Module::global_iterator I = M.global_begin(), E = M.global_end();
        I != E;) {
     GlobalVariable *GV = I++;
-    if (GV->isExternal() && GV->hasName()) {
+    if (GV->isDeclaration() && GV->hasName()) {
       std::pair<std::map<std::string, GlobalValue*>::iterator, bool> X
         = ExtSymbols.insert(std::make_pair(GV->getName(), GV));
       if (!X.second) {
@@ -344,11 +362,12 @@ void CWriter::printStructReturnPointerFunctionType(std::ostream &Out,
   FunctionType::param_iterator I = FTy->param_begin(), E = FTy->param_end();
   const Type *RetTy = cast<PointerType>(I->get())->getElementType();
   unsigned Idx = 1;
+  const ParamAttrsList *Attrs = FTy->getParamAttrs();
   for (++I; I != E; ++I) {
     if (PrintedType)
       FunctionInnards << ", ";
     printType(FunctionInnards, *I, 
-        /*isSigned=*/FTy->paramHasAttr(Idx, FunctionType::SExtAttribute), "");
+        /*isSigned=*/Attrs && Attrs->paramHasAttr(Idx, ParamAttr::SExt), "");
     PrintedType = true;
   }
   if (FTy->isVarArg()) {
@@ -360,26 +379,33 @@ void CWriter::printStructReturnPointerFunctionType(std::ostream &Out,
   FunctionInnards << ')';
   std::string tstr = FunctionInnards.str();
   printType(Out, RetTy, 
-      /*isSigned=*/FTy->paramHasAttr(0, FunctionType::SExtAttribute), tstr);
+      /*isSigned=*/Attrs && Attrs->paramHasAttr(0, ParamAttr::SExt), tstr);
 }
 
 std::ostream &
-CWriter::printPrimitiveType(std::ostream &Out, const Type *Ty, bool isSigned,
+CWriter::printSimpleType(std::ostream &Out, const Type *Ty, bool isSigned,
                             const std::string &NameSoFar) {
-  assert(Ty->isPrimitiveType() && "Invalid type for printPrimitiveType");
+  assert((Ty->isPrimitiveType() || Ty->isInteger()) && 
+         "Invalid type for printSimpleType");
   switch (Ty->getTypeID()) {
-  case Type::VoidTyID:   return Out << "void "               << NameSoFar;
-  case Type::BoolTyID:   return Out << "bool "               << NameSoFar;
-  case Type::Int8TyID:
-    return Out << (isSigned?"signed":"unsigned") << " char " << NameSoFar;
-  case Type::Int16TyID:  
-    return Out << (isSigned?"signed":"unsigned") << " short " << NameSoFar;
-  case Type::Int32TyID:    
-    return Out << (isSigned?"signed":"unsigned") << " int " << NameSoFar;
-  case Type::Int64TyID:   
-    return Out << (isSigned?"signed":"unsigned") << " long long " << NameSoFar;
-  case Type::FloatTyID:  return Out << "float "              << NameSoFar;
-  case Type::DoubleTyID: return Out << "double "             << NameSoFar;
+  case Type::VoidTyID:   return Out << "void " << NameSoFar;
+  case Type::IntegerTyID: {
+    unsigned NumBits = cast<IntegerType>(Ty)->getBitWidth();
+    if (NumBits == 1) 
+      return Out << "bool " << NameSoFar;
+    else if (NumBits <= 8)
+      return Out << (isSigned?"signed":"unsigned") << " char " << NameSoFar;
+    else if (NumBits <= 16)
+      return Out << (isSigned?"signed":"unsigned") << " short " << NameSoFar;
+    else if (NumBits <= 32)
+      return Out << (isSigned?"signed":"unsigned") << " int " << NameSoFar;
+    else { 
+      assert(NumBits <= 64 && "Bit widths > 64 not implemented yet");
+      return Out << (isSigned?"signed":"unsigned") << " long long "<< NameSoFar;
+    }
+  }
+  case Type::FloatTyID:  return Out << "float "   << NameSoFar;
+  case Type::DoubleTyID: return Out << "double "  << NameSoFar;
   default :
     cerr << "Unknown primitive type: " << *Ty << "\n";
     abort();
@@ -392,11 +418,8 @@ CWriter::printPrimitiveType(std::ostream &Out, const Type *Ty, bool isSigned,
 std::ostream &CWriter::printType(std::ostream &Out, const Type *Ty,
                                  bool isSigned, const std::string &NameSoFar,
                                  bool IgnoreName) {
-  if (Ty->isPrimitiveType()) {
-    // FIXME:Signedness. When integer types are signless, this should just
-    // always pass "false" for the sign of the primitive type. The instructions
-    // will figure out how the value is to be interpreted.
-    printPrimitiveType(Out, Ty, isSigned, NameSoFar);
+  if (Ty->isPrimitiveType() || Ty->isInteger()) {
+    printSimpleType(Out, Ty, isSigned, NameSoFar);
     return Out;
   }
 
@@ -411,13 +434,14 @@ std::ostream &CWriter::printType(std::ostream &Out, const Type *Ty,
     const FunctionType *FTy = cast<FunctionType>(Ty);
     std::stringstream FunctionInnards;
     FunctionInnards << " (" << NameSoFar << ") (";
+    const ParamAttrsList *Attrs = FTy->getParamAttrs();
     unsigned Idx = 1;
     for (FunctionType::param_iterator I = FTy->param_begin(),
            E = FTy->param_end(); I != E; ++I) {
       if (I != FTy->param_begin())
         FunctionInnards << ", ";
       printType(FunctionInnards, *I, 
-         /*isSigned=*/FTy->paramHasAttr(Idx, FunctionType::SExtAttribute), "");
+         /*isSigned=*/Attrs && Attrs->paramHasAttr(Idx, ParamAttr::SExt), "");
       ++Idx;
     }
     if (FTy->isVarArg()) {
@@ -429,7 +453,7 @@ std::ostream &CWriter::printType(std::ostream &Out, const Type *Ty,
     FunctionInnards << ')';
     std::string tstr = FunctionInnards.str();
     printType(Out, FTy->getReturnType(), 
-        /*isSigned=*/FTy->paramHasAttr(0, FunctionType::SExtAttribute), tstr);
+        /*isSigned=*/Attrs && Attrs->paramHasAttr(0, ParamAttr::SExt), tstr);
     return Out;
   }
   case Type::StructTyID: {
@@ -442,7 +466,10 @@ std::ostream &CWriter::printType(std::ostream &Out, const Type *Ty,
       printType(Out, *I, false, "field" + utostr(Idx++));
       Out << ";\n";
     }
-    return Out << '}';
+    Out << '}';
+    if (STy->isPacked())
+      Out << " __attribute__ ((packed))";
+    return Out;
   }
 
   case Type::PointerTyID: {
@@ -450,7 +477,7 @@ std::ostream &CWriter::printType(std::ostream &Out, const Type *Ty,
     std::string ptrName = "*" + NameSoFar;
 
     if (isa<ArrayType>(PTy->getElementType()) ||
-        isa<PackedType>(PTy->getElementType()))
+        isa<VectorType>(PTy->getElementType()))
       ptrName = "(" + ptrName + ")";
 
     return printType(Out, PTy->getElementType(), false, ptrName);
@@ -464,8 +491,8 @@ std::ostream &CWriter::printType(std::ostream &Out, const Type *Ty,
                      NameSoFar + "[" + utostr(NumElements) + "]");
   }
 
-  case Type::PackedTyID: {
-    const PackedType *PTy = cast<PackedType>(Ty);
+  case Type::VectorTyID: {
+    const VectorType *PTy = cast<VectorType>(Ty);
     unsigned NumElements = PTy->getNumElements();
     if (NumElements == 0) NumElements = 1;
     return printType(Out, PTy->getElementType(), false,
@@ -555,7 +582,7 @@ void CWriter::printConstantArray(ConstantArray *CPA) {
   }
 }
 
-void CWriter::printConstantPacked(ConstantPacked *CP) {
+void CWriter::printConstantVector(ConstantVector *CP) {
   Out << '{';
   if (CP->getNumOperands()) {
     Out << ' ';
@@ -577,17 +604,19 @@ void CWriter::printConstantPacked(ConstantPacked *CP) {
 // only deal in IEEE FP).
 //
 static bool isFPCSafeToPrint(const ConstantFP *CFP) {
+  APFloat APF = APFloat(CFP->getValueAPF());  // copy
+  if (CFP->getType()==Type::FloatTy)
+    APF.convert(APFloat::IEEEdouble, APFloat::rmNearestTiesToEven);
 #if HAVE_PRINTF_A && ENABLE_CBE_PRINTF_A
   char Buffer[100];
-  sprintf(Buffer, "%a", CFP->getValue());
-
+  sprintf(Buffer, "%a", APF.convertToDouble());
   if (!strncmp(Buffer, "0x", 2) ||
       !strncmp(Buffer, "-0x", 3) ||
       !strncmp(Buffer, "+0x", 3))
-    return atof(Buffer) == CFP->getValue();
+    return APF.bitwiseIsEqual(APFloat(atof(Buffer)));
   return false;
 #else
-  std::string StrVal = ftostr(CFP->getValue());
+  std::string StrVal = ftostr(APF);
 
   while (StrVal[0] == ' ')
     StrVal.erase(StrVal.begin());
@@ -598,7 +627,7 @@ static bool isFPCSafeToPrint(const ConstantFP *CFP) {
       ((StrVal[0] == '-' || StrVal[0] == '+') &&
        (StrVal[1] >= '0' && StrVal[1] <= '9')))
     // Reparse stringized version!
-    return atof(StrVal.c_str()) == CFP->getValue();
+    return APF.bitwiseIsEqual(APFloat(atof(StrVal.c_str())));
   return false;
 #endif
 }
@@ -624,13 +653,13 @@ void CWriter::printCast(unsigned opc, const Type *SrcTy, const Type *DstTy) {
     case Instruction::PtrToInt:
     case Instruction::FPToUI: // For these, make sure we get an unsigned dest
       Out << '(';
-      printPrimitiveType(Out, DstTy, false);
+      printSimpleType(Out, DstTy, false);
       Out << ')';
       break;
     case Instruction::SExt: 
     case Instruction::FPToSI: // For these, make sure we get a signed dest
       Out << '(';
-      printPrimitiveType(Out, DstTy, true);
+      printSimpleType(Out, DstTy, true);
       Out << ')';
       break;
     default:
@@ -642,13 +671,13 @@ void CWriter::printCast(unsigned opc, const Type *SrcTy, const Type *DstTy) {
     case Instruction::UIToFP:
     case Instruction::ZExt:
       Out << '(';
-      printPrimitiveType(Out, SrcTy, false);
+      printSimpleType(Out, SrcTy, false);
       Out << ')';
       break;
     case Instruction::SIToFP:
     case Instruction::SExt:
       Out << '(';
-      printPrimitiveType(Out, SrcTy, true); 
+      printSimpleType(Out, SrcTy, true); 
       Out << ')';
       break;
     case Instruction::IntToPtr:
@@ -688,12 +717,12 @@ void CWriter::printConstant(Constant *CPV) {
       Out << "(";
       printCast(CE->getOpcode(), CE->getOperand(0)->getType(), CE->getType());
       if (CE->getOpcode() == Instruction::SExt &&
-          CE->getOperand(0)->getType() == Type::BoolTy) {
+          CE->getOperand(0)->getType() == Type::Int1Ty) {
         // Make sure we really sext from bool here by subtracting from 0
         Out << "0-";
       }
       printConstant(CE->getOperand(0));
-      if (CE->getType() == Type::BoolTy &&
+      if (CE->getType() == Type::Int1Ty &&
           (CE->getOpcode() == Instruction::Trunc ||
            CE->getOpcode() == Instruction::FPToUI ||
            CE->getOpcode() == Instruction::FPToSI ||
@@ -826,22 +855,21 @@ void CWriter::printConstant(Constant *CPV) {
     return;
   }
 
-  if (ConstantBool *CB = dyn_cast<ConstantBool>(CPV)) {
-    Out << (CB->getValue() ? '1' : '0') ;
-    return;
-  }
-
   if (ConstantInt *CI = dyn_cast<ConstantInt>(CPV)) {
     const Type* Ty = CI->getType();
-    Out << "((";
-    printPrimitiveType(Out, Ty, false) << ')';
-    if (CI->isMinValue(true)) 
-      Out << CI->getZExtValue() << 'u';
-    else
-      Out << CI->getSExtValue();
-    if (Ty->getPrimitiveSizeInBits() > 32)
-      Out << "ll";
-    Out << ')';
+    if (Ty == Type::Int1Ty)
+      Out << (CI->getZExtValue() ? '1' : '0') ;
+    else {
+      Out << "((";
+      printSimpleType(Out, Ty, false) << ')';
+      if (CI->isMinValue(true)) 
+        Out << CI->getZExtValue() << 'u';
+      else
+        Out << CI->getSExtValue();
+      if (Ty->getPrimitiveSizeInBits() > 32)
+        Out << "ll";
+      Out << ')';
+    }
     return;
   } 
 
@@ -856,9 +884,13 @@ void CWriter::printConstant(Constant *CPV) {
       Out << "(*(" << (FPC->getType() == Type::FloatTy ? "float" : "double")
           << "*)&FPConstant" << I->second << ')';
     } else {
-      if (IsNAN(FPC->getValue())) {
+      double V = FPC->getType() == Type::FloatTy ? 
+                 FPC->getValueAPF().convertToFloat() : 
+                 FPC->getValueAPF().convertToDouble();
+      if (IsNAN(V)) {
         // The value is NaN
 
+        // FIXME the actual NaN bits should be emitted.
         // The prefix for a quiet NaN is 0x7FF8. For a signalling NaN,
         // it's 0x7ff4.
         const unsigned long QuietNaN = 0x7ff8UL;
@@ -867,7 +899,7 @@ void CWriter::printConstant(Constant *CPV) {
         // We need to grab the first part of the FP #
         char Buffer[100];
 
-        uint64_t ll = DoubleToBits(FPC->getValue());
+        uint64_t ll = DoubleToBits(V);
         sprintf(Buffer, "0x%llx", static_cast<long long>(ll));
 
         std::string Num(&Buffer[0], &Buffer[6]);
@@ -879,9 +911,9 @@ void CWriter::printConstant(Constant *CPV) {
         else
           Out << "LLVM_NAN" << (Val == QuietNaN ? "" : "S") << "(\""
               << Buffer << "\") /*nan*/ ";
-      } else if (IsInf(FPC->getValue())) {
+      } else if (IsInf(V)) {
         // The value is Inf
-        if (FPC->getValue() < 0) Out << '-';
+        if (V < 0) Out << '-';
         Out << "LLVM_INF" << (FPC->getType() == Type::FloatTy ? "F" : "")
             << " /*inf*/ ";
       } else {
@@ -889,12 +921,12 @@ void CWriter::printConstant(Constant *CPV) {
 #if HAVE_PRINTF_A && ENABLE_CBE_PRINTF_A
         // Print out the constant as a floating point number.
         char Buffer[100];
-        sprintf(Buffer, "%a", FPC->getValue());
+        sprintf(Buffer, "%a", V);
         Num = Buffer;
 #else
-        Num = ftostr(FPC->getValue());
+        Num = ftostr(FPC->getValueAPF());
 #endif
-        Out << Num;
+       Out << Num;
       }
     }
     break;
@@ -919,9 +951,9 @@ void CWriter::printConstant(Constant *CPV) {
     }
     break;
 
-  case Type::PackedTyID:
+  case Type::VectorTyID:
     if (isa<ConstantAggregateZero>(CPV) || isa<UndefValue>(CPV)) {
-      const PackedType *AT = cast<PackedType>(CPV->getType());
+      const VectorType *AT = cast<VectorType>(CPV->getType());
       Out << '{';
       if (AT->getNumElements()) {
         Out << ' ';
@@ -934,7 +966,7 @@ void CWriter::printConstant(Constant *CPV) {
       }
       Out << " }";
     } else {
-      printConstantPacked(cast<ConstantPacked>(CPV));
+      printConstantVector(cast<ConstantVector>(CPV));
     }
     break;
 
@@ -1019,8 +1051,8 @@ bool CWriter::printConstExprCast(const ConstantExpr* CE) {
   }
   if (NeedsExplicitCast) {
     Out << "((";
-    if (Ty->isInteger())
-      printPrimitiveType(Out, Ty, TypeIsSigned);
+    if (Ty->isInteger() && Ty != Type::Int1Ty)
+      printSimpleType(Out, Ty, TypeIsSigned);
     else
       printType(Out, Ty); // not integer, sign doesn't matter
     Out << ")(";
@@ -1065,7 +1097,7 @@ void CWriter::printConstantWithCast(Constant* CPV, unsigned Opcode) {
   // operand.
   if (shouldCast) {
     Out << "((";
-    printPrimitiveType(Out, OpTy, typeIsSigned);
+    printSimpleType(Out, OpTy, typeIsSigned);
     Out << ")";
     printConstant(CPV);
     Out << ")";
@@ -1073,6 +1105,34 @@ void CWriter::printConstantWithCast(Constant* CPV, unsigned Opcode) {
     printConstant(CPV);
 }
 
+std::string CWriter::GetValueName(const Value *Operand) {
+  std::string Name;
+
+  if (!isa<GlobalValue>(Operand) && Operand->getName() != "") {
+    std::string VarName;
+
+    Name = Operand->getName();
+    VarName.reserve(Name.capacity());
+
+    for (std::string::iterator I = Name.begin(), E = Name.end();
+         I != E; ++I) {
+      char ch = *I;
+
+      if (!((ch >= 'a' && ch <= 'z') || (ch >= 'A' && ch <= 'Z') ||
+            (ch >= '0' && ch <= '9') || ch == '_'))
+        VarName += '_';
+      else
+        VarName += ch;
+    }
+
+    Name = "llvm_cbe_" + VarName;
+  } else {
+    Name = Mang->getValueName(Operand);
+  }
+
+  return Name;
+}
+
 void CWriter::writeOperandInternal(Value *Operand) {
   if (Instruction *I = dyn_cast<Instruction>(Operand))
     if (isInlinableInst(*I) && !isDirectAlloca(I)) {
@@ -1084,11 +1144,11 @@ void CWriter::writeOperandInternal(Value *Operand) {
     }
 
   Constant* CPV = dyn_cast<Constant>(Operand);
-  if (CPV && !isa<GlobalValue>(CPV)) {
+
+  if (CPV && !isa<GlobalValue>(CPV))
     printConstant(CPV);
-  } else {
-    Out << Mang->getValueName(Operand);
-  }
+  else
+    Out << GetValueName(Operand);
 }
 
 void CWriter::writeOperandRaw(Value *Operand) {
@@ -1096,7 +1156,7 @@ void CWriter::writeOperandRaw(Value *Operand) {
   if (CPV && !isa<GlobalValue>(CPV)) {
     printConstant(CPV);
   } else {
-    Out << Mang->getValueName(Operand);
+    Out << GetValueName(Operand);
   }
 }
 
@@ -1121,14 +1181,14 @@ bool CWriter::writeInstructionCast(const Instruction &I) {
   case Instruction::URem: 
   case Instruction::UDiv: 
     Out << "((";
-    printPrimitiveType(Out, Ty, false);
+    printSimpleType(Out, Ty, false);
     Out << ")(";
     return true;
   case Instruction::AShr:
   case Instruction::SRem: 
   case Instruction::SDiv: 
     Out << "((";
-    printPrimitiveType(Out, Ty, true);
+    printSimpleType(Out, Ty, true);
     Out << ")(";
     return true;
   default: break;
@@ -1175,7 +1235,7 @@ void CWriter::writeOperandWithCast(Value* Operand, unsigned Opcode) {
   // operand.
   if (shouldCast) {
     Out << "((";
-    printPrimitiveType(Out, OpTy, castIsSigned);
+    printSimpleType(Out, OpTy, castIsSigned);
     Out << ")";
     writeOperand(Operand);
     Out << ")";
@@ -1222,8 +1282,8 @@ void CWriter::writeOperandWithCast(Value* Operand, ICmpInst::Predicate predicate
   // operand.
   if (shouldCast) {
     Out << "((";
-    if (OpTy->isInteger())
-      printPrimitiveType(Out, OpTy, castIsSigned);
+    if (OpTy->isInteger() && OpTy != Type::Int1Ty)
+      printSimpleType(Out, OpTy, castIsSigned);
     else
       printType(Out, OpTy); // not integer, sign doesn't matter
     Out << ")";
@@ -1240,8 +1300,8 @@ static void generateCompilerSpecificCode(std::ostream& Out) {
   // Alloca is hard to get, and we don't want to include stdlib.h here.
   Out << "/* get a declaration for alloca */\n"
       << "#if defined(__CYGWIN__) || defined(__MINGW32__)\n"
-      << "extern void *_alloca(unsigned long);\n"
-      << "#define alloca(x) _alloca(x)\n"
+      << "#define  alloca(x) __builtin_alloca((x))\n"
+      << "#define _alloca(x) __builtin_alloca((x))\n"    
       << "#elif defined(__APPLE__)\n"
       << "extern void *__builtin_alloca(unsigned long);\n"
       << "#define alloca(x) __builtin_alloca(x)\n"
@@ -1256,7 +1316,10 @@ static void generateCompilerSpecificCode(std::ostream& Out) {
       << "#define alloca(x) __builtin_alloca(x)\n"
       << "#elif defined(__FreeBSD__) || defined(__OpenBSD__)\n"
       << "#define alloca(x) __builtin_alloca(x)\n"
-      << "#elif !defined(_MSC_VER)\n"
+      << "#elif defined(_MSC_VER)\n"
+      << "#define inline _inline\n"
+      << "#define alloca(x) _alloca(x)\n"
+      << "#else\n"
       << "#include <alloca.h>\n"
       << "#endif\n\n";
 
@@ -1284,6 +1347,11 @@ static void generateCompilerSpecificCode(std::ostream& Out) {
       << "#define __ATTRIBUTE_WEAK__\n"
       << "#endif\n\n";
 
+  // Add hidden visibility support. FIXME: APPLE_CC?
+  Out << "#if defined(__GNUC__)\n"
+      << "#define __HIDDEN__ __attribute__((visibility(\"hidden\")))\n"
+      << "#endif\n\n";
+    
   // Define NaN and Inf as GCC builtins if using GCC, as 0 otherwise
   // From the GCC documentation:
   //
@@ -1339,19 +1407,14 @@ static void generateCompilerSpecificCode(std::ostream& Out) {
       << "#define __ATTRIBUTE_DTOR__\n"
       << "#define LLVM_ASM(X)\n"
       << "#endif\n\n";
+  
+  Out << "#if __GNUC__ < 4 /* Old GCC's, or compilers not GCC */ \n"
+      << "#define __builtin_stack_save() 0   /* not implemented */\n"
+      << "#define __builtin_stack_restore(X) /* noop */\n"
+      << "#endif\n\n";
 
   // Output target-specific code that should be inserted into main.
   Out << "#define CODE_FOR_MAIN() /* Any target-specific code for main()*/\n";
-  // On X86, set the FP control word to 64-bits of precision instead of 80 bits.
-  Out << "#if defined(__GNUC__) && !defined(__llvm__)\n"
-      << "#if defined(i386) || defined(__i386__) || defined(__i386) || "
-      << "defined(__x86_64__)\n"
-      << "#undef CODE_FOR_MAIN\n"
-      << "#define CODE_FOR_MAIN() \\\n"
-      << "  {short F;__asm__ (\"fnstcw %0\" : \"=m\" (*&F)); \\\n"
-      << "  F=(F&~0x300)|0x200;__asm__(\"fldcw %0\"::\"m\"(*&F));}\n"
-      << "#endif\n#endif\n";
-
 }
 
 /// FindStaticTors - Given a static ctor/dtor list, unpack its contents into
@@ -1405,7 +1468,9 @@ bool CWriter::doInitialization(Module &M) {
   // Initialize
   TheModule = &M;
 
-  IL.AddPrototypes(M);
+  TD = new TargetData(&M);
+  IL = new IntrinsicLowering(*TD);
+  IL->AddPrototypes(M);
 
   // Ensure that all structure types have names...
   Mang = new Mangler(M);
@@ -1455,22 +1520,23 @@ bool CWriter::doInitialization(Module &M) {
     Out << "\n/* External Global Variable Declarations */\n";
     for (Module::global_iterator I = M.global_begin(), E = M.global_end();
          I != E; ++I) {
-      if (I->hasExternalLinkage()) {
+
+      if (I->hasExternalLinkage() || I->hasExternalWeakLinkage())
         Out << "extern ";
-        printType(Out, I->getType()->getElementType(), false, 
-                  Mang->getValueName(I));
-        Out << ";\n";
-      } else if (I->hasDLLImportLinkage()) {
+      else if (I->hasDLLImportLinkage())
         Out << "__declspec(dllimport) ";
-        printType(Out, I->getType()->getElementType(), false, 
-                  Mang->getValueName(I));
-        Out << ";\n";        
-      } else if (I->hasExternalWeakLinkage()) {
-        Out << "extern ";
-        printType(Out, I->getType()->getElementType(), false,
-                  Mang->getValueName(I));
-        Out << " __EXTERNAL_WEAK__ ;\n";
-      }
+      else
+        continue; // Internal Global
+
+      // Thread Local Storage
+      if (I->isThreadLocal())
+        Out << "__thread ";
+
+      printType(Out, I->getType()->getElementType(), false, GetValueName(I));
+
+      if (I->hasExternalWeakLinkage())
+         Out << " __EXTERNAL_WEAK__";
+      Out << ";\n";
     }
   }
 
@@ -1494,6 +1560,8 @@ bool CWriter::doInitialization(Module &M) {
         Out << " __ATTRIBUTE_CTOR__";
       if (StaticDtors.count(I))
         Out << " __ATTRIBUTE_DTOR__";
+      if (I->hasHiddenVisibility())
+        Out << " __HIDDEN__";
       
       if (I->hasName() && I->getName()[0] == 1)
         Out << " LLVM_ASM(\"" << I->getName().c_str()+1 << "\")";
@@ -1507,17 +1575,22 @@ bool CWriter::doInitialization(Module &M) {
     Out << "\n\n/* Global Variable Declarations */\n";
     for (Module::global_iterator I = M.global_begin(), E = M.global_end();
          I != E; ++I)
-      if (!I->isExternal()) {
+      if (!I->isDeclaration()) {
         // Ignore special globals, such as debug info.
         if (getGlobalVariableClass(I))
           continue;
-        
+
         if (I->hasInternalLinkage())
           Out << "static ";
         else
           Out << "extern ";
+
+        // Thread Local Storage
+        if (I->isThreadLocal())
+          Out << "__thread ";
+
         printType(Out, I->getType()->getElementType(), false, 
-                  Mang->getValueName(I));
+                  GetValueName(I));
 
         if (I->hasLinkOnceLinkage())
           Out << " __attribute__((common))";
@@ -1525,6 +1598,8 @@ bool CWriter::doInitialization(Module &M) {
           Out << " __ATTRIBUTE_WEAK__";
         else if (I->hasExternalWeakLinkage())
           Out << " __EXTERNAL_WEAK__";
+        if (I->hasHiddenVisibility())
+          Out << " __HIDDEN__";
         Out << ";\n";
       }
   }
@@ -1534,25 +1609,32 @@ bool CWriter::doInitialization(Module &M) {
     Out << "\n\n/* Global Variable Definitions and Initialization */\n";
     for (Module::global_iterator I = M.global_begin(), E = M.global_end(); 
          I != E; ++I)
-      if (!I->isExternal()) {
+      if (!I->isDeclaration()) {
         // Ignore special globals, such as debug info.
         if (getGlobalVariableClass(I))
           continue;
-        
+
         if (I->hasInternalLinkage())
           Out << "static ";
         else if (I->hasDLLImportLinkage())
           Out << "__declspec(dllimport) ";
         else if (I->hasDLLExportLinkage())
           Out << "__declspec(dllexport) ";
-            
+
+        // Thread Local Storage
+        if (I->isThreadLocal())
+          Out << "__thread ";
+
         printType(Out, I->getType()->getElementType(), false, 
-                  Mang->getValueName(I));
+                  GetValueName(I));
         if (I->hasLinkOnceLinkage())
           Out << " __attribute__((common))";
         else if (I->hasWeakLinkage())
           Out << " __ATTRIBUTE_WEAK__";
 
+        if (I->hasHiddenVisibility())
+          Out << " __HIDDEN__";
+        
         // If the initializer is not null, emit the initializer.  If it is null,
         // we try to avoid emitting large amounts of zeros.  The problem with
         // this, however, occurs when the variable has weak linkage.  In this
@@ -1568,7 +1650,7 @@ bool CWriter::doInitialization(Module &M) {
           Out << " = " ;
           if (isa<StructType>(I->getInitializer()->getType()) ||
               isa<ArrayType>(I->getInitializer()->getType()) ||
-              isa<PackedType>(I->getInitializer()->getType())) {
+              isa<VectorType>(I->getInitializer()->getType())) {
             Out << "{ 0 }";
           } else {
             // Just print it out normally.
@@ -1629,15 +1711,15 @@ void CWriter::printFloatingPointConstants(Function &F) {
     if (const ConstantFP *FPC = dyn_cast<ConstantFP>(*I))
       if (!isFPCSafeToPrint(FPC) && // Do not put in FPConstantMap if safe.
           !FPConstantMap.count(FPC)) {
-        double Val = FPC->getValue();
-
         FPConstantMap[FPC] = FPCounter;  // Number the FP constants
 
         if (FPC->getType() == Type::DoubleTy) {
+          double Val = FPC->getValueAPF().convertToDouble();
           Out << "static const ConstantDoubleTy FPConstant" << FPCounter++
               << " = 0x" << std::hex << DoubleToBits(Val) << std::dec
               << "ULL;    /* " << Val << " */\n";
         } else if (FPC->getType() == Type::FloatTy) {
+          float Val = FPC->getValueAPF().convertToFloat();
           Out << "static const ConstantFloatTy FPConstant" << FPCounter++
               << " = 0x" << std::hex << FloatToBits(Val) << std::dec
               << "U;    /* " << Val << " */\n";
@@ -1670,22 +1752,21 @@ void CWriter::printModuleTypes(const TypeSymbolTable &TST) {
 
   // Print out forward declarations for structure types before anything else!
   Out << "/* Structure forward decls */\n";
-  for (; I != End; ++I)
-    if (const Type *STy = dyn_cast<StructType>(I->second)) {
-      std::string Name = "struct l_" + Mang->makeNameProper(I->first);
-      Out << Name << ";\n";
-      TypeNames.insert(std::make_pair(STy, Name));
-    }
+  for (; I != End; ++I) {
+    std::string Name = "struct l_" + Mang->makeNameProper(I->first);
+    Out << Name << ";\n";
+    TypeNames.insert(std::make_pair(I->second, Name));
+  }
 
   Out << '\n';
 
-  // Now we can print out typedefs...
+  // Now we can print out typedefs.  Above, we guaranteed that this can only be
+  // for struct or opaque types.
   Out << "/* Typedefs */\n";
   for (I = TST.begin(); I != End; ++I) {
-    const Type *Ty = cast<Type>(I->second);
     std::string Name = "l_" + Mang->makeNameProper(I->first);
     Out << "typedef ";
-    printType(Out, Ty, false, Name);
+    printType(Out, I->second, false, Name);
     Out << ";\n";
   }
 
@@ -1707,12 +1788,12 @@ void CWriter::printModuleTypes(const TypeSymbolTable &TST) {
 // Push the struct onto the stack and recursively push all structs
 // this one depends on.
 //
-// TODO:  Make this work properly with packed types
+// TODO:  Make this work properly with vector types
 //
 void CWriter::printContainedStructs(const Type *Ty,
                                     std::set<const StructType*> &StructPrinted){
   // Don't walk through pointers.
-  if (isa<PointerType>(Ty) || Ty->isPrimitiveType()) return;
+  if (isa<PointerType>(Ty) || Ty->isPrimitiveType() || Ty->isInteger()) return;
   
   // Print all contained types first.
   for (Type::subtype_iterator I = Ty->subtype_begin(),
@@ -1731,8 +1812,8 @@ void CWriter::printContainedStructs(const Type *Ty,
 }
 
 void CWriter::printFunctionSignature(const Function *F, bool Prototype) {
-  /// isCStructReturn - Should this function actually return a struct by-value?
-  bool isCStructReturn = F->getCallingConv() == CallingConv::CSRet;
+  /// isStructReturn - Should this function actually return a struct by-value?
+  bool isStructReturn = F->getFunctionType()->isStructReturn();
   
   if (F->hasInternalLinkage()) Out << "static ";
   if (F->hasDLLImportLinkage()) Out << "__declspec(dllimport) ";
@@ -1748,20 +1829,21 @@ void CWriter::printFunctionSignature(const Function *F, bool Prototype) {
   
   // Loop over the arguments, printing them...
   const FunctionType *FT = cast<FunctionType>(F->getFunctionType());
+  const ParamAttrsList *Attrs = FT->getParamAttrs();
 
   std::stringstream FunctionInnards;
 
   // Print out the name...
-  FunctionInnards << Mang->getValueName(F) << '(';
+  FunctionInnards << GetValueName(F) << '(';
 
   bool PrintedArg = false;
-  if (!F->isExternal()) {
+  if (!F->isDeclaration()) {
     if (!F->arg_empty()) {
       Function::const_arg_iterator I = F->arg_begin(), E = F->arg_end();
       
       // If this is a struct-return function, don't print the hidden
       // struct-return argument.
-      if (isCStructReturn) {
+      if (isStructReturn) {
         assert(I != E && "Invalid struct return function!");
         ++I;
       }
@@ -1771,11 +1853,11 @@ void CWriter::printFunctionSignature(const Function *F, bool Prototype) {
       for (; I != E; ++I) {
         if (PrintedArg) FunctionInnards << ", ";
         if (I->hasName() || !Prototype)
-          ArgName = Mang->getValueName(I);
+          ArgName = GetValueName(I);
         else
           ArgName = "";
         printType(FunctionInnards, I->getType(), 
-            /*isSigned=*/FT->paramHasAttr(Idx, FunctionType::SExtAttribute), 
+            /*isSigned=*/Attrs && Attrs->paramHasAttr(Idx, ParamAttr::SExt), 
             ArgName);
         PrintedArg = true;
         ++Idx;
@@ -1787,7 +1869,7 @@ void CWriter::printFunctionSignature(const Function *F, bool Prototype) {
     
     // If this is a struct-return function, don't print the hidden
     // struct-return argument.
-    if (isCStructReturn) {
+    if (isStructReturn) {
       assert(I != E && "Invalid struct return function!");
       ++I;
     }
@@ -1796,7 +1878,7 @@ void CWriter::printFunctionSignature(const Function *F, bool Prototype) {
     for (; I != E; ++I) {
       if (PrintedArg) FunctionInnards << ", ";
       printType(FunctionInnards, *I,
-             /*isSigned=*/FT->paramHasAttr(Idx, FunctionType::SExtAttribute));
+             /*isSigned=*/Attrs && Attrs->paramHasAttr(Idx, ParamAttr::SExt));
       PrintedArg = true;
       ++Idx;
     }
@@ -1815,7 +1897,7 @@ void CWriter::printFunctionSignature(const Function *F, bool Prototype) {
   
   // Get the return tpe for the function.
   const Type *RetTy;
-  if (!isCStructReturn)
+  if (!isStructReturn)
     RetTy = F->getReturnType();
   else {
     // If this is a struct-return function, print the struct-return type.
@@ -1824,7 +1906,7 @@ void CWriter::printFunctionSignature(const Function *F, bool Prototype) {
     
   // Print out the return type and the signature built above.
   printType(Out, RetTy, 
-            /*isSigned=*/FT->paramHasAttr(0, FunctionType::SExtAttribute), 
+            /*isSigned=*/ Attrs && Attrs->paramHasAttr(0, ParamAttr::SExt), 
             FunctionInnards.str());
 }
 
@@ -1838,11 +1920,14 @@ static inline bool isFPIntBitCast(const Instruction &I) {
 }
 
 void CWriter::printFunction(Function &F) {
+  /// isStructReturn - Should this function actually return a struct by-value?
+  bool isStructReturn = F.getFunctionType()->isStructReturn();
+
   printFunctionSignature(&F, false);
   Out << " {\n";
   
   // If this is a struct return function, handle the result with magic.
-  if (F.getCallingConv() == CallingConv::CSRet) {
+  if (isStructReturn) {
     const Type *StructTy =
       cast<PointerType>(F.arg_begin()->getType())->getElementType();
     Out << "  ";
@@ -1851,7 +1936,7 @@ void CWriter::printFunction(Function &F) {
 
     Out << "  ";
     printType(Out, F.arg_begin()->getType(), false, 
-              Mang->getValueName(F.arg_begin()));
+              GetValueName(F.arg_begin()));
     Out << " = &StructReturn;\n";
   }
 
@@ -1861,18 +1946,18 @@ void CWriter::printFunction(Function &F) {
   for (inst_iterator I = inst_begin(&F), E = inst_end(&F); I != E; ++I) {
     if (const AllocaInst *AI = isDirectAlloca(&*I)) {
       Out << "  ";
-      printType(Out, AI->getAllocatedType(), false, Mang->getValueName(AI));
+      printType(Out, AI->getAllocatedType(), false, GetValueName(AI));
       Out << ";    /* Address-exposed local */\n";
       PrintedVar = true;
     } else if (I->getType() != Type::VoidTy && !isInlinableInst(*I)) {
       Out << "  ";
-      printType(Out, I->getType(), false, Mang->getValueName(&*I));
+      printType(Out, I->getType(), false, GetValueName(&*I));
       Out << ";\n";
 
       if (isa<PHINode>(*I)) {  // Print out PHI node temporaries as well...
         Out << "  ";
         printType(Out, I->getType(), false,
-                  Mang->getValueName(&*I)+"__PHI_TEMPORARY");
+                  GetValueName(&*I)+"__PHI_TEMPORARY");
         Out << ";\n";
       }
       PrintedVar = true;
@@ -1881,7 +1966,7 @@ void CWriter::printFunction(Function &F) {
     // of a union to do the BitCast. This is separate from the need for a
     // variable to hold the result of the BitCast. 
     if (isFPIntBitCast(*I)) {
-      Out << "  llvmBitCastUnion " << Mang->getValueName(&*I)
+      Out << "  llvmBitCastUnion " << GetValueName(&*I)
           << "__BITCAST_TEMPORARY;\n";
       PrintedVar = true;
     }
@@ -1935,7 +2020,7 @@ void CWriter::printBasicBlock(BasicBlock *BB) {
       break;
     }
 
-  if (NeedsLabel) Out << Mang->getValueName(BB) << ":\n";
+  if (NeedsLabel) Out << GetValueName(BB) << ":\n";
 
   // Output all of the instructions in the basic block...
   for (BasicBlock::iterator II = BB->begin(), E = --BB->end(); II != E;
@@ -1960,7 +2045,10 @@ void CWriter::printBasicBlock(BasicBlock *BB) {
 //
 void CWriter::visitReturnInst(ReturnInst &I) {
   // If this is a struct return function, return the temporary struct.
-  if (I.getParent()->getParent()->getCallingConv() == CallingConv::CSRet) {
+  bool isStructReturn = I.getParent()->getParent()->
+    getFunctionType()->isStructReturn();
+
+  if (isStructReturn) {
     Out << "  return StructReturn;\n";
     return;
   }
@@ -2028,7 +2116,7 @@ void CWriter::printPHICopiesForSuccessor (BasicBlock *CurBlock,
     Value *IV = PN->getIncomingValueForBlock(CurBlock);
     if (!isa<UndefValue>(IV)) {
       Out << std::string(Indent, ' ');
-      Out << "  " << Mang->getValueName(I) << "__PHI_TEMPORARY = ";
+      Out << "  " << GetValueName(I) << "__PHI_TEMPORARY = ";
       writeOperand(IV);
       Out << ";   /* for PHI node */\n";
     }
@@ -2132,18 +2220,18 @@ void CWriter::visitBinaryOperator(Instruction &I) {
     writeOperandWithCast(I.getOperand(0), I.getOpcode());
 
     switch (I.getOpcode()) {
-    case Instruction::Add: Out << " + "; break;
-    case Instruction::Sub: Out << " - "; break;
-    case Instruction::Mul: Out << '*'; break;
+    case Instruction::Add:  Out << " + "; break;
+    case Instruction::Sub:  Out << " - "; break;
+    case Instruction::Mul:  Out << " * "; break;
     case Instruction::URem:
     case Instruction::SRem:
-    case Instruction::FRem: Out << '%'; break;
+    case Instruction::FRem: Out << " % "; break;
     case Instruction::UDiv:
     case Instruction::SDiv: 
-    case Instruction::FDiv: Out << '/'; break;
-    case Instruction::And: Out << " & "; break;
-    case Instruction::Or: Out << " | "; break;
-    case Instruction::Xor: Out << " ^ "; break;
+    case Instruction::FDiv: Out << " / "; break;
+    case Instruction::And:  Out << " & "; break;
+    case Instruction::Or:   Out << " | "; break;
+    case Instruction::Xor:  Out << " ^ "; break;
     case Instruction::Shl : Out << " << "; break;
     case Instruction::LShr:
     case Instruction::AShr: Out << " >> "; break;
@@ -2238,9 +2326,14 @@ static const char * getFloatBitCastField(const Type *Ty) {
   switch (Ty->getTypeID()) {
     default: assert(0 && "Invalid Type");
     case Type::FloatTyID:  return "Float";
-    case Type::Int32TyID:  return "Int32";
     case Type::DoubleTyID: return "Double";
-    case Type::Int64TyID:  return "Int64";
+    case Type::IntegerTyID: {
+      unsigned NumBits = cast<IntegerType>(Ty)->getBitWidth();
+      if (NumBits <= 32)
+        return "Int32";
+      else
+        return "Int64";
+    }
   }
 }
 
@@ -2250,19 +2343,19 @@ void CWriter::visitCastInst(CastInst &I) {
   Out << '(';
   if (isFPIntBitCast(I)) {
     // These int<->float and long<->double casts need to be handled specially
-    Out << Mang->getValueName(&I) << "__BITCAST_TEMPORARY." 
+    Out << GetValueName(&I) << "__BITCAST_TEMPORARY." 
         << getFloatBitCastField(I.getOperand(0)->getType()) << " = ";
     writeOperand(I.getOperand(0));
-    Out << ", " << Mang->getValueName(&I) << "__BITCAST_TEMPORARY."
+    Out << ", " << GetValueName(&I) << "__BITCAST_TEMPORARY."
         << getFloatBitCastField(I.getType());
   } else {
     printCast(I.getOpcode(), SrcTy, DstTy);
-    if (I.getOpcode() == Instruction::SExt && SrcTy == Type::BoolTy) {
+    if (I.getOpcode() == Instruction::SExt && SrcTy == Type::Int1Ty) {
       // Make sure we really get a sext from bool by subtracing the bool from 0
       Out << "0-";
     }
     writeOperand(I.getOperand(0));
-    if (DstTy == Type::BoolTy && 
+    if (DstTy == Type::Int1Ty && 
         (I.getOpcode() == Instruction::Trunc ||
          I.getOpcode() == Instruction::FPToUI ||
          I.getOpcode() == Instruction::FPToSI ||
@@ -2286,7 +2379,14 @@ void CWriter::visitSelectInst(SelectInst &I) {
 
 
 void CWriter::lowerIntrinsics(Function &F) {
-  for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
+  // This is used to keep track of intrinsics that get generated to a lowered
+  // function. We must generate the prototypes before the function body which
+  // will only be expanded on first use (by the loop below).
+  std::vector<Function*> prototypesToGen;
+
+  // Examine all the instructions in this function to find the intrinsics that
+  // need to be lowered.
+  for (Function::iterator BB = F.begin(), EE = F.end(); BB != EE; ++BB)
     for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; )
       if (CallInst *CI = dyn_cast<CallInst>(I++))
         if (Function *F = CI->getCalledFunction())
@@ -2320,16 +2420,36 @@ void CWriter::lowerIntrinsics(Function &F) {
             if (CI != &BB->front())
               Before = prior(BasicBlock::iterator(CI));
 
-            IL.LowerIntrinsicCall(CI);
+            IL->LowerIntrinsicCall(CI);
             if (Before) {        // Move iterator to instruction after call
               I = Before; ++I;
             } else {
               I = BB->begin();
             }
+            // If the intrinsic got lowered to another call, and that call has
+            // a definition then we need to make sure its prototype is emitted
+            // before any calls to it.
+            if (CallInst *Call = dyn_cast<CallInst>(I))
+              if (Function *NewF = Call->getCalledFunction())
+                if (!NewF->isDeclaration())
+                  prototypesToGen.push_back(NewF);
+
             break;
           }
-}
 
+  // We may have collected some prototypes to emit in the loop above. 
+  // Emit them now, before the function that uses them is emitted. But,
+  // be careful not to emit them twice.
+  std::vector<Function*>::iterator I = prototypesToGen.begin();
+  std::vector<Function*>::iterator E = prototypesToGen.end();
+  for ( ; I != E; ++I) {
+    if (intrinsicPrototypesAlreadyGenerated.insert(*I).second) {
+      Out << '\n';
+      printFunctionSignature(*I, true);
+      Out << ";\n";
+    }
+  }
+}
 
 
 void CWriter::visitCallInst(CallInst &I) {
@@ -2446,9 +2566,12 @@ void CWriter::visitCallInst(CallInst &I) {
 
   Value *Callee = I.getCalledValue();
 
+  const PointerType  *PTy   = cast<PointerType>(Callee->getType());
+  const FunctionType *FTy   = cast<FunctionType>(PTy->getElementType());
+
   // If this is a call to a struct-return function, assign to the first
   // parameter instead of passing it to the call.
-  bool isStructRet = I.getCallingConv() == CallingConv::CSRet;
+  bool isStructRet = FTy->isStructReturn();
   if (isStructRet) {
     Out << "*(";
     writeOperand(I.getOperand(1));
@@ -2456,9 +2579,6 @@ void CWriter::visitCallInst(CallInst &I) {
   }
   
   if (I.isTailCall()) Out << " /*tail*/ ";
-
-  const PointerType  *PTy   = cast<PointerType>(Callee->getType());
-  const FunctionType *FTy   = cast<FunctionType>(PTy->getElementType());
   
   if (!WroteCallee) {
     // If this is an indirect call to a struct return function, we need to cast
@@ -2509,6 +2629,7 @@ void CWriter::visitCallInst(CallInst &I) {
     ++ArgNo;
   }
       
+  const ParamAttrsList *Attrs = FTy->getParamAttrs();
   bool PrintedArg = false;
   unsigned Idx = 1;
   for (; AI != AE; ++AI, ++ArgNo, ++Idx) {
@@ -2517,7 +2638,7 @@ void CWriter::visitCallInst(CallInst &I) {
         (*AI)->getType() != FTy->getParamType(ArgNo)) {
       Out << '(';
       printType(Out, FTy->getParamType(ArgNo), 
-            /*isSigned=*/FTy->paramHasAttr(Idx, FunctionType::SExtAttribute));
+            /*isSigned=*/Attrs && Attrs->paramHasAttr(Idx, ParamAttr::SExt));
       Out << ')';
     }
     writeOperand(*AI);
@@ -2754,7 +2875,21 @@ void CWriter::visitStoreInst(StoreInst &I) {
   writeOperand(I.getPointerOperand());
   if (I.isVolatile()) Out << ')';
   Out << " = ";
-  writeOperand(I.getOperand(0));
+  Value *Operand = I.getOperand(0);
+  Constant *BitMask = 0;
+  if (const IntegerType* ITy = dyn_cast<IntegerType>(Operand->getType()))
+    if (!ITy->isPowerOf2ByteWidth())
+      // We have a bit width that doesn't match an even power-of-2 byte
+      // size. Consequently we must & the value with the type's bit mask
+      BitMask = ConstantInt::get(ITy, ITy->getBitMask());
+  if (BitMask)
+    Out << "((";
+  writeOperand(Operand);
+  if (BitMask) {
+    Out << ") & ";
+    printConstant(BitMask);
+    Out << ")"; 
+  }
 }
 
 void CWriter::visitGetElementPtrInst(GetElementPtrInst &I) {