Turn off "attribute weak" to pacify Mac OS X's system compiler, which prints a
[oota-llvm.git] / lib / Target / CBackend / Writer.cpp
index a12afa7958136792d26602de992a123a86dc8000..3d73493d94acc23406a99f6ccf105669e2361bc8 100644 (file)
@@ -1,4 +1,11 @@
 //===-- Writer.cpp - Library for converting LLVM code to C ----------------===//
+// 
+//                     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 library converts LLVM code to C code, compilable by GCC.
 //
 #include "llvm/Pass.h"
 #include "llvm/SymbolTable.h"
 #include "llvm/Intrinsics.h"
-#include "llvm/SlotCalculator.h"
 #include "llvm/Analysis/FindUsedTypes.h"
 #include "llvm/Analysis/ConstantsScanner.h"
+#include "llvm/Support/CallSite.h"
+#include "llvm/Support/GetElementPtrTypeIterator.h"
 #include "llvm/Support/InstVisitor.h"
 #include "llvm/Support/InstIterator.h"
+#include "llvm/Support/Mangler.h"
 #include "Support/StringExtras.h"
 #include "Support/STLExtras.h"
+#include "Config/config.h"
 #include <algorithm>
-#include <set>
 #include <sstream>
 
+namespace llvm {
+
 namespace {
   class CWriter : public Pass, public InstVisitor<CWriter> {
     std::ostream &Out; 
-    SlotCalculator *Table;
+    Mangler *Mang;
     const Module *TheModule;
+    FindUsedTypes *FUT;
+
     std::map<const Type *, std::string> TypeNames;
     std::set<const Value*> MangledGlobals;
-    bool needsMalloc;
+    bool needsMalloc, emittedInvoke;
 
     std::map<const ConstantFP *, unsigned> FPConstantMap;
   public:
@@ -43,17 +56,18 @@ namespace {
 
     virtual bool run(Module &M) {
       // Initialize
-      Table = new SlotCalculator(&M, false);
       TheModule = &M;
+      FUT = &getAnalysis<FindUsedTypes>();
 
       // Ensure that all structure types have names...
       bool Changed = nameAllUsedStructureTypes(M);
+      Mang = new Mangler(M);
 
       // Run...
       printModule(&M);
 
       // Free memory...
-      delete Table;
+      delete Mang;
       TypeNames.clear();
       MangledGlobals.clear();
       return false;
@@ -61,19 +75,17 @@ namespace {
 
     std::ostream &printType(std::ostream &Out, const Type *Ty,
                             const std::string &VariableName = "",
-                            bool IgnoreName = false, bool namedContext = true);
+                            bool IgnoreName = false);
 
     void writeOperand(Value *Operand);
     void writeOperandInternal(Value *Operand);
 
-    std::string getValueName(const Value *V);
-
   private :
     bool nameAllUsedStructureTypes(Module &M);
     void printModule(Module *M);
+    void printFloatingPointConstants(Module &M);
     void printSymbolTable(const SymbolTable &ST);
     void printContainedStructs(const Type *Ty, std::set<const StructType *> &);
-    void printGlobal(const GlobalVariable *GV);
     void printFunctionSignature(const Function *F, bool Prototype);
 
     void printFunction(Function *);
@@ -89,27 +101,45 @@ namespace {
     static bool isInlinableInst(const Instruction &I) {
       // Must be an expression, must be used exactly once.  If it is dead, we
       // emit it inline where it would go.
-      if (I.getType() == Type::VoidTy || I.use_size() != 1 ||
+      if (I.getType() == Type::VoidTy || !I.hasOneUse() ||
           isa<TerminatorInst>(I) || isa<CallInst>(I) || isa<PHINode>(I) || 
-          isa<LoadInst>(I)) // Don't inline a load across a store!
+          isa<LoadInst>(I) || isa<VAArgInst>(I) || isa<VANextInst>(I))
+        // Don't inline a load across a store or other bad things!
         return false;
 
       // Only inline instruction it it's use is in the same BB as the inst.
       return I.getParent() == cast<Instruction>(I.use_back())->getParent();
     }
 
+    // isDirectAlloca - Define fixed sized allocas in the entry block as direct
+    // variables which are accessed with the & operator.  This causes GCC to
+    // generate significantly better code than to emit alloca calls directly.
+    //
+    static const AllocaInst *isDirectAlloca(const Value *V) {
+      const AllocaInst *AI = dyn_cast<AllocaInst>(V);
+      if (!AI) return false;
+      if (AI->isArrayAllocation())
+        return 0;   // FIXME: we can also inline fixed size array allocas!
+      if (AI->getParent() != &AI->getParent()->getParent()->getEntryBlock())
+        return 0;
+      return AI;
+    }
+
     // Instruction visitation functions
     friend class InstVisitor<CWriter>;
 
     void visitReturnInst(ReturnInst &I);
     void visitBranchInst(BranchInst &I);
     void visitSwitchInst(SwitchInst &I);
+    void visitInvokeInst(InvokeInst &I);
+    void visitUnwindInst(UnwindInst &I);
 
     void visitPHINode(PHINode &I);
     void visitBinaryOperator(Instruction &I);
 
     void visitCastInst (CastInst &I);
     void visitCallInst (CallInst &I);
+    void visitCallSite (CallSite CS);
     void visitShiftInst(ShiftInst &I) { visitBinaryOperator(I); }
 
     void visitMallocInst(MallocInst &I);
@@ -118,7 +148,8 @@ namespace {
     void visitLoadInst  (LoadInst   &I);
     void visitStoreInst (StoreInst  &I);
     void visitGetElementPtrInst(GetElementPtrInst &I);
-    void visitVarArgInst(VarArgInst &I);
+    void visitVANextInst(VANextInst &I);
+    void visitVAArgInst (VAArgInst &I);
 
     void visitInstruction(Instruction &I) {
       std::cerr << "C Writer does not know about " << I;
@@ -126,57 +157,20 @@ namespace {
     }
 
     void outputLValue(Instruction *I) {
-      Out << "  " << getValueName(I) << " = ";
+      Out << "  " << Mang->getValueName(I) << " = ";
     }
     void printBranchToBlock(BasicBlock *CurBlock, BasicBlock *SuccBlock,
                             unsigned Indent);
-    void printIndexingExpression(Value *Ptr, User::op_iterator I,
-                                 User::op_iterator E);
+    void printIndexingExpression(Value *Ptr, gep_type_iterator I,
+                                 gep_type_iterator E);
   };
-}
-
-// We dont want identifier names with ., space, -  in them. 
-// So we replace them with _
-static std::string makeNameProper(std::string x) {
-  std::string tmp;
-  for (std::string::iterator sI = x.begin(), sEnd = x.end(); sI != sEnd; sI++)
-    switch (*sI) {
-    case '.': tmp += "d_"; break;
-    case ' ': tmp += "s_"; break;
-    case '-': tmp += "D_"; break;
-    default:  tmp += *sI;
-    }
-
-  return tmp;
-}
-
-std::string CWriter::getValueName(const Value *V) {
-  if (V->hasName()) {              // Print out the label if it exists...
-    if (isa<GlobalValue>(V) &&     // Do not mangle globals...
-        (cast<GlobalValue>(V)->hasExternalLinkage() &&// Unless it's internal or
-         !MangledGlobals.count(V))) // Unless the name would collide if we don't
-      return makeNameProper(V->getName());
-
-    return "l" + utostr(V->getType()->getUniqueID()) + "_" +
-           makeNameProper(V->getName());      
-  }
-
-  int Slot = Table->getValSlot(V);
-  assert(Slot >= 0 && "Invalid value!");
-  return "ltmp_" + itostr(Slot) + "_" + utostr(V->getType()->getUniqueID());
-}
-
-// A pointer type should not use parens around *'s alone, e.g., (**)
-inline bool ptrTypeNameNeedsParens(const std::string &NameSoFar) {
-  return (NameSoFar.find_last_not_of('*') != std::string::npos);
-}
 
 // Pass the Type* and the variable name and this prints out the variable
 // declaration.
 //
 std::ostream &CWriter::printType(std::ostream &Out, const Type *Ty,
                                  const std::string &NameSoFar,
-                                 bool IgnoreName, bool namedContext) {
+                                 bool IgnoreName) {
   if (Ty->isPrimitiveType())
     switch (Ty->getPrimitiveID()) {
     case Type::VoidTyID:   return Out << "void "               << NameSoFar;
@@ -199,31 +193,29 @@ std::ostream &CWriter::printType(std::ostream &Out, const Type *Ty,
   // Check to see if the type is named.
   if (!IgnoreName || isa<OpaqueType>(Ty)) {
     std::map<const Type *, std::string>::iterator I = TypeNames.find(Ty);
-    if (I != TypeNames.end()) {
-      return Out << I->second << " " << NameSoFar;
-    }
+    if (I != TypeNames.end()) return Out << I->second << " " << NameSoFar;
   }
 
   switch (Ty->getPrimitiveID()) {
   case Type::FunctionTyID: {
     const FunctionType *MTy = cast<FunctionType>(Ty);
-    std::stringstream FunctionInards; 
-    FunctionInards << " (" << NameSoFar << ") (";
+    std::stringstream FunctionInnards; 
+    FunctionInnards << " (" << NameSoFar << ") (";
     for (FunctionType::ParamTypes::const_iterator
            I = MTy->getParamTypes().begin(),
            E = MTy->getParamTypes().end(); I != E; ++I) {
       if (I != MTy->getParamTypes().begin())
-        FunctionInards << ", ";
-      printType(FunctionInards, *I, "");
+        FunctionInnards << ", ";
+      printType(FunctionInnards, *I, "");
     }
     if (MTy->isVarArg()) {
       if (!MTy->getParamTypes().empty()) 
-       FunctionInards << ", ...";
+       FunctionInnards << ", ...";
     } else if (MTy->getParamTypes().empty()) {
-      FunctionInards << "void";
+      FunctionInnards << "void";
     }
-    FunctionInards << ")";
-    std::string tstr = FunctionInards.str();
+    FunctionInnards << ")";
+    std::string tstr = FunctionInnards.str();
     printType(Out, MTy->getReturnType(), tstr);
     return Out;
   }
@@ -245,15 +237,11 @@ std::ostream &CWriter::printType(std::ostream &Out, const Type *Ty,
     const PointerType *PTy = cast<PointerType>(Ty);
     std::string ptrName = "*" + NameSoFar;
 
-    // Do not need parens around "* NameSoFar" if NameSoFar consists only
-    // of zero or more '*' chars *and* this is not an unnamed pointer type
-    // such as the result type in a cast statement.  Otherwise, enclose in ( ).
-    if (ptrTypeNameNeedsParens(NameSoFar) || !namedContext || 
-        PTy->getElementType()->getPrimitiveID() == Type::ArrayTyID)
-      ptrName = "(" + ptrName + ")";    // 
+    if (isa<ArrayType>(PTy->getElementType()))
+      ptrName = "(" + ptrName + ")";
 
     return printType(Out, PTy->getElementType(), ptrName);
-  }Out <<"--";
+  }
 
   case Type::ArrayTyID: {
     const ArrayType *ATy = cast<ArrayType>(Ty);
@@ -286,24 +274,33 @@ void CWriter::printConstantArray(ConstantArray *CPA) {
   bool isString = (ETy == Type::SByteTy || ETy == Type::UByteTy);
 
   // Make sure the last character is a null char, as automatically added by C
-  if (CPA->getNumOperands() == 0 ||
-      !cast<Constant>(*(CPA->op_end()-1))->isNullValue())
+  if (isString && (CPA->getNumOperands() == 0 ||
+                   !cast<Constant>(*(CPA->op_end()-1))->isNullValue()))
     isString = false;
   
   if (isString) {
     Out << "\"";
+    // Keep track of whether the last number was a hexadecimal escape
+    bool LastWasHex = false;
+
     // Do not include the last character, which we know is null
     for (unsigned i = 0, e = CPA->getNumOperands()-1; i != e; ++i) {
-      unsigned char C = (ETy == Type::SByteTy) ?
-        (unsigned char)cast<ConstantSInt>(CPA->getOperand(i))->getValue() :
-        (unsigned char)cast<ConstantUInt>(CPA->getOperand(i))->getValue();
+      unsigned char C = cast<ConstantInt>(CPA->getOperand(i))->getRawValue();
       
-      if (isprint(C)) {
+      // Print it out literally if it is a printable character.  The only thing
+      // to be careful about is when the last letter output was a hex escape
+      // code, in which case we have to be careful not to print out hex digits
+      // explicitly (the C compiler thinks it is a continuation of the previous
+      // character, sheesh...)
+      //
+      if (isprint(C) && (!LastWasHex || !isxdigit(C))) {
+        LastWasHex = false;
         if (C == '"' || C == '\\')
           Out << "\\" << C;
         else
           Out << C;
       } else {
+        LastWasHex = false;
         switch (C) {
         case '\n': Out << "\\n"; break;
         case '\t': Out << "\\t"; break;
@@ -314,8 +311,9 @@ void CWriter::printConstantArray(ConstantArray *CPA) {
         case '\'': Out << "\\\'"; break;           
         default:
           Out << "\\x";
-          Out << ( C/16  < 10) ? ( C/16 +'0') : ( C/16 -10+'A');
-          Out << ((C&15) < 10) ? ((C&15)+'0') : ((C&15)-10+'A');
+          Out << (char)(( C/16  < 10) ? ( C/16 +'0') : ( C/16 -10+'A'));
+          Out << (char)(((C&15) < 10) ? ((C&15)+'0') : ((C&15)-10+'A'));
+          LastWasHex = true;
           break;
         }
       }
@@ -335,6 +333,40 @@ void CWriter::printConstantArray(ConstantArray *CPA) {
   }
 }
 
+// isFPCSafeToPrint - Returns true if we may assume that CFP may be written out
+// textually as a double (rather than as a reference to a stack-allocated
+// variable). We decide this by converting CFP to a string and back into a
+// double, and then checking whether the conversion results in a bit-equal
+// double to the original value of CFP. This depends on us and the target C
+// compiler agreeing on the conversion process (which is pretty likely since we
+// only deal in IEEE FP).
+//
+bool isFPCSafeToPrint(const ConstantFP *CFP) {
+#if HAVE_PRINTF_A
+  char Buffer[100];
+  sprintf(Buffer, "%a", CFP->getValue());
+
+  if (!strncmp(Buffer, "0x", 2) ||
+      !strncmp(Buffer, "-0x", 3) ||
+      !strncmp(Buffer, "+0x", 3))
+    return atof(Buffer) == CFP->getValue();
+  return false;
+#else
+  std::string StrVal = ftostr(CFP->getValue());
+
+  while (StrVal[0] == ' ')
+    StrVal.erase(StrVal.begin());
+
+  // Check to make sure that the stringized number is not some string like "Inf"
+  // or NaN.  Check that the string matches the "[-+]?[0-9]" regex.
+  if ((StrVal[0] >= '0' && StrVal[0] <= '9') ||
+      ((StrVal[0] == '-' || StrVal[0] == '+') &&
+       (StrVal[1] >= '0' && StrVal[1] <= '9')))
+    // Reparse stringized version!
+    return atof(StrVal.c_str()) == CFP->getValue();
+  return false;
+#endif
+}
 
 // printConstant - The LLVM Constant to C Constant converter.
 void CWriter::printConstant(Constant *CPV) {
@@ -350,21 +382,41 @@ void CWriter::printConstant(Constant *CPV) {
 
     case Instruction::GetElementPtr:
       Out << "(&(";
-      printIndexingExpression(CE->getOperand(0),
-                              CPV->op_begin()+1, CPV->op_end());
+      printIndexingExpression(CE->getOperand(0), gep_type_begin(CPV),
+                              gep_type_end(CPV));
       Out << "))";
       return;
     case Instruction::Add:
-      Out << "(";
-      printConstant(CE->getOperand(0));
-      Out << " + ";
-      printConstant(CE->getOperand(1));
-      Out << ")";
-      return;
     case Instruction::Sub:
+    case Instruction::Mul:
+    case Instruction::Div:
+    case Instruction::Rem:
+    case Instruction::SetEQ:
+    case Instruction::SetNE:
+    case Instruction::SetLT:
+    case Instruction::SetLE:
+    case Instruction::SetGT:
+    case Instruction::SetGE:
+    case Instruction::Shl:
+    case Instruction::Shr:
       Out << "(";
       printConstant(CE->getOperand(0));
-      Out << " - ";
+      switch (CE->getOpcode()) {
+      case Instruction::Add: Out << " + "; break;
+      case Instruction::Sub: Out << " - "; break;
+      case Instruction::Mul: Out << " * "; break;
+      case Instruction::Div: Out << " / "; break;
+      case Instruction::Rem: Out << " % "; break;
+      case Instruction::SetEQ: Out << " == "; break;
+      case Instruction::SetNE: Out << " != "; break;
+      case Instruction::SetLT: Out << " < "; break;
+      case Instruction::SetLE: Out << " <= "; break;
+      case Instruction::SetGT: Out << " > "; break;
+      case Instruction::SetGE: Out << " >= "; break;
+      case Instruction::Shl: Out << " << "; break;
+      case Instruction::Shr: Out << " >> "; break;
+      default: assert(0 && "Illegal opcode here!");
+      }
       printConstant(CE->getOperand(1));
       Out << ")";
       return;
@@ -408,9 +460,16 @@ void CWriter::printConstant(Constant *CPV) {
       // Because of FP precision problems we must load from a stack allocated
       // value that holds the value in hex.
       Out << "(*(" << (FPC->getType() == Type::FloatTy ? "float" : "double")
-          << "*)&FloatConstant" << I->second << ")";
+          << "*)&FPConstant" << I->second << ")";
     } else {
-      Out << FPC->getValue();
+#if HAVE_PRINTF_A
+      // Print out the constant as a floating point number.
+      char Buffer[100];
+      sprintf(Buffer, "%a", FPC->getValue());
+      Out << Buffer << " /*" << FPC->getValue() << "*/ ";
+#else
+      Out << ftostr(FPC->getValue());
+#endif
     }
     break;
   }
@@ -435,7 +494,9 @@ void CWriter::printConstant(Constant *CPV) {
 
   case Type::PointerTyID:
     if (isa<ConstantPointerNull>(CPV)) {
-      Out << "(NULL)";
+      Out << "((";
+      printType(Out, CPV->getType());
+      Out << ")/*NULL*/0)";
       break;
     } else if (ConstantPointerRef *CPR = dyn_cast<ConstantPointerRef>(CPV)) {
       writeOperand(CPR->getValue());
@@ -450,7 +511,7 @@ void CWriter::printConstant(Constant *CPV) {
 
 void CWriter::writeOperandInternal(Value *Operand) {
   if (Instruction *I = dyn_cast<Instruction>(Operand))
-    if (isInlinableInst(*I)) {
+    if (isInlinableInst(*I) && !isDirectAlloca(I)) {
       // Should we inline this instruction to build a tree?
       Out << "(";
       visit(*I);
@@ -458,24 +519,20 @@ void CWriter::writeOperandInternal(Value *Operand) {
       return;
     }
   
-  if (Operand->hasName()) {  
-    Out << getValueName(Operand);
-  } else if (Constant *CPV = dyn_cast<Constant>(Operand)) {
+  if (Constant *CPV = dyn_cast<Constant>(Operand)) {
     printConstant(CPV); 
   } else {
-    int Slot = Table->getValSlot(Operand);
-    assert(Slot >= 0 && "Malformed LLVM!");
-    Out << "ltmp_" << Slot << "_" << Operand->getType()->getUniqueID();
+    Out << Mang->getValueName(Operand);
   }
 }
 
 void CWriter::writeOperand(Value *Operand) {
-  if (isa<GlobalVariable>(Operand))
+  if (isa<GlobalVariable>(Operand) || isDirectAlloca(Operand))
     Out << "(&";  // Global variables are references as their addresses by llvm
 
   writeOperandInternal(Operand);
 
-  if (isa<GlobalVariable>(Operand))
+  if (isa<GlobalVariable>(Operand) || isDirectAlloca(Operand))
     Out << ")";
 }
 
@@ -485,7 +542,7 @@ void CWriter::writeOperand(Value *Operand) {
 //
 bool CWriter::nameAllUsedStructureTypes(Module &M) {
   // Get a set of types that are used by the program...
-  std::set<const Type *> UT = getAnalysis<FindUsedTypes>().getTypes();
+  std::set<const Type *> UT = FUT->getTypes();
 
   // Loop over the module symbol table, removing types from UT that are already
   // named.
@@ -509,16 +566,72 @@ bool CWriter::nameAllUsedStructureTypes(Module &M) {
   return Changed;
 }
 
-static void generateAllocaDecl(std::ostream& Out) {
-  // On SunOS, we need to insert the alloca macro & proto for the builtin.
-  Out << "#ifdef sun\n"
+// generateCompilerSpecificCode - This is where we add conditional compilation
+// directives to cater to specific compilers as need be.
+//
+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"
+      << "#ifdef sun\n"
       << "extern void *__builtin_alloca(unsigned long);\n"
       << "#define alloca(x) __builtin_alloca(x)\n"
       << "#else\n"
+      << "#ifndef __FreeBSD__\n"
       << "#include <alloca.h>\n"
+      << "#endif\n"
+      << "#endif\n\n";
+
+  // We output GCC specific attributes to preserve 'linkonce'ness on globals.
+  // If we aren't being compiled with GCC, just drop these attributes.
+  Out << "#ifndef __GNUC__  /* Can only support \"linkonce\" vars with GCC */\n"
+      << "#define __attribute__(X)\n"
+      << "#endif\n\n";
+
+#if 0
+  // At some point, we should support "external weak" vs. "weak" linkages.
+  // On Mac OS X, "external weak" is spelled "__attribute__((weak_import))".
+  Out << "#if defined(__GNUC__) && defined(__APPLE_CC__)\n"
+      << "#define __EXTERNAL_WEAK__ __attribute__((weak_import))\n"
+      << "#elif defined(__GNUC__)\n"
+      << "#define __EXTERNAL_WEAK__ __attribute__((weak))\n"
+      << "#else\n"
+      << "#define __EXTERNAL_WEAK__\n"
+      << "#endif\n\n";
+#endif
+
+  // For now, turn off the weak linkage attribute on Mac OS X. (See above.)
+  Out << "#if defined(__GNUC__) && defined(__APPLE_CC__)\n"
+      << "#define __ATTRIBUTE_WEAK__\n"
+      << "#elif defined(__GNUC__)\n"
+      << "#define __ATTRIBUTE_WEAK__ __attribute__((weak))\n"
+      << "#else\n"
+      << "#define __ATTRIBUTE_WEAK__\n"
+      << "#endif\n\n";
+}
+
+// generateProcessorSpecificCode - This is where we add conditional compilation
+// directives to cater to specific processors as need be.
+//
+static void generateProcessorSpecificCode(std::ostream& Out) {
+  // According to ANSI C, longjmp'ing to a setjmp could invalidate any
+  // non-volatile variable in the scope of the setjmp.  For now, we are not
+  // doing analysis to determine which variables need to be marked volatile, so
+  // we just mark them all.
+  //
+  // HOWEVER, many targets implement setjmp by saving and restoring the register
+  // file, so they DON'T need variables to be marked volatile, and this is a
+  // HUGE pessimization for them.  For this reason, on known-good processors, we
+  // do not emit volatile qualifiers.
+  Out << "#if defined(__386__) || defined(__i386__) || \\\n"
+      << "    defined(i386) || defined(WIN32)\n"
+      << "/* setjmp does not require variables to be marked volatile */"
+      << "#define VOLATILE_FOR_SETJMP\n"
+      << "#else\n"
+      << "#define VOLATILE_FOR_SETJMP volatile\n"
       << "#endif\n\n";
 }
 
+
 void CWriter::printModule(Module *M) {
   // Calculate which global values have names that will collide when we throw
   // away type information.
@@ -541,19 +654,24 @@ void CWriter::printModule(Module *M) {
 
   // get declaration for alloca
   Out << "/* Provide Declarations */\n";
-  generateAllocaDecl(Out);
-  Out << "#include <stdarg.h>\n";
-  Out << "#include <setjmp.h>\n";
-  
-  // Provide a definition for null if one does not already exist,
-  // and for `bool' if not compiling with a C++ compiler.
-  Out << "#ifndef NULL\n#define NULL 0\n#endif\n\n"
+  Out << "#include <stdarg.h>\n";      // Varargs support
+  Out << "#include <setjmp.h>\n";      // Unwind support
+  generateCompilerSpecificCode(Out);
+  generateProcessorSpecificCode(Out);
+
+  // Provide a definition for `bool' if not compiling with a C++ compiler.
+  Out << "\n"
       << "#ifndef __cplusplus\ntypedef unsigned char bool;\n#endif\n"
     
       << "\n\n/* Support for floating point constants */\n"
       << "typedef unsigned long long ConstantDoubleTy;\n"
       << "typedef unsigned int        ConstantFloatTy;\n"
     
+      << "\n\n/* Support for the invoke instruction */\n"
+      << "extern struct __llvm_jmpbuf_list_t {\n"
+      << "  jmp_buf buf; struct __llvm_jmpbuf_list_t *next;\n"
+      << "} *__llvm_jmpbuf_list;\n"
+
       << "\n\n/* Global Declarations */\n";
 
   // First output all the declarations for the program, because C requires
@@ -569,7 +687,7 @@ void CWriter::printModule(Module *M) {
     for (Module::giterator I = M->gbegin(), E = M->gend(); I != E; ++I) {
       if (I->hasExternalLinkage()) {
         Out << "extern ";
-        printType(Out, I->getType()->getElementType(), getValueName(I));
+        printType(Out, I->getType()->getElementType(), Mang->getValueName(I));
         Out << ";\n";
       }
     }
@@ -586,30 +704,34 @@ void CWriter::printModule(Module *M) {
       if ((I->hasInternalLinkage() || !MangledGlobals.count(I)) &&
           !I->getIntrinsicID()) {
         printFunctionSignature(I, true);
+        if (I->hasWeakLinkage()) Out << " __ATTRIBUTE_WEAK__";
         Out << ";\n";
       }
     }
   }
 
   // Print Malloc prototype if needed
-  if (needsMalloc){
+  if (needsMalloc) {
     Out << "\n/* Malloc to make sun happy */\n";
-    Out << "extern void * malloc(size_t);\n\n";
+    Out << "extern void * malloc();\n\n";
   }
 
-  // Output the global variable declerations
+  // Output the global variable declarations
   if (!M->gempty()) {
-    Out << "\n\n/* Global Variable Declerations */\n";
+    Out << "\n\n/* Global Variable Declarations */\n";
     for (Module::giterator I = M->gbegin(), E = M->gend(); I != E; ++I)
       if (!I->isExternal()) {
         Out << "extern ";
-        printType(Out, I->getType()->getElementType(), getValueName(I));
-      
+        printType(Out, I->getType()->getElementType(), Mang->getValueName(I));
+
+        if (I->hasLinkOnceLinkage())
+          Out << " __attribute__((common))";
+        else if (I->hasWeakLinkage())
+          Out << " __ATTRIBUTE_WEAK__";
         Out << ";\n";
       }
   }
 
-  
   // Output the global variable definitions and contents...
   if (!M->gempty()) {
     Out << "\n\n/* Global Variable Definitions and Initialization */\n";
@@ -617,22 +739,94 @@ void CWriter::printModule(Module *M) {
       if (!I->isExternal()) {
         if (I->hasInternalLinkage())
           Out << "static ";
-        printType(Out, I->getType()->getElementType(), getValueName(I));
-      
-        Out << " = " ;
-        writeOperand(I->getInitializer());
+        printType(Out, I->getType()->getElementType(), Mang->getValueName(I));
+        if (I->hasLinkOnceLinkage())
+          Out << " __attribute__((common))";
+        else if (I->hasWeakLinkage())
+          Out << " __ATTRIBUTE_WEAK__";
+
+        // 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
+        // case, the assembler will complain about the variable being both weak
+        // and common, so we disable this optimization.
+        if (!I->getInitializer()->isNullValue() ||
+            I->hasWeakLinkage()) {
+          Out << " = " ;
+          writeOperand(I->getInitializer());
+        }
         Out << ";\n";
       }
   }
 
+  // Output all floating point constants that cannot be printed accurately...
+  printFloatingPointConstants(*M);
+  
   // Output all of the functions...
+  emittedInvoke = false;
   if (!M->empty()) {
     Out << "\n\n/* Function Bodies */\n";
     for (Module::iterator I = M->begin(), E = M->end(); I != E; ++I)
       printFunction(I);
   }
+
+  // If the program included an invoke instruction, we need to output the
+  // support code for it here!
+  if (emittedInvoke) {
+    Out << "\n/* More support for the invoke instruction */\n"
+        << "struct __llvm_jmpbuf_list_t *__llvm_jmpbuf_list "
+        << "__attribute__((common)) = 0;\n";
+  }
+
+  // Done with global FP constants
+  FPConstantMap.clear();
 }
 
+/// Output all floating point constants that cannot be printed accurately...
+void CWriter::printFloatingPointConstants(Module &M) {
+  union {
+    double D;
+    unsigned long long U;
+  } DBLUnion;
+
+  union {
+    float F;
+    unsigned U;
+  } FLTUnion;
+
+  // Scan the module for floating point constants.  If any FP constant is used
+  // in the function, we want to redirect it here so that we do not depend on
+  // the precision of the printed form, unless the printed form preserves
+  // precision.
+  //
+  unsigned FPCounter = 0;
+  for (Module::iterator F = M.begin(), E = M.end(); F != E; ++F)
+    for (constant_iterator I = constant_begin(F), E = constant_end(F);
+         I != E; ++I)
+      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) {
+            DBLUnion.D = Val;
+            Out << "const ConstantDoubleTy FPConstant" << FPCounter++
+                << " = 0x" << std::hex << DBLUnion.U << std::dec
+                << "ULL;    /* " << Val << " */\n";
+          } else if (FPC->getType() == Type::FloatTy) {
+            FLTUnion.F = Val;
+            Out << "const ConstantFloatTy FPConstant" << FPCounter++
+                << " = 0x" << std::hex << FLTUnion.U << std::dec
+                << "U;    /* " << Val << " */\n";
+          } else
+            assert(0 && "Unknown float type!");
+        }
+  
+  Out << "\n";
+ }
+
 
 /// printSymbolTable - Run through symbol table looking for type names.  If a
 /// type name is found, emit it's declaration...
@@ -649,24 +843,28 @@ void CWriter::printSymbolTable(const SymbolTable &ST) {
   // 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_" + makeNameProper(I->first);
-      Out << Name << ";\n";
-      TypeNames.insert(std::make_pair(STy, Name));
-    }
+    if (const Type *STy = dyn_cast<StructType>(I->second))
+      // Only print out used types!
+      if (FUT->getTypes().count(STy)) {
+        std::string Name = "struct l_" + Mangler::makeNameProper(I->first);
+        Out << Name << ";\n";
+        TypeNames.insert(std::make_pair(STy, Name));
+      }
 
   Out << "\n";
 
   // Now we can print out typedefs...
   Out << "/* Typedefs */\n";
-  for (I = ST.type_begin(Type::TypeTy); I != End; ++I) {
-    const Type *Ty = cast<Type>(I->second);
-    std::string Name = "l_" + makeNameProper(I->first);
-    Out << "typedef ";
-    printType(Out, Ty, Name);
-    Out << ";\n";
-  }
-
+  for (I = ST.type_begin(Type::TypeTy); I != End; ++I)
+    // Only print out used types!
+    if (FUT->getTypes().count(cast<Type>(I->second))) {
+      const Type *Ty = cast<Type>(I->second);
+      std::string Name = "l_" + Mangler::makeNameProper(I->first);
+      Out << "typedef ";
+      printType(Out, Ty, Name);
+      Out << ";\n";
+    }
+  
   Out << "\n";
 
   // Keep track of which structures have been printed so far...
@@ -678,14 +876,16 @@ void CWriter::printSymbolTable(const SymbolTable &ST) {
   Out << "/* Structure contents */\n";
   for (I = ST.type_begin(Type::TypeTy); I != End; ++I)
     if (const StructType *STy = dyn_cast<StructType>(I->second))
-      printContainedStructs(STy, StructPrinted);
+      // Only print out used types!
+      if (FUT->getTypes().count(STy))
+        printContainedStructs(STy, StructPrinted);
 }
 
 // Push the struct onto the stack and recursively push all structs
 // this one depends on.
 void CWriter::printContainedStructs(const Type *Ty,
                                     std::set<const StructType*> &StructPrinted){
-  if (const StructType *STy = dyn_cast<StructType>(Ty)){
+  if (const StructType *STy = dyn_cast<StructType>(Ty)) {
     //Check to see if we have already printed this struct
     if (StructPrinted.count(STy) == 0) {
       // Print all contained types first...
@@ -714,33 +914,36 @@ void CWriter::printContainedStructs(const Type *Ty,
 
 
 void CWriter::printFunctionSignature(const Function *F, bool Prototype) {
-  // If the program provides it's own malloc prototype we don't need
+  // If the program provides its own malloc prototype we don't need
   // to include the general one.  
-  if (getValueName(F) == "malloc")
+  if (Mang->getValueName(F) == "malloc")
     needsMalloc = false;
-  if (F->hasInternalLinkage()) Out << "static ";  
+
+  if (F->hasInternalLinkage()) Out << "static ";
+  if (F->hasLinkOnceLinkage()) Out << "inline ";
+  
   // Loop over the arguments, printing them...
   const FunctionType *FT = cast<FunctionType>(F->getFunctionType());
   
-  std::stringstream FunctionInards; 
+  std::stringstream FunctionInnards; 
     
   // Print out the name...
-  FunctionInards << getValueName(F) << "(";
+  FunctionInnards << Mang->getValueName(F) << "(";
     
   if (!F->isExternal()) {
     if (!F->aempty()) {
       std::string ArgName;
       if (F->abegin()->hasName() || !Prototype)
-        ArgName = getValueName(F->abegin());
-      printType(FunctionInards, F->afront().getType(), ArgName);
+        ArgName = Mang->getValueName(F->abegin());
+      printType(FunctionInnards, F->afront().getType(), ArgName);
       for (Function::const_aiterator I = ++F->abegin(), E = F->aend();
            I != E; ++I) {
-        FunctionInards << ", ";
+        FunctionInnards << ", ";
         if (I->hasName() || !Prototype)
-          ArgName = getValueName(I);
+          ArgName = Mang->getValueName(I);
         else 
           ArgName = "";
-        printType(FunctionInards, I->getType(), ArgName);
+        printType(FunctionInnards, I->getType(), ArgName);
       }
     }
   } else {
@@ -748,8 +951,8 @@ void CWriter::printFunctionSignature(const Function *F, bool Prototype) {
     for (FunctionType::ParamTypes::const_iterator I = 
           FT->getParamTypes().begin(),
           E = FT->getParamTypes().end(); I != E; ++I) {
-      if (I != FT->getParamTypes().begin()) FunctionInards << ", ";
-      printType(FunctionInards, *I);
+      if (I != FT->getParamTypes().begin()) FunctionInnards << ", ";
+      printType(FunctionInnards, *I);
     }
   }
 
@@ -757,73 +960,60 @@ void CWriter::printFunctionSignature(const Function *F, bool Prototype) {
   // unless there are no known types, in which case, we just emit ().
   //
   if (FT->isVarArg() && !FT->getParamTypes().empty()) {
-    if (FT->getParamTypes().size()) FunctionInards << ", ";
-    FunctionInards << "...";  // Output varargs portion of signature!
+    if (FT->getParamTypes().size()) FunctionInnards << ", ";
+    FunctionInnards << "...";  // Output varargs portion of signature!
+  } else if (!FT->isVarArg() && FT->getParamTypes().empty()) {
+    FunctionInnards << "void"; // ret() -> ret(void) in C.
   }
-  FunctionInards << ")";
+  FunctionInnards << ")";
   // Print out the return type and the entire signature for that matter
-  printType(Out, F->getReturnType(), FunctionInards.str());
-  
+  printType(Out, F->getReturnType(), FunctionInnards.str());
 }
 
-
 void CWriter::printFunction(Function *F) {
   if (F->isExternal()) return;
 
-  Table->incorporateFunction(F);
-
   printFunctionSignature(F, false);
   Out << " {\n";
 
+  // Determine whether or not the function contains any invoke instructions.
+  bool HasInvoke = false;
+  for (Function::iterator I = F->begin(), E = F->end(); I != E; ++I)
+    if (isa<InvokeInst>(I->getTerminator())) {
+      HasInvoke = true;
+      break;
+    }
+
   // print local variable information for the function
   for (inst_iterator I = inst_begin(F), E = inst_end(F); I != E; ++I)
-    if ((*I)->getType() != Type::VoidTy && !isInlinableInst(**I)) {
+    if (const AllocaInst *AI = isDirectAlloca(*I)) {
       Out << "  ";
-      printType(Out, (*I)->getType(), getValueName(*I));
+      if (HasInvoke) Out << "VOLATILE_FOR_SETJMP ";
+      printType(Out, AI->getAllocatedType(), Mang->getValueName(AI));
+      Out << ";    /* Address exposed local */\n";
+    } else if ((*I)->getType() != Type::VoidTy && !isInlinableInst(**I)) {
+      Out << "  ";
+      if (HasInvoke) Out << "VOLATILE_FOR_SETJMP ";
+      printType(Out, (*I)->getType(), Mang->getValueName(*I));
       Out << ";\n";
-
+      
       if (isa<PHINode>(*I)) {  // Print out PHI node temporaries as well...
         Out << "  ";
-        printType(Out, (*I)->getType(), getValueName(*I)+"__PHI_TEMPORARY");
+        if (HasInvoke) Out << "VOLATILE_FOR_SETJMP ";
+        printType(Out, (*I)->getType(),
+                  Mang->getValueName(*I)+"__PHI_TEMPORARY");
         Out << ";\n";
       }
     }
 
   Out << "\n";
 
-  // Scan the function for floating point constants.  If any FP constant is used
-  // in the function, we want to redirect it here so that we do not depend on
-  // the precision of the printed form.
-  //
-  unsigned FPCounter = 0;
-  for (constant_iterator I = constant_begin(F), E = constant_end(F); I != E;++I)
-    if (const ConstantFP *FPC = dyn_cast<ConstantFP>(*I))
-      if (FPConstantMap.find(FPC) == FPConstantMap.end()) {
-        double Val = FPC->getValue();
-        
-        FPConstantMap[FPC] = FPCounter;  // Number the FP constants
-
-        if (FPC->getType() == Type::DoubleTy)
-          Out << "  const ConstantDoubleTy FloatConstant" << FPCounter++
-              << " = 0x" << std::hex << *(unsigned long long*)&Val << std::dec
-              << ";    /* " << Val << " */\n";
-        else if (FPC->getType() == Type::FloatTy) {
-          float fVal = Val;
-          Out << "  const ConstantFloatTy FloatConstant" << FPCounter++
-              << " = 0x" << std::hex << *(unsigned*)&fVal << std::dec
-              << ";    /* " << Val << " */\n";
-        } else
-          assert(0 && "Unknown float type!");
-      }
-
-  Out << "\n";
   // print the basic blocks
   for (Function::iterator BB = F->begin(), E = F->end(); BB != E; ++BB) {
     BasicBlock *Prev = BB->getPrev();
 
     // Don't print the label for the basic block if there are no uses, or if the
-    // only terminator use is the precessor basic block's terminator.  We have
+    // only terminator use is the predecessor basic block's terminator.  We have
     // to scan the use list because PHI nodes use basic blocks too but do not
     // require a label to be generated.
     //
@@ -832,16 +1022,17 @@ void CWriter::printFunction(Function *F) {
          UI != UE; ++UI)
       if (TerminatorInst *TI = dyn_cast<TerminatorInst>(*UI))
         if (TI != Prev->getTerminator() ||
-            isa<SwitchInst>(Prev->getTerminator())) {
+            isa<SwitchInst>(Prev->getTerminator()) ||
+            isa<InvokeInst>(Prev->getTerminator())) {
           NeedsLabel = true;
           break;        
         }
 
-    if (NeedsLabel) Out << getValueName(BB) << ":\n";
+    if (NeedsLabel) Out << Mang->getValueName(BB) << ":\n";
 
     // Output all of the instructions in the basic block...
     for (BasicBlock::iterator II = BB->begin(), E = --BB->end(); II != E; ++II){
-      if (!isInlinableInst(*II)) {
+      if (!isInlinableInst(*II) && !isDirectAlloca(II)) {
         if (II->getType() != Type::VoidTy)
           outputLValue(II);
         else
@@ -856,12 +1047,10 @@ void CWriter::printFunction(Function *F) {
   }
   
   Out << "}\n\n";
-  Table->purgeFunction();
-  FPConstantMap.clear();
 }
 
 // Specific Instruction type classes... note that all of the casts are
-// neccesary because we use the instruction classes as opaque types...
+// necessary because we use the instruction classes as opaque types...
 //
 void CWriter::visitReturnInst(ReturnInst &I) {
   // Don't output a void return if this is the last basic block in the function
@@ -897,8 +1086,47 @@ void CWriter::visitSwitchInst(SwitchInst &SI) {
   Out << "  }\n";
 }
 
+void CWriter::visitInvokeInst(InvokeInst &II) {
+  Out << "  {\n"
+      << "    struct __llvm_jmpbuf_list_t Entry;\n"
+      << "    Entry.next = __llvm_jmpbuf_list;\n"
+      << "    if (setjmp(Entry.buf)) {\n"
+      << "      __llvm_jmpbuf_list = Entry.next;\n";
+  printBranchToBlock(II.getParent(), II.getExceptionalDest(), 4);
+  Out << "    }\n"
+      << "    __llvm_jmpbuf_list = &Entry;\n"
+      << "    ";
+
+  if (II.getType() != Type::VoidTy) outputLValue(&II);
+  visitCallSite(&II);
+  Out << ";\n"
+      << "    __llvm_jmpbuf_list = Entry.next;\n"
+      << "  }\n";
+  printBranchToBlock(II.getParent(), II.getNormalDest(), 0);
+  emittedInvoke = true;
+}
 
-static bool isGotoCodeNeccessary(BasicBlock *From, BasicBlock *To) {
+
+void CWriter::visitUnwindInst(UnwindInst &I) {
+  // The unwind instructions causes a control flow transfer out of the current
+  // function, unwinding the stack until a caller who used the invoke
+  // instruction is found.  In this context, we code generated the invoke
+  // instruction to add an entry to the top of the jmpbuf_list.  Thus, here we
+  // just have to longjmp to the specified handler.
+  Out << "  if (__llvm_jmpbuf_list == 0) {  /* unwind */\n"
+      << "#ifdef _LP64\n"
+      << "    extern signed long long write();\n"
+      << "#else\n"
+      << "    extern write();\n"
+      << "#endif\n"
+      << "    ((void (*)(int, void*, unsigned))write)(2,\n"
+      << "           \"throw found with no handler!\\n\", 31); abort();\n"
+      << "  }\n"
+      << "  longjmp(__llvm_jmpbuf_list->buf, 1);\n";
+  emittedInvoke = true;
+}
+
+bool isGotoCodeNecessary(BasicBlock *From, BasicBlock *To) {
   // If PHI nodes need copies, we need the copy code...
   if (isa<PHINode>(To->front()) ||
       From->getNext() != To)      // Not directly successor, need goto
@@ -909,41 +1137,43 @@ static bool isGotoCodeNeccessary(BasicBlock *From, BasicBlock *To) {
 }
 
 void CWriter::printBranchToBlock(BasicBlock *CurBB, BasicBlock *Succ,
-                                           unsigned Indent) {
+                                 unsigned Indent) {
   for (BasicBlock::iterator I = Succ->begin();
        PHINode *PN = dyn_cast<PHINode>(I); ++I) {
     //  now we have to do the printing
     Out << std::string(Indent, ' ');
-    Out << "  " << getValueName(I) << "__PHI_TEMPORARY = ";
+    Out << "  " << Mang->getValueName(I) << "__PHI_TEMPORARY = ";
     writeOperand(PN->getIncomingValue(PN->getBasicBlockIndex(CurBB)));
     Out << ";   /* for PHI node */\n";
   }
 
-  if (CurBB->getNext() != Succ) {
+  if (CurBB->getNext() != Succ ||
+      isa<InvokeInst>(CurBB->getTerminator()) ||
+      isa<SwitchInst>(CurBB->getTerminator())) {
     Out << std::string(Indent, ' ') << "  goto ";
     writeOperand(Succ);
     Out << ";\n";
   }
 }
 
-// Brach instruction printing - Avoid printing out a brach to a basic block that
-// immediately succeeds the current one.
+// Branch instruction printing - Avoid printing out a branch to a basic block
+// that immediately succeeds the current one.
 //
 void CWriter::visitBranchInst(BranchInst &I) {
   if (I.isConditional()) {
-    if (isGotoCodeNeccessary(I.getParent(), I.getSuccessor(0))) {
+    if (isGotoCodeNecessary(I.getParent(), I.getSuccessor(0))) {
       Out << "  if (";
       writeOperand(I.getCondition());
       Out << ") {\n";
       
       printBranchToBlock(I.getParent(), I.getSuccessor(0), 2);
       
-      if (isGotoCodeNeccessary(I.getParent(), I.getSuccessor(1))) {
+      if (isGotoCodeNecessary(I.getParent(), I.getSuccessor(1))) {
         Out << "  } else {\n";
         printBranchToBlock(I.getParent(), I.getSuccessor(1), 2);
       }
     } else {
-      // First goto not neccesary, assume second one is...
+      // First goto not necessary, assume second one is...
       Out << "  if (!";
       writeOperand(I.getCondition());
       Out << ") {\n";
@@ -970,6 +1200,17 @@ void CWriter::visitPHINode(PHINode &I) {
 void CWriter::visitBinaryOperator(Instruction &I) {
   // binary instructions, shift instructions, setCond instructions.
   assert(!isa<PointerType>(I.getType()));
+
+  // We must cast the results of binary operations which might be promoted.
+  bool needsCast = false;
+  if ((I.getType() == Type::UByteTy) || (I.getType() == Type::SByteTy)
+      || (I.getType() == Type::UShortTy) || (I.getType() == Type::ShortTy)
+      || (I.getType() == Type::FloatTy)) {
+    needsCast = true;
+    Out << "((";
+    printType(Out, I.getType());
+    Out << ")(";
+  }
       
   writeOperand(I.getOperand(0));
 
@@ -994,6 +1235,10 @@ void CWriter::visitBinaryOperator(Instruction &I) {
   }
 
   writeOperand(I.getOperand(1));
+
+  if (needsCast) {
+    Out << "))";
+  }
 }
 
 void CWriter::visitCastInst(CastInst &I) {
@@ -1004,7 +1249,7 @@ void CWriter::visitCastInst(CastInst &I) {
     return;
   }
   Out << "(";
-  printType(Out, I.getType(), "", /*ignoreName*/false, /*namedContext*/false);
+  printType(Out, I.getType());
   Out << ")";
   if (isa<PointerType>(I.getType())&&I.getOperand(0)->getType()->isIntegral() ||
       isa<PointerType>(I.getOperand(0)->getType())&&I.getType()->isIntegral()) {
@@ -1018,58 +1263,69 @@ void CWriter::visitCastInst(CastInst &I) {
 void CWriter::visitCallInst(CallInst &I) {
   // Handle intrinsic function calls first...
   if (Function *F = I.getCalledFunction())
-    if (LLVMIntrinsic::ID ID = (LLVMIntrinsic::ID)F->getIntrinsicID()) {
+    if (Intrinsic::ID ID = (Intrinsic::ID)F->getIntrinsicID()) {
       switch (ID) {
       default:  assert(0 && "Unknown LLVM intrinsic!");
-      case LLVMIntrinsic::va_start: 
-        Out << "va_start((va_list)*";
-        writeOperand(I.getOperand(1));
-        Out << ", ";
+      case Intrinsic::va_start: 
+        Out << "0; ";
+        
+        Out << "va_start(*(va_list*)&" << Mang->getValueName(&I) << ", ";
         // Output the last argument to the enclosing function...
+        if (I.getParent()->getParent()->aempty()) {
+          std::cerr << "The C backend does not currently support zero "
+                    << "argument varargs functions, such as '"
+                    << I.getParent()->getParent()->getName() << "'!\n";
+          abort();
+        }
         writeOperand(&I.getParent()->getParent()->aback());
         Out << ")";
         return;
-      case LLVMIntrinsic::va_end:
-        Out << "va_end((va_list)*";
+      case Intrinsic::va_end:
+        Out << "va_end(*(va_list*)&";
         writeOperand(I.getOperand(1));
         Out << ")";
         return;
-      case LLVMIntrinsic::va_copy:
-        Out << "va_copy((va_list)*";
+      case Intrinsic::va_copy:
+        Out << "0;";
+        Out << "va_copy(*(va_list*)&" << Mang->getValueName(&I) << ", ";
+        Out << "*(va_list*)&";
         writeOperand(I.getOperand(1));
-        Out << ", (va_list)";
-        writeOperand(I.getOperand(2));
         Out << ")";
         return;
-        
-      case LLVMIntrinsic::setjmp:
-        Out << "setjmp((jmp_buf)";
-        writeOperand(I.getOperand(1));
-        Out << ")";
+      case Intrinsic::setjmp:
+      case Intrinsic::sigsetjmp:
+        // This intrinsic should never exist in the program, but until we get
+        // setjmp/longjmp transformations going on, we should codegen it to
+        // something reasonable.  This will allow code that never calls longjmp
+        // to work.
+        Out << "0";
         return;
-      case LLVMIntrinsic::longjmp:
-        Out << "longjmp((jmp_buf)";
-        writeOperand(I.getOperand(1));
-        Out << ", ";
-        writeOperand(I.getOperand(2));
-        Out << ")";
+      case Intrinsic::longjmp:
+      case Intrinsic::siglongjmp:
+        // Longjmp is not implemented, and never will be.  It would cause an
+        // exception throw.
+        Out << "abort()";
         return;
       }
     }
+  visitCallSite(&I);
+}
 
-  const PointerType  *PTy   = cast<PointerType>(I.getCalledValue()->getType());
+void CWriter::visitCallSite(CallSite CS) {
+  const PointerType  *PTy   = cast<PointerType>(CS.getCalledValue()->getType());
   const FunctionType *FTy   = cast<FunctionType>(PTy->getElementType());
   const Type         *RetTy = FTy->getReturnType();
   
-  writeOperand(I.getOperand(0));
+  writeOperand(CS.getCalledValue());
   Out << "(";
 
-  if (I.getNumOperands() > 1) {
-    writeOperand(I.getOperand(1));
+  if (CS.arg_begin() != CS.arg_end()) {
+    CallSite::arg_iterator AI = CS.arg_begin(), AE = CS.arg_end();
+    writeOperand(*AI);
 
-    for (unsigned op = 2, Eop = I.getNumOperands(); op != Eop; ++op) {
+    for (++AI; AI != AE; ++AI) {
       Out << ", ";
-      writeOperand(I.getOperand(op));
+      writeOperand(*AI);
     }
   }
   Out << ")";
@@ -1103,13 +1359,13 @@ void CWriter::visitAllocaInst(AllocaInst &I) {
 }
 
 void CWriter::visitFreeInst(FreeInst &I) {
-  Out << "free(";
+  Out << "free((char*)";
   writeOperand(I.getOperand(0));
   Out << ")";
 }
 
-void CWriter::printIndexingExpression(Value *Ptr, User::op_iterator I,
-                                      User::op_iterator E) {
+void CWriter::printIndexingExpression(Value *Ptr, gep_type_iterator I,
+                                      gep_type_iterator E) {
   bool HasImplicitAddress = false;
   // If accessing a global value with no indexing, avoid *(&GV) syndrome
   if (GlobalValue *V = dyn_cast<GlobalValue>(Ptr)) {
@@ -1117,6 +1373,8 @@ void CWriter::printIndexingExpression(Value *Ptr, User::op_iterator I,
   } else if (ConstantPointerRef *CPR = dyn_cast<ConstantPointerRef>(Ptr)) {
     HasImplicitAddress = true;
     Ptr = CPR->getValue();         // Get to the global...
+  } else if (isDirectAlloca(Ptr)) {
+    HasImplicitAddress = true;
   }
 
   if (I == E) {
@@ -1127,7 +1385,7 @@ void CWriter::printIndexingExpression(Value *Ptr, User::op_iterator I,
     return;
   }
 
-  const Constant *CI = dyn_cast<Constant>(I);
+  const Constant *CI = dyn_cast<Constant>(I.getOperand());
   if (HasImplicitAddress && (!CI || !CI->isNullValue()))
     Out << "(&";
 
@@ -1143,22 +1401,24 @@ void CWriter::printIndexingExpression(Value *Ptr, User::op_iterator I,
 
   if (HasImplicitAddress) {
     ++I;
-  } else if (CI && CI->isNullValue() && I+1 != E) {
+  } else if (CI && CI->isNullValue()) {
+    gep_type_iterator TmpI = I; ++TmpI;
+
     // Print out the -> operator if possible...
-    if ((*(I+1))->getType() == Type::UByteTy) {
+    if (TmpI != E && isa<StructType>(*TmpI)) {
       Out << (HasImplicitAddress ? "." : "->");
-      Out << "field" << cast<ConstantUInt>(*(I+1))->getValue();
-      I += 2;
-    } 
+      Out << "field" << cast<ConstantUInt>(TmpI.getOperand())->getValue();
+      I = ++TmpI;
+    }
   }
 
   for (; I != E; ++I)
-    if ((*I)->getType() == Type::LongTy) {
+    if (isa<StructType>(*I)) {
+      Out << ".field" << cast<ConstantUInt>(I.getOperand())->getValue();
+    } else {
       Out << "[";
-      writeOperand(*I);
+      writeOperand(I.getOperand());
       Out << "]";
-    } else {
-      Out << ".field" << cast<ConstantUInt>(*I)->getValue();
     }
 }
 
@@ -1176,20 +1436,32 @@ void CWriter::visitStoreInst(StoreInst &I) {
 
 void CWriter::visitGetElementPtrInst(GetElementPtrInst &I) {
   Out << "&";
-  printIndexingExpression(I.getPointerOperand(), I.idx_begin(), I.idx_end());
+  printIndexingExpression(I.getPointerOperand(), gep_type_begin(I),
+                          gep_type_end(I));
 }
 
-void CWriter::visitVarArgInst(VarArgInst &I) {
-  Out << "va_arg((va_list)*";
-  writeOperand(I.getOperand(0));
-  Out << ", ";
-  printType(Out, I.getType(), "", /*ignoreName*/false, /*namedContext*/false);
+void CWriter::visitVANextInst(VANextInst &I) {
+  Out << Mang->getValueName(I.getOperand(0));
+  Out << ";  va_arg(*(va_list*)&" << Mang->getValueName(&I) << ", ";
+  printType(Out, I.getArgType());
   Out << ")";  
 }
 
+void CWriter::visitVAArgInst(VAArgInst &I) {
+  Out << "0;\n";
+  Out << "{ va_list Tmp; va_copy(Tmp, *(va_list*)&";
+  writeOperand(I.getOperand(0));
+  Out << ");\n  " << Mang->getValueName(&I) << " = va_arg(Tmp, ";
+  printType(Out, I.getType());
+  Out << ");\n  va_end(Tmp); }";
+}
+
+}
 
 //===----------------------------------------------------------------------===//
 //                       External Interface declaration
 //===----------------------------------------------------------------------===//
 
 Pass *createWriteToCPass(std::ostream &o) { return new CWriter(o); }
+
+} // End llvm namespace