Turn off "attribute weak" to pacify Mac OS X's system compiler, which prints a
[oota-llvm.git] / lib / Target / CBackend / Writer.cpp
index 921aa3488d9f646cb1211f97f2fe90689399ec7a..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/Intrinsics.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/CallSite.h"
 #include "llvm/Support/Mangler.h"
 #include "Support/StringExtras.h"
 #include "Support/STLExtras.h"
+#include "Config/config.h"
 #include <algorithm>
 #include <sstream>
 
+namespace llvm {
+
 namespace {
   class CWriter : public Pass, public InstVisitor<CWriter> {
     std::ostream &Out; 
     Mangler *Mang;
     const Module *TheModule;
+    FindUsedTypes *FUT;
+
     std::map<const Type *, std::string> TypeNames;
     std::set<const Value*> MangledGlobals;
     bool needsMalloc, emittedInvoke;
@@ -44,6 +57,7 @@ namespace {
     virtual bool run(Module &M) {
       // Initialize
       TheModule = &M;
+      FUT = &getAnalysis<FindUsedTypes>();
 
       // Ensure that all structure types have names...
       bool Changed = nameAllUsedStructureTypes(M);
@@ -61,7 +75,7 @@ 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);
@@ -69,6 +83,7 @@ namespace {
   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 printFunctionSignature(const Function *F, bool Prototype);
@@ -86,9 +101,9 @@ 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) || isa<VarArgInst>(I))
+          isa<LoadInst>(I) || isa<VAArgInst>(I) || isa<VANextInst>(I))
         // Don't inline a load across a store or other bad things!
         return false;
 
@@ -105,7 +120,7 @@ namespace {
       if (!AI) return false;
       if (AI->isArrayAllocation())
         return 0;   // FIXME: we can also inline fixed size array allocas!
-      if (AI->getParent() != &AI->getParent()->getParent()->getEntryNode())
+      if (AI->getParent() != &AI->getParent()->getParent()->getEntryBlock())
         return 0;
       return AI;
     }
@@ -133,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;
@@ -145,22 +161,16 @@ namespace {
     }
     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);
   };
-}
-
-// 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;
@@ -227,12 +237,8 @@ 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);
   }
@@ -327,26 +333,39 @@ void CWriter::printConstantArray(ConstantArray *CPA) {
   }
 }
 
-/// FPCSafeToPrint - 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.) This is adapted from similar code in
-/// lib/VMCore/AsmWriter.cpp:WriteConstantInt().
-static bool FPCSafeToPrint (const ConstantFP *CFP) {
+// 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());
-  // Check to make sure that the stringized number is not some string like
-  // "Inf" or NaN, that atof will accept, but the lexer will not.  Check that
-  // the string matches the "[-+]?[0-9]" regex.
+
+  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 atof(StrVal.c_str()) == CFP->getValue();
   return false;
+#endif
 }
 
 // printConstant - The LLVM Constant to C Constant converter.
@@ -363,8 +382,8 @@ 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:
@@ -378,6 +397,8 @@ void CWriter::printConstant(Constant *CPV) {
     case Instruction::SetLE:
     case Instruction::SetGT:
     case Instruction::SetGE:
+    case Instruction::Shl:
+    case Instruction::Shr:
       Out << "(";
       printConstant(CE->getOperand(0));
       switch (CE->getOpcode()) {
@@ -392,6 +413,8 @@ void CWriter::printConstant(Constant *CPV) {
       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));
@@ -437,13 +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 {
-      if (FPCSafeToPrint (FPC)) {
-        Out << ftostr (FPC->getValue ());
-      } else {
-        Out << FPC->getValue(); // Who knows? Give it our best shot...
-      }
+#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;
   }
@@ -516,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.
@@ -559,9 +585,53 @@ static void generateCompilerSpecificCode(std::ostream& Out) {
   // 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";
+      << "#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.
@@ -584,10 +654,11 @@ void CWriter::printModule(Module *M) {
 
   // get declaration for alloca
   Out << "/* Provide Declarations */\n";
-  Out << "#include <stdarg.h>\n";
-  Out << "#include <setjmp.h>\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"
@@ -633,6 +704,7 @@ void CWriter::printModule(Module *M) {
       if ((I->hasInternalLinkage() || !MangledGlobals.count(I)) &&
           !I->getIntrinsicID()) {
         printFunctionSignature(I, true);
+        if (I->hasWeakLinkage()) Out << " __ATTRIBUTE_WEAK__";
         Out << ";\n";
       }
     }
@@ -651,7 +723,11 @@ void CWriter::printModule(Module *M) {
       if (!I->isExternal()) {
         Out << "extern ";
         printType(Out, I->getType()->getElementType(), Mang->getValueName(I));
-      
+
+        if (I->hasLinkOnceLinkage())
+          Out << " __attribute__((common))";
+        else if (I->hasWeakLinkage())
+          Out << " __ATTRIBUTE_WEAK__";
         Out << ";\n";
       }
   }
@@ -666,7 +742,16 @@ void CWriter::printModule(Module *M) {
         printType(Out, I->getType()->getElementType(), Mang->getValueName(I));
         if (I->hasLinkOnceLinkage())
           Out << " __attribute__((common))";
-        if (!I->getInitializer()->isNullValue()) {
+        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());
         }
@@ -674,6 +759,9 @@ void CWriter::printModule(Module *M) {
       }
   }
 
+  // Output all floating point constants that cannot be printed accurately...
+  printFloatingPointConstants(*M);
+  
   // Output all of the functions...
   emittedInvoke = false;
   if (!M->empty()) {
@@ -689,8 +777,56 @@ void CWriter::printModule(Module *M) {
         << "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...
@@ -707,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_" + Mangler::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_" + Mangler::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...
@@ -736,7 +876,9 @@ 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
@@ -820,6 +962,8 @@ void CWriter::printFunctionSignature(const Function *F, bool Prototype) {
   if (FT->isVarArg() && !FT->getParamTypes().empty()) {
     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.
   }
   FunctionInnards << ")";
   // Print out the return type and the entire signature for that matter
@@ -832,61 +976,44 @@ void CWriter::printFunction(Function *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 (const AllocaInst *AI = isDirectAlloca(*I)) {
       Out << "  ";
+      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(), Mang->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, unless the printed form preserves
-  // precision.
-  //
-  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 ((!FPCSafeToPrint(FPC)) // Do not put in FPConstantMap if safe.
-         && (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.
     //
@@ -920,7 +1047,6 @@ void CWriter::printFunction(Function *F) {
   }
   
   Out << "}\n\n";
-  FPConstantMap.clear();
 }
 
 // Specific Instruction type classes... note that all of the casts are
@@ -987,14 +1113,20 @@ void CWriter::visitUnwindInst(UnwindInst &I) {
   // 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) {  /* llvm.unwind */\n"
-      << "    printf(\"throw found with no handler!\\n\"); abort();\n"
+  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;
 }
 
-static bool isGotoCodeNeccessary(BasicBlock *From, BasicBlock *To) {
+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
@@ -1015,26 +1147,28 @@ void CWriter::printBranchToBlock(BasicBlock *CurBB, BasicBlock *Succ,
     Out << ";   /* for PHI node */\n";
   }
 
-  if (CurBB->getNext() != Succ || isa<InvokeInst>(CurBB->getTerminator())) {
+  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);
       }
@@ -1074,7 +1208,7 @@ void CWriter::visitBinaryOperator(Instruction &I) {
       || (I.getType() == Type::FloatTy)) {
     needsCast = true;
     Out << "((";
-    printType(Out, I.getType(), "", false, false);
+    printType(Out, I.getType());
     Out << ")(";
   }
       
@@ -1115,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()) {
@@ -1129,40 +1263,45 @@ 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:
-      case LLVMIntrinsic::sigsetjmp:
-        // This instrinsic should never exist in the program, but until we get
+      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:
-      case LLVMIntrinsic::siglongjmp:
+      case Intrinsic::longjmp:
+      case Intrinsic::siglongjmp:
         // Longjmp is not implemented, and never will be.  It would cause an
         // exception throw.
         Out << "abort()";
@@ -1225,8 +1364,8 @@ void CWriter::visitFreeInst(FreeInst &I) {
   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)) {
@@ -1246,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 << "(&";
 
@@ -1262,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();
     }
 }
 
@@ -1295,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