LLVM API Documentation

Main Page | Namespace List | Class Hierarchy | Alphabetical List | Class List | Directories | File List | Namespace Members | Class Members | File Members | Related Pages

Target/CBackend/Writer.cpp

Go to the documentation of this file.
00001 //===-- Writer.cpp - Library for converting LLVM code to C ----------------===//
00002 // 
00003 //                     The LLVM Compiler Infrastructure
00004 //
00005 // This file was developed by the LLVM research group and is distributed under
00006 // the University of Illinois Open Source License. See LICENSE.TXT for details.
00007 // 
00008 //===----------------------------------------------------------------------===//
00009 //
00010 // This library converts LLVM code to C code, compilable by GCC and other C
00011 // compilers.
00012 //
00013 //===----------------------------------------------------------------------===//
00014 
00015 #include "CTargetMachine.h"
00016 #include "llvm/Constants.h"
00017 #include "llvm/DerivedTypes.h"
00018 #include "llvm/Module.h"
00019 #include "llvm/Instructions.h"
00020 #include "llvm/Pass.h"
00021 #include "llvm/PassManager.h"
00022 #include "llvm/SymbolTable.h"
00023 #include "llvm/Intrinsics.h"
00024 #include "llvm/Analysis/ConstantsScanner.h"
00025 #include "llvm/Analysis/FindUsedTypes.h"
00026 #include "llvm/Analysis/LoopInfo.h"
00027 #include "llvm/CodeGen/IntrinsicLowering.h"
00028 #include "llvm/Transforms/Scalar.h"
00029 #include "llvm/Target/TargetMachineRegistry.h"
00030 #include "llvm/Support/CallSite.h"
00031 #include "llvm/Support/CFG.h"
00032 #include "llvm/Support/GetElementPtrTypeIterator.h"
00033 #include "llvm/Support/InstVisitor.h"
00034 #include "llvm/Support/Mangler.h"
00035 #include "llvm/ADT/StringExtras.h"
00036 #include "llvm/Support/MathExtras.h"
00037 #include "llvm/Config/config.h"
00038 #include <algorithm>
00039 #include <iostream>
00040 #include <sstream>
00041 using namespace llvm;
00042 
00043 namespace {
00044   // Register the target.
00045   RegisterTarget<CTargetMachine> X("c", "  C backend");
00046 
00047   /// NameAllUsedStructs - This pass inserts names for any unnamed structure
00048   /// types that are used by the program.
00049   ///
00050   class CBackendNameAllUsedStructs : public ModulePass {
00051     void getAnalysisUsage(AnalysisUsage &AU) const {
00052       AU.addRequired<FindUsedTypes>();
00053     }
00054 
00055     virtual const char *getPassName() const {
00056       return "C backend type canonicalizer";
00057     }
00058 
00059     virtual bool runOnModule(Module &M);
00060   };
00061   
00062   /// CWriter - This class is the main chunk of code that converts an LLVM
00063   /// module to a C translation unit.
00064   class CWriter : public FunctionPass, public InstVisitor<CWriter> {
00065     std::ostream &Out; 
00066     IntrinsicLowering &IL;
00067     Mangler *Mang;
00068     LoopInfo *LI;
00069     const Module *TheModule;
00070     std::map<const Type *, std::string> TypeNames;
00071 
00072     std::map<const ConstantFP *, unsigned> FPConstantMap;
00073   public:
00074     CWriter(std::ostream &o, IntrinsicLowering &il) : Out(o), IL(il) {}
00075 
00076     virtual const char *getPassName() const { return "C backend"; }
00077 
00078     void getAnalysisUsage(AnalysisUsage &AU) const {
00079       AU.addRequired<LoopInfo>();
00080       AU.setPreservesAll();
00081     }
00082 
00083     virtual bool doInitialization(Module &M);
00084 
00085     bool runOnFunction(Function &F) {
00086       LI = &getAnalysis<LoopInfo>();
00087 
00088       // Get rid of intrinsics we can't handle.
00089       lowerIntrinsics(F);
00090 
00091       // Output all floating point constants that cannot be printed accurately.
00092       printFloatingPointConstants(F);
00093 
00094       // Ensure that no local symbols conflict with global symbols.
00095       F.renameLocalSymbols();
00096 
00097       printFunction(F);
00098       FPConstantMap.clear();
00099       return false;
00100     }
00101 
00102     virtual bool doFinalization(Module &M) {
00103       // Free memory...
00104       delete Mang;
00105       TypeNames.clear();
00106       return false;
00107     }
00108 
00109     std::ostream &printType(std::ostream &Out, const Type *Ty,
00110                             const std::string &VariableName = "",
00111                             bool IgnoreName = false);
00112 
00113     void writeOperand(Value *Operand);
00114     void writeOperandInternal(Value *Operand);
00115 
00116   private :
00117     void lowerIntrinsics(Function &F);
00118 
00119     bool nameAllUsedStructureTypes(Module &M);
00120     void printModule(Module *M);
00121     void printModuleTypes(const SymbolTable &ST);
00122     void printContainedStructs(const Type *Ty, std::set<const StructType *> &);
00123     void printFloatingPointConstants(Function &F);
00124     void printFunctionSignature(const Function *F, bool Prototype);
00125 
00126     void printFunction(Function &);
00127     void printBasicBlock(BasicBlock *BB);
00128     void printLoop(Loop *L);
00129 
00130     void printConstant(Constant *CPV);
00131     void printConstantArray(ConstantArray *CPA);
00132 
00133     // isInlinableInst - Attempt to inline instructions into their uses to build
00134     // trees as much as possible.  To do this, we have to consistently decide
00135     // what is acceptable to inline, so that variable declarations don't get
00136     // printed and an extra copy of the expr is not emitted.
00137     //
00138     static bool isInlinableInst(const Instruction &I) {
00139       // Always inline setcc instructions, even if they are shared by multiple
00140       // expressions.  GCC generates horrible code if we don't.
00141       if (isa<SetCondInst>(I)) return true;
00142 
00143       // Must be an expression, must be used exactly once.  If it is dead, we
00144       // emit it inline where it would go.
00145       if (I.getType() == Type::VoidTy || !I.hasOneUse() ||
00146           isa<TerminatorInst>(I) || isa<CallInst>(I) || isa<PHINode>(I) || 
00147           isa<LoadInst>(I) || isa<VAArgInst>(I) || isa<VANextInst>(I))
00148         // Don't inline a load across a store or other bad things!
00149         return false;
00150 
00151       // Only inline instruction it it's use is in the same BB as the inst.
00152       return I.getParent() == cast<Instruction>(I.use_back())->getParent();
00153     }
00154 
00155     // isDirectAlloca - Define fixed sized allocas in the entry block as direct
00156     // variables which are accessed with the & operator.  This causes GCC to
00157     // generate significantly better code than to emit alloca calls directly.
00158     //
00159     static const AllocaInst *isDirectAlloca(const Value *V) {
00160       const AllocaInst *AI = dyn_cast<AllocaInst>(V);
00161       if (!AI) return false;
00162       if (AI->isArrayAllocation())
00163         return 0;   // FIXME: we can also inline fixed size array allocas!
00164       if (AI->getParent() != &AI->getParent()->getParent()->getEntryBlock())
00165         return 0;
00166       return AI;
00167     }
00168 
00169     // Instruction visitation functions
00170     friend class InstVisitor<CWriter>;
00171 
00172     void visitReturnInst(ReturnInst &I);
00173     void visitBranchInst(BranchInst &I);
00174     void visitSwitchInst(SwitchInst &I);
00175     void visitInvokeInst(InvokeInst &I) {
00176       assert(0 && "Lowerinvoke pass didn't work!");
00177     }
00178 
00179     void visitUnwindInst(UnwindInst &I) {
00180       assert(0 && "Lowerinvoke pass didn't work!");
00181     }
00182     void visitUnreachableInst(UnreachableInst &I);
00183 
00184     void visitPHINode(PHINode &I);
00185     void visitBinaryOperator(Instruction &I);
00186 
00187     void visitCastInst (CastInst &I);
00188     void visitSelectInst(SelectInst &I);
00189     void visitCallInst (CallInst &I);
00190     void visitShiftInst(ShiftInst &I) { visitBinaryOperator(I); }
00191 
00192     void visitMallocInst(MallocInst &I);
00193     void visitAllocaInst(AllocaInst &I);
00194     void visitFreeInst  (FreeInst   &I);
00195     void visitLoadInst  (LoadInst   &I);
00196     void visitStoreInst (StoreInst  &I);
00197     void visitGetElementPtrInst(GetElementPtrInst &I);
00198     void visitVANextInst(VANextInst &I);
00199     void visitVAArgInst (VAArgInst &I);
00200 
00201     void visitInstruction(Instruction &I) {
00202       std::cerr << "C Writer does not know about " << I;
00203       abort();
00204     }
00205 
00206     void outputLValue(Instruction *I) {
00207       Out << "  " << Mang->getValueName(I) << " = ";
00208     }
00209 
00210     bool isGotoCodeNecessary(BasicBlock *From, BasicBlock *To);
00211     void printPHICopiesForSuccessor(BasicBlock *CurBlock,
00212                                     BasicBlock *Successor, unsigned Indent);
00213     void printBranchToBlock(BasicBlock *CurBlock, BasicBlock *SuccBlock,
00214                             unsigned Indent);
00215     void printIndexingExpression(Value *Ptr, gep_type_iterator I,
00216                                  gep_type_iterator E);
00217   };
00218 }
00219 
00220 /// This method inserts names for any unnamed structure types that are used by
00221 /// the program, and removes names from structure types that are not used by the
00222 /// program.
00223 ///
00224 bool CBackendNameAllUsedStructs::runOnModule(Module &M) {
00225   // Get a set of types that are used by the program...
00226   std::set<const Type *> UT = getAnalysis<FindUsedTypes>().getTypes();
00227   
00228   // Loop over the module symbol table, removing types from UT that are
00229   // already named, and removing names for structure types that are not used.
00230   //
00231   SymbolTable &MST = M.getSymbolTable();
00232   for (SymbolTable::type_iterator TI = MST.type_begin(), TE = MST.type_end();
00233        TI != TE; ) {
00234     SymbolTable::type_iterator I = TI++;
00235     if (const StructType *STy = dyn_cast<StructType>(I->second)) {
00236       // If this is not used, remove it from the symbol table.
00237       std::set<const Type *>::iterator UTI = UT.find(STy);
00238       if (UTI == UT.end())
00239         MST.remove(I);
00240       else
00241         UT.erase(UTI);
00242     }
00243   }
00244 
00245   // UT now contains types that are not named.  Loop over it, naming
00246   // structure types.
00247   //
00248   bool Changed = false;
00249   unsigned RenameCounter = 0;
00250   for (std::set<const Type *>::const_iterator I = UT.begin(), E = UT.end();
00251        I != E; ++I)
00252     if (const StructType *ST = dyn_cast<StructType>(*I)) {
00253       while (M.addTypeName("unnamed"+utostr(RenameCounter), ST))
00254         ++RenameCounter;
00255       Changed = true;
00256     }
00257   return Changed;
00258 }
00259 
00260 
00261 // Pass the Type* and the variable name and this prints out the variable
00262 // declaration.
00263 //
00264 std::ostream &CWriter::printType(std::ostream &Out, const Type *Ty,
00265                                  const std::string &NameSoFar,
00266                                  bool IgnoreName) {
00267   if (Ty->isPrimitiveType())
00268     switch (Ty->getTypeID()) {
00269     case Type::VoidTyID:   return Out << "void "               << NameSoFar;
00270     case Type::BoolTyID:   return Out << "bool "               << NameSoFar;
00271     case Type::UByteTyID:  return Out << "unsigned char "      << NameSoFar;
00272     case Type::SByteTyID:  return Out << "signed char "        << NameSoFar;
00273     case Type::UShortTyID: return Out << "unsigned short "     << NameSoFar;
00274     case Type::ShortTyID:  return Out << "short "              << NameSoFar;
00275     case Type::UIntTyID:   return Out << "unsigned "           << NameSoFar;
00276     case Type::IntTyID:    return Out << "int "                << NameSoFar;
00277     case Type::ULongTyID:  return Out << "unsigned long long " << NameSoFar;
00278     case Type::LongTyID:   return Out << "signed long long "   << NameSoFar;
00279     case Type::FloatTyID:  return Out << "float "              << NameSoFar;
00280     case Type::DoubleTyID: return Out << "double "             << NameSoFar;
00281     default :
00282       std::cerr << "Unknown primitive type: " << *Ty << "\n";
00283       abort();
00284     }
00285   
00286   // Check to see if the type is named.
00287   if (!IgnoreName || isa<OpaqueType>(Ty)) {
00288     std::map<const Type *, std::string>::iterator I = TypeNames.find(Ty);
00289     if (I != TypeNames.end()) return Out << I->second << " " << NameSoFar;
00290   }
00291 
00292   switch (Ty->getTypeID()) {
00293   case Type::FunctionTyID: {
00294     const FunctionType *MTy = cast<FunctionType>(Ty);
00295     std::stringstream FunctionInnards; 
00296     FunctionInnards << " (" << NameSoFar << ") (";
00297     for (FunctionType::param_iterator I = MTy->param_begin(),
00298            E = MTy->param_end(); I != E; ++I) {
00299       if (I != MTy->param_begin())
00300         FunctionInnards << ", ";
00301       printType(FunctionInnards, *I, "");
00302     }
00303     if (MTy->isVarArg()) {
00304       if (MTy->getNumParams()) 
00305         FunctionInnards << ", ...";
00306     } else if (!MTy->getNumParams()) {
00307       FunctionInnards << "void";
00308     }
00309     FunctionInnards << ")";
00310     std::string tstr = FunctionInnards.str();
00311     printType(Out, MTy->getReturnType(), tstr);
00312     return Out;
00313   }
00314   case Type::StructTyID: {
00315     const StructType *STy = cast<StructType>(Ty);
00316     Out << NameSoFar + " {\n";
00317     unsigned Idx = 0;
00318     for (StructType::element_iterator I = STy->element_begin(),
00319            E = STy->element_end(); I != E; ++I) {
00320       Out << "  ";
00321       printType(Out, *I, "field" + utostr(Idx++));
00322       Out << ";\n";
00323     }
00324     return Out << "}";
00325   }  
00326 
00327   case Type::PointerTyID: {
00328     const PointerType *PTy = cast<PointerType>(Ty);
00329     std::string ptrName = "*" + NameSoFar;
00330 
00331     if (isa<ArrayType>(PTy->getElementType()))
00332       ptrName = "(" + ptrName + ")";
00333 
00334     return printType(Out, PTy->getElementType(), ptrName);
00335   }
00336 
00337   case Type::ArrayTyID: {
00338     const ArrayType *ATy = cast<ArrayType>(Ty);
00339     unsigned NumElements = ATy->getNumElements();
00340     return printType(Out, ATy->getElementType(),
00341                      NameSoFar + "[" + utostr(NumElements) + "]");
00342   }
00343 
00344   case Type::OpaqueTyID: {
00345     static int Count = 0;
00346     std::string TyName = "struct opaque_" + itostr(Count++);
00347     assert(TypeNames.find(Ty) == TypeNames.end());
00348     TypeNames[Ty] = TyName;
00349     return Out << TyName << " " << NameSoFar;
00350   }
00351   default:
00352     assert(0 && "Unhandled case in getTypeProps!");
00353     abort();
00354   }
00355 
00356   return Out;
00357 }
00358 
00359 void CWriter::printConstantArray(ConstantArray *CPA) {
00360 
00361   // As a special case, print the array as a string if it is an array of
00362   // ubytes or an array of sbytes with positive values.
00363   // 
00364   const Type *ETy = CPA->getType()->getElementType();
00365   bool isString = (ETy == Type::SByteTy || ETy == Type::UByteTy);
00366 
00367   // Make sure the last character is a null char, as automatically added by C
00368   if (isString && (CPA->getNumOperands() == 0 ||
00369                    !cast<Constant>(*(CPA->op_end()-1))->isNullValue()))
00370     isString = false;
00371   
00372   if (isString) {
00373     Out << "\"";
00374     // Keep track of whether the last number was a hexadecimal escape
00375     bool LastWasHex = false;
00376 
00377     // Do not include the last character, which we know is null
00378     for (unsigned i = 0, e = CPA->getNumOperands()-1; i != e; ++i) {
00379       unsigned char C = cast<ConstantInt>(CPA->getOperand(i))->getRawValue();
00380       
00381       // Print it out literally if it is a printable character.  The only thing
00382       // to be careful about is when the last letter output was a hex escape
00383       // code, in which case we have to be careful not to print out hex digits
00384       // explicitly (the C compiler thinks it is a continuation of the previous
00385       // character, sheesh...)
00386       //
00387       if (isprint(C) && (!LastWasHex || !isxdigit(C))) {
00388         LastWasHex = false;
00389         if (C == '"' || C == '\\')
00390           Out << "\\" << C;
00391         else
00392           Out << C;
00393       } else {
00394         LastWasHex = false;
00395         switch (C) {
00396         case '\n': Out << "\\n"; break;
00397         case '\t': Out << "\\t"; break;
00398         case '\r': Out << "\\r"; break;
00399         case '\v': Out << "\\v"; break;
00400         case '\a': Out << "\\a"; break;
00401         case '\"': Out << "\\\""; break;
00402         case '\'': Out << "\\\'"; break;           
00403         default:
00404           Out << "\\x";
00405           Out << (char)(( C/16  < 10) ? ( C/16 +'0') : ( C/16 -10+'A'));
00406           Out << (char)(((C&15) < 10) ? ((C&15)+'0') : ((C&15)-10+'A'));
00407           LastWasHex = true;
00408           break;
00409         }
00410       }
00411     }
00412     Out << "\"";
00413   } else {
00414     Out << "{";
00415     if (CPA->getNumOperands()) {
00416       Out << " ";
00417       printConstant(cast<Constant>(CPA->getOperand(0)));
00418       for (unsigned i = 1, e = CPA->getNumOperands(); i != e; ++i) {
00419         Out << ", ";
00420         printConstant(cast<Constant>(CPA->getOperand(i)));
00421       }
00422     }
00423     Out << " }";
00424   }
00425 }
00426 
00427 // isFPCSafeToPrint - Returns true if we may assume that CFP may be written out
00428 // textually as a double (rather than as a reference to a stack-allocated
00429 // variable). We decide this by converting CFP to a string and back into a
00430 // double, and then checking whether the conversion results in a bit-equal
00431 // double to the original value of CFP. This depends on us and the target C
00432 // compiler agreeing on the conversion process (which is pretty likely since we
00433 // only deal in IEEE FP).
00434 //
00435 static bool isFPCSafeToPrint(const ConstantFP *CFP) {
00436 #if HAVE_PRINTF_A
00437   char Buffer[100];
00438   sprintf(Buffer, "%a", CFP->getValue());
00439 
00440   if (!strncmp(Buffer, "0x", 2) ||
00441       !strncmp(Buffer, "-0x", 3) ||
00442       !strncmp(Buffer, "+0x", 3))
00443     return atof(Buffer) == CFP->getValue();
00444   return false;
00445 #else
00446   std::string StrVal = ftostr(CFP->getValue());
00447 
00448   while (StrVal[0] == ' ')
00449     StrVal.erase(StrVal.begin());
00450 
00451   // Check to make sure that the stringized number is not some string like "Inf"
00452   // or NaN.  Check that the string matches the "[-+]?[0-9]" regex.
00453   if ((StrVal[0] >= '0' && StrVal[0] <= '9') ||
00454       ((StrVal[0] == '-' || StrVal[0] == '+') &&
00455        (StrVal[1] >= '0' && StrVal[1] <= '9')))
00456     // Reparse stringized version!
00457     return atof(StrVal.c_str()) == CFP->getValue();
00458   return false;
00459 #endif
00460 }
00461 
00462 // printConstant - The LLVM Constant to C Constant converter.
00463 void CWriter::printConstant(Constant *CPV) {
00464   if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(CPV)) {
00465     switch (CE->getOpcode()) {
00466     case Instruction::Cast:
00467       Out << "((";
00468       printType(Out, CPV->getType());
00469       Out << ")";
00470       printConstant(CE->getOperand(0));
00471       Out << ")";
00472       return;
00473 
00474     case Instruction::GetElementPtr:
00475       Out << "(&(";
00476       printIndexingExpression(CE->getOperand(0), gep_type_begin(CPV),
00477                               gep_type_end(CPV));
00478       Out << "))";
00479       return;
00480     case Instruction::Select:
00481       Out << "(";
00482       printConstant(CE->getOperand(0));
00483       Out << "?";
00484       printConstant(CE->getOperand(1));
00485       Out << ":";
00486       printConstant(CE->getOperand(2));
00487       Out << ")";
00488       return;
00489     case Instruction::Add:
00490     case Instruction::Sub:
00491     case Instruction::Mul:
00492     case Instruction::Div:
00493     case Instruction::Rem:
00494     case Instruction::SetEQ:
00495     case Instruction::SetNE:
00496     case Instruction::SetLT:
00497     case Instruction::SetLE:
00498     case Instruction::SetGT:
00499     case Instruction::SetGE:
00500     case Instruction::Shl:
00501     case Instruction::Shr:
00502       Out << "(";
00503       printConstant(CE->getOperand(0));
00504       switch (CE->getOpcode()) {
00505       case Instruction::Add: Out << " + "; break;
00506       case Instruction::Sub: Out << " - "; break;
00507       case Instruction::Mul: Out << " * "; break;
00508       case Instruction::Div: Out << " / "; break;
00509       case Instruction::Rem: Out << " % "; break;
00510       case Instruction::SetEQ: Out << " == "; break;
00511       case Instruction::SetNE: Out << " != "; break;
00512       case Instruction::SetLT: Out << " < "; break;
00513       case Instruction::SetLE: Out << " <= "; break;
00514       case Instruction::SetGT: Out << " > "; break;
00515       case Instruction::SetGE: Out << " >= "; break;
00516       case Instruction::Shl: Out << " << "; break;
00517       case Instruction::Shr: Out << " >> "; break;
00518       default: assert(0 && "Illegal opcode here!");
00519       }
00520       printConstant(CE->getOperand(1));
00521       Out << ")";
00522       return;
00523 
00524     default:
00525       std::cerr << "CWriter Error: Unhandled constant expression: "
00526                 << *CE << "\n";
00527       abort();
00528     }
00529   } else if (isa<UndefValue>(CPV) && CPV->getType()->isFirstClassType()) {
00530     Out << "((";
00531     printType(Out, CPV->getType());
00532     Out << ")/*UNDEF*/0)";
00533     return;
00534   }
00535 
00536   switch (CPV->getType()->getTypeID()) {
00537   case Type::BoolTyID:
00538     Out << (CPV == ConstantBool::False ? "0" : "1"); break;
00539   case Type::SByteTyID:
00540   case Type::ShortTyID:
00541     Out << cast<ConstantSInt>(CPV)->getValue(); break;
00542   case Type::IntTyID:
00543     if ((int)cast<ConstantSInt>(CPV)->getValue() == (int)0x80000000)
00544       Out << "((int)0x80000000U)";   // Handle MININT specially to avoid warning
00545     else
00546       Out << cast<ConstantSInt>(CPV)->getValue();
00547     break;
00548 
00549   case Type::LongTyID:
00550     if (cast<ConstantSInt>(CPV)->isMinValue())
00551       Out << "(/*INT64_MIN*/(-9223372036854775807LL)-1)";
00552     else
00553       Out << cast<ConstantSInt>(CPV)->getValue() << "ll"; break;
00554 
00555   case Type::UByteTyID:
00556   case Type::UShortTyID:
00557     Out << cast<ConstantUInt>(CPV)->getValue(); break;
00558   case Type::UIntTyID:
00559     Out << cast<ConstantUInt>(CPV)->getValue() << "u"; break;
00560   case Type::ULongTyID:
00561     Out << cast<ConstantUInt>(CPV)->getValue() << "ull"; break;
00562 
00563   case Type::FloatTyID:
00564   case Type::DoubleTyID: {
00565     ConstantFP *FPC = cast<ConstantFP>(CPV);
00566     std::map<const ConstantFP*, unsigned>::iterator I = FPConstantMap.find(FPC);
00567     if (I != FPConstantMap.end()) {
00568       // Because of FP precision problems we must load from a stack allocated
00569       // value that holds the value in hex.
00570       Out << "(*(" << (FPC->getType() == Type::FloatTy ? "float" : "double")
00571           << "*)&FPConstant" << I->second << ")";
00572     } else {
00573       if (IsNAN(FPC->getValue())) {
00574         // The value is NaN
00575  
00576         // The prefix for a quiet NaN is 0x7FF8. For a signalling NaN,
00577         // it's 0x7ff4.
00578         const unsigned long QuietNaN = 0x7ff8UL;
00579         const unsigned long SignalNaN = 0x7ff4UL;
00580 
00581         // We need to grab the first part of the FP #
00582         union {
00583           double   d;
00584           uint64_t ll;
00585         } DHex;
00586         char Buffer[100];
00587 
00588         DHex.d = FPC->getValue();
00589         sprintf(Buffer, "0x%llx", (unsigned long long)DHex.ll);
00590 
00591         std::string Num(&Buffer[0], &Buffer[6]);
00592         unsigned long Val = strtoul(Num.c_str(), 0, 16);
00593 
00594         if (FPC->getType() == Type::FloatTy)
00595           Out << "LLVM_NAN" << (Val == QuietNaN ? "" : "S") << "F(\""
00596               << Buffer << "\") /*nan*/ ";
00597         else
00598           Out << "LLVM_NAN" << (Val == QuietNaN ? "" : "S") << "(\""
00599               << Buffer << "\") /*nan*/ ";
00600       } else if (IsInf(FPC->getValue())) {
00601         // The value is Inf
00602         if (FPC->getValue() < 0) Out << "-";
00603         Out << "LLVM_INF" << (FPC->getType() == Type::FloatTy ? "F" : "")
00604             << " /*inf*/ ";
00605       } else {
00606         std::string Num;
00607 #if HAVE_PRINTF_A
00608         // Print out the constant as a floating point number.
00609         char Buffer[100];
00610         sprintf(Buffer, "%a", FPC->getValue());
00611         Num = Buffer;
00612 #else
00613         Num = ftostr(FPC->getValue());
00614 #endif
00615         Out << Num;
00616       }
00617     }
00618     break;
00619   }
00620 
00621   case Type::ArrayTyID:
00622     if (isa<ConstantAggregateZero>(CPV) || isa<UndefValue>(CPV)) {
00623       const ArrayType *AT = cast<ArrayType>(CPV->getType());
00624       Out << "{";
00625       if (AT->getNumElements()) {
00626         Out << " ";
00627         Constant *CZ = Constant::getNullValue(AT->getElementType());
00628         printConstant(CZ);
00629         for (unsigned i = 1, e = AT->getNumElements(); i != e; ++i) {
00630           Out << ", ";
00631           printConstant(CZ);
00632         }
00633       }
00634       Out << " }";
00635     } else {
00636       printConstantArray(cast<ConstantArray>(CPV));
00637     }
00638     break;
00639 
00640   case Type::StructTyID:
00641     if (isa<ConstantAggregateZero>(CPV) || isa<UndefValue>(CPV)) {
00642       const StructType *ST = cast<StructType>(CPV->getType());
00643       Out << "{";
00644       if (ST->getNumElements()) {
00645         Out << " ";
00646         printConstant(Constant::getNullValue(ST->getElementType(0)));
00647         for (unsigned i = 1, e = ST->getNumElements(); i != e; ++i) {
00648           Out << ", ";
00649           printConstant(Constant::getNullValue(ST->getElementType(i)));
00650         }
00651       }
00652       Out << " }";
00653     } else {
00654       Out << "{";
00655       if (CPV->getNumOperands()) {
00656         Out << " ";
00657         printConstant(cast<Constant>(CPV->getOperand(0)));
00658         for (unsigned i = 1, e = CPV->getNumOperands(); i != e; ++i) {
00659           Out << ", ";
00660           printConstant(cast<Constant>(CPV->getOperand(i)));
00661         }
00662       }
00663       Out << " }";
00664     }
00665     break;
00666 
00667   case Type::PointerTyID:
00668     if (isa<ConstantPointerNull>(CPV)) {
00669       Out << "((";
00670       printType(Out, CPV->getType());
00671       Out << ")/*NULL*/0)";
00672       break;
00673     } else if (GlobalValue *GV = dyn_cast<GlobalValue>(CPV)) {
00674       writeOperand(GV);
00675       break;
00676     }
00677     // FALL THROUGH
00678   default:
00679     std::cerr << "Unknown constant type: " << *CPV << "\n";
00680     abort();
00681   }
00682 }
00683 
00684 void CWriter::writeOperandInternal(Value *Operand) {
00685   if (Instruction *I = dyn_cast<Instruction>(Operand))
00686     if (isInlinableInst(*I) && !isDirectAlloca(I)) {
00687       // Should we inline this instruction to build a tree?
00688       Out << "(";
00689       visit(*I);
00690       Out << ")";    
00691       return;
00692     }
00693   
00694   Constant* CPV = dyn_cast<Constant>(Operand);
00695   if (CPV && !isa<GlobalValue>(CPV)) {
00696     printConstant(CPV); 
00697   } else {
00698     Out << Mang->getValueName(Operand);
00699   }
00700 }
00701 
00702 void CWriter::writeOperand(Value *Operand) {
00703   if (isa<GlobalVariable>(Operand) || isDirectAlloca(Operand))
00704     Out << "(&";  // Global variables are references as their addresses by llvm
00705 
00706   writeOperandInternal(Operand);
00707 
00708   if (isa<GlobalVariable>(Operand) || isDirectAlloca(Operand))
00709     Out << ")";
00710 }
00711 
00712 // generateCompilerSpecificCode - This is where we add conditional compilation
00713 // directives to cater to specific compilers as need be.
00714 //
00715 static void generateCompilerSpecificCode(std::ostream& Out) {
00716   // Alloca is hard to get, and we don't want to include stdlib.h here...
00717   Out << "/* get a declaration for alloca */\n"
00718       << "#if defined(sun) || defined(__CYGWIN__) || defined(__APPLE__)\n"
00719       << "extern void *__builtin_alloca(unsigned long);\n"
00720       << "#define alloca(x) __builtin_alloca(x)\n"
00721       << "#elif defined(__FreeBSD__)\n"
00722       << "#define alloca(x) __builtin_alloca(x)\n"
00723       << "#else\n"
00724       << "#include <alloca.h>\n"
00725       << "#endif\n\n";
00726 
00727   // We output GCC specific attributes to preserve 'linkonce'ness on globals.
00728   // If we aren't being compiled with GCC, just drop these attributes.
00729   Out << "#ifndef __GNUC__  /* Can only support \"linkonce\" vars with GCC */\n"
00730       << "#define __attribute__(X)\n"
00731       << "#endif\n\n";
00732 
00733 #if 0
00734   // At some point, we should support "external weak" vs. "weak" linkages.
00735   // On Mac OS X, "external weak" is spelled "__attribute__((weak_import))".
00736   Out << "#if defined(__GNUC__) && defined(__APPLE_CC__)\n"
00737       << "#define __EXTERNAL_WEAK__ __attribute__((weak_import))\n"
00738       << "#elif defined(__GNUC__)\n"
00739       << "#define __EXTERNAL_WEAK__ __attribute__((weak))\n"
00740       << "#else\n"
00741       << "#define __EXTERNAL_WEAK__\n"
00742       << "#endif\n\n";
00743 #endif
00744 
00745   // For now, turn off the weak linkage attribute on Mac OS X. (See above.)
00746   Out << "#if defined(__GNUC__) && defined(__APPLE_CC__)\n"
00747       << "#define __ATTRIBUTE_WEAK__\n"
00748       << "#elif defined(__GNUC__)\n"
00749       << "#define __ATTRIBUTE_WEAK__ __attribute__((weak))\n"
00750       << "#else\n"
00751       << "#define __ATTRIBUTE_WEAK__\n"
00752       << "#endif\n\n";
00753 
00754   // Define NaN and Inf as GCC builtins if using GCC, as 0 otherwise
00755   // From the GCC documentation:
00756   // 
00757   //   double __builtin_nan (const char *str)
00758   //
00759   // This is an implementation of the ISO C99 function nan.
00760   //
00761   // Since ISO C99 defines this function in terms of strtod, which we do
00762   // not implement, a description of the parsing is in order. The string is
00763   // parsed as by strtol; that is, the base is recognized by leading 0 or
00764   // 0x prefixes. The number parsed is placed in the significand such that
00765   // the least significant bit of the number is at the least significant
00766   // bit of the significand. The number is truncated to fit the significand
00767   // field provided. The significand is forced to be a quiet NaN.
00768   //
00769   // This function, if given a string literal, is evaluated early enough
00770   // that it is considered a compile-time constant.
00771   //
00772   //   float __builtin_nanf (const char *str)
00773   //
00774   // Similar to __builtin_nan, except the return type is float.
00775   //
00776   //   double __builtin_inf (void)
00777   //
00778   // Similar to __builtin_huge_val, except a warning is generated if the
00779   // target floating-point format does not support infinities. This
00780   // function is suitable for implementing the ISO C99 macro INFINITY.
00781   //
00782   //   float __builtin_inff (void)
00783   //
00784   // Similar to __builtin_inf, except the return type is float.
00785   Out << "#ifdef __GNUC__\n"
00786       << "#define LLVM_NAN(NanStr)   __builtin_nan(NanStr)   /* Double */\n"
00787       << "#define LLVM_NANF(NanStr)  __builtin_nanf(NanStr)  /* Float */\n"
00788       << "#define LLVM_NANS(NanStr)  __builtin_nans(NanStr)  /* Double */\n"
00789       << "#define LLVM_NANSF(NanStr) __builtin_nansf(NanStr) /* Float */\n"
00790       << "#define LLVM_INF           __builtin_inf()         /* Double */\n"
00791       << "#define LLVM_INFF          __builtin_inff()        /* Float */\n"
00792       << "#else\n"
00793       << "#define LLVM_NAN(NanStr)   ((double)0.0)           /* Double */\n"
00794       << "#define LLVM_NANF(NanStr)  0.0F                    /* Float */\n"
00795       << "#define LLVM_NANS(NanStr)  ((double)0.0)           /* Double */\n"
00796       << "#define LLVM_NANSF(NanStr) 0.0F                    /* Float */\n"
00797       << "#define LLVM_INF           ((double)0.0)           /* Double */\n"
00798       << "#define LLVM_INFF          0.0F                    /* Float */\n"
00799       << "#endif\n";
00800 }
00801 
00802 bool CWriter::doInitialization(Module &M) {
00803   // Initialize
00804   TheModule = &M;
00805 
00806   IL.AddPrototypes(M);
00807   
00808   // Ensure that all structure types have names...
00809   Mang = new Mangler(M);
00810 
00811   // get declaration for alloca
00812   Out << "/* Provide Declarations */\n";
00813   Out << "#include <stdarg.h>\n";      // Varargs support
00814   Out << "#include <setjmp.h>\n";      // Unwind support
00815   generateCompilerSpecificCode(Out);
00816 
00817   // Provide a definition for `bool' if not compiling with a C++ compiler.
00818   Out << "\n"
00819       << "#ifndef __cplusplus\ntypedef unsigned char bool;\n#endif\n"
00820     
00821       << "\n\n/* Support for floating point constants */\n"
00822       << "typedef unsigned long long ConstantDoubleTy;\n"
00823       << "typedef unsigned int        ConstantFloatTy;\n"
00824     
00825       << "\n\n/* Global Declarations */\n";
00826 
00827   // First output all the declarations for the program, because C requires
00828   // Functions & globals to be declared before they are used.
00829   //
00830 
00831   // Loop over the symbol table, emitting all named constants...
00832   printModuleTypes(M.getSymbolTable());
00833 
00834   // Global variable declarations...
00835   if (!M.gempty()) {
00836     Out << "\n/* External Global Variable Declarations */\n";
00837     for (Module::giterator I = M.gbegin(), E = M.gend(); I != E; ++I) {
00838       if (I->hasExternalLinkage()) {
00839         Out << "extern ";
00840         printType(Out, I->getType()->getElementType(), Mang->getValueName(I));
00841         Out << ";\n";
00842       }
00843     }
00844   }
00845 
00846   // Function declarations
00847   if (!M.empty()) {
00848     Out << "\n/* Function Declarations */\n";
00849     for (Module::iterator I = M.begin(), E = M.end(); I != E; ++I) {
00850       // Don't print declarations for intrinsic functions.
00851       if (!I->getIntrinsicID() && 
00852           I->getName() != "setjmp" && I->getName() != "longjmp") {
00853         printFunctionSignature(I, true);
00854         if (I->hasWeakLinkage()) Out << " __ATTRIBUTE_WEAK__";
00855         if (I->hasLinkOnceLinkage()) Out << " __ATTRIBUTE_WEAK__";
00856         Out << ";\n";
00857       }
00858     }
00859   }
00860 
00861   // Output the global variable declarations
00862   if (!M.gempty()) {
00863     Out << "\n\n/* Global Variable Declarations */\n";
00864     for (Module::giterator I = M.gbegin(), E = M.gend(); I != E; ++I)
00865       if (!I->isExternal()) {
00866         if (I->hasInternalLinkage())
00867           Out << "static ";
00868         else
00869           Out << "extern ";
00870         printType(Out, I->getType()->getElementType(), Mang->getValueName(I));
00871 
00872         if (I->hasLinkOnceLinkage())
00873           Out << " __attribute__((common))";
00874         else if (I->hasWeakLinkage())
00875           Out << " __ATTRIBUTE_WEAK__";
00876         Out << ";\n";
00877       }
00878   }
00879 
00880   // Output the global variable definitions and contents...
00881   if (!M.gempty()) {
00882     Out << "\n\n/* Global Variable Definitions and Initialization */\n";
00883     for (Module::giterator I = M.gbegin(), E = M.gend(); I != E; ++I)
00884       if (!I->isExternal()) {
00885         if (I->hasInternalLinkage())
00886           Out << "static ";
00887         printType(Out, I->getType()->getElementType(), Mang->getValueName(I));
00888         if (I->hasLinkOnceLinkage())
00889           Out << " __attribute__((common))";
00890         else if (I->hasWeakLinkage())
00891           Out << " __ATTRIBUTE_WEAK__";
00892 
00893         // If the initializer is not null, emit the initializer.  If it is null,
00894         // we try to avoid emitting large amounts of zeros.  The problem with
00895         // this, however, occurs when the variable has weak linkage.  In this
00896         // case, the assembler will complain about the variable being both weak
00897         // and common, so we disable this optimization.
00898         if (!I->getInitializer()->isNullValue()) {
00899           Out << " = " ;
00900           writeOperand(I->getInitializer());
00901         } else if (I->hasWeakLinkage()) {
00902           // We have to specify an initializer, but it doesn't have to be
00903           // complete.  If the value is an aggregate, print out { 0 }, and let
00904           // the compiler figure out the rest of the zeros.
00905           Out << " = " ;
00906           if (isa<StructType>(I->getInitializer()->getType()) ||
00907               isa<ArrayType>(I->getInitializer()->getType())) {
00908             Out << "{ 0 }";
00909           } else {
00910             // Just print it out normally.
00911             writeOperand(I->getInitializer());
00912           }
00913         }
00914         Out << ";\n";
00915       }
00916   }
00917 
00918   if (!M.empty())
00919     Out << "\n\n/* Function Bodies */\n";
00920   return false;
00921 }
00922 
00923 
00924 /// Output all floating point constants that cannot be printed accurately...
00925 void CWriter::printFloatingPointConstants(Function &F) {
00926   union {
00927     double D;
00928     uint64_t U;
00929   } DBLUnion;
00930 
00931   union {
00932     float F;
00933     unsigned U;
00934   } FLTUnion;
00935 
00936   // Scan the module for floating point constants.  If any FP constant is used
00937   // in the function, we want to redirect it here so that we do not depend on
00938   // the precision of the printed form, unless the printed form preserves
00939   // precision.
00940   //
00941   static unsigned FPCounter = 0;
00942   for (constant_iterator I = constant_begin(&F), E = constant_end(&F);
00943        I != E; ++I)
00944     if (const ConstantFP *FPC = dyn_cast<ConstantFP>(*I))
00945       if (!isFPCSafeToPrint(FPC) && // Do not put in FPConstantMap if safe.
00946           !FPConstantMap.count(FPC)) {
00947         double Val = FPC->getValue();
00948         
00949         FPConstantMap[FPC] = FPCounter;  // Number the FP constants
00950         
00951         if (FPC->getType() == Type::DoubleTy) {
00952           DBLUnion.D = Val;
00953           Out << "static const ConstantDoubleTy FPConstant" << FPCounter++
00954               << " = 0x" << std::hex << DBLUnion.U << std::dec
00955               << "ULL;    /* " << Val << " */\n";
00956         } else if (FPC->getType() == Type::FloatTy) {
00957           FLTUnion.F = Val;
00958           Out << "static const ConstantFloatTy FPConstant" << FPCounter++
00959               << " = 0x" << std::hex << FLTUnion.U << std::dec
00960               << "U;    /* " << Val << " */\n";
00961         } else
00962           assert(0 && "Unknown float type!");
00963       }
00964   
00965   Out << "\n";
00966 }
00967 
00968 
00969 /// printSymbolTable - Run through symbol table looking for type names.  If a
00970 /// type name is found, emit it's declaration...
00971 ///
00972 void CWriter::printModuleTypes(const SymbolTable &ST) {
00973   // If there are no type names, exit early.
00974   if ( ! ST.hasTypes() )
00975     return;
00976 
00977   // We are only interested in the type plane of the symbol table...
00978   SymbolTable::type_const_iterator I   = ST.type_begin();
00979   SymbolTable::type_const_iterator End = ST.type_end();
00980   
00981   // Print out forward declarations for structure types before anything else!
00982   Out << "/* Structure forward decls */\n";
00983   for (; I != End; ++I)
00984     if (const Type *STy = dyn_cast<StructType>(I->second)) {
00985       std::string Name = "struct l_" + Mangler::makeNameProper(I->first);
00986       Out << Name << ";\n";
00987       TypeNames.insert(std::make_pair(STy, Name));
00988     }
00989 
00990   Out << "\n";
00991 
00992   // Now we can print out typedefs...
00993   Out << "/* Typedefs */\n";
00994   for (I = ST.type_begin(); I != End; ++I) {
00995     const Type *Ty = cast<Type>(I->second);
00996     std::string Name = "l_" + Mangler::makeNameProper(I->first);
00997     Out << "typedef ";
00998     printType(Out, Ty, Name);
00999     Out << ";\n";
01000   }
01001   
01002   Out << "\n";
01003 
01004   // Keep track of which structures have been printed so far...
01005   std::set<const StructType *> StructPrinted;
01006 
01007   // Loop over all structures then push them into the stack so they are
01008   // printed in the correct order.
01009   //
01010   Out << "/* Structure contents */\n";
01011   for (I = ST.type_begin(); I != End; ++I)
01012     if (const StructType *STy = dyn_cast<StructType>(I->second))
01013       // Only print out used types!
01014       printContainedStructs(STy, StructPrinted);
01015 }
01016 
01017 // Push the struct onto the stack and recursively push all structs
01018 // this one depends on.
01019 void CWriter::printContainedStructs(const Type *Ty,
01020                                     std::set<const StructType*> &StructPrinted){
01021   if (const StructType *STy = dyn_cast<StructType>(Ty)) {
01022     //Check to see if we have already printed this struct
01023     if (StructPrinted.count(STy) == 0) {
01024       // Print all contained types first...
01025       for (StructType::element_iterator I = STy->element_begin(),
01026              E = STy->element_end(); I != E; ++I) {
01027         const Type *Ty1 = I->get();
01028         if (isa<StructType>(Ty1) || isa<ArrayType>(Ty1))
01029           printContainedStructs(*I, StructPrinted);
01030       }
01031       
01032       //Print structure type out..
01033       StructPrinted.insert(STy);
01034       std::string Name = TypeNames[STy];  
01035       printType(Out, STy, Name, true);
01036       Out << ";\n\n";
01037     }
01038 
01039     // If it is an array, check contained types and continue
01040   } else if (const ArrayType *ATy = dyn_cast<ArrayType>(Ty)){
01041     const Type *Ty1 = ATy->getElementType();
01042     if (isa<StructType>(Ty1) || isa<ArrayType>(Ty1))
01043       printContainedStructs(Ty1, StructPrinted);
01044   }
01045 }
01046 
01047 
01048 void CWriter::printFunctionSignature(const Function *F, bool Prototype) {
01049   if (F->hasInternalLinkage()) Out << "static ";
01050   
01051   // Loop over the arguments, printing them...
01052   const FunctionType *FT = cast<FunctionType>(F->getFunctionType());
01053   
01054   std::stringstream FunctionInnards; 
01055     
01056   // Print out the name...
01057   FunctionInnards << Mang->getValueName(F) << "(";
01058     
01059   if (!F->isExternal()) {
01060     if (!F->aempty()) {
01061       std::string ArgName;
01062       if (F->abegin()->hasName() || !Prototype)
01063         ArgName = Mang->getValueName(F->abegin());
01064       printType(FunctionInnards, F->afront().getType(), ArgName);
01065       for (Function::const_aiterator I = ++F->abegin(), E = F->aend();
01066            I != E; ++I) {
01067         FunctionInnards << ", ";
01068         if (I->hasName() || !Prototype)
01069           ArgName = Mang->getValueName(I);
01070         else 
01071           ArgName = "";
01072         printType(FunctionInnards, I->getType(), ArgName);
01073       }
01074     }
01075   } else {
01076     // Loop over the arguments, printing them...
01077     for (FunctionType::param_iterator I = FT->param_begin(),
01078            E = FT->param_end(); I != E; ++I) {
01079       if (I != FT->param_begin()) FunctionInnards << ", ";
01080       printType(FunctionInnards, *I);
01081     }
01082   }
01083 
01084   // Finish printing arguments... if this is a vararg function, print the ...,
01085   // unless there are no known types, in which case, we just emit ().
01086   //
01087   if (FT->isVarArg() && FT->getNumParams()) {
01088     if (FT->getNumParams()) FunctionInnards << ", ";
01089     FunctionInnards << "...";  // Output varargs portion of signature!
01090   } else if (!FT->isVarArg() && FT->getNumParams() == 0) {
01091     FunctionInnards << "void"; // ret() -> ret(void) in C.
01092   }
01093   FunctionInnards << ")";
01094   // Print out the return type and the entire signature for that matter
01095   printType(Out, F->getReturnType(), FunctionInnards.str());
01096 }
01097 
01098 void CWriter::printFunction(Function &F) {
01099   printFunctionSignature(&F, false);
01100   Out << " {\n";
01101 
01102   // print local variable information for the function
01103   for (inst_iterator I = inst_begin(&F), E = inst_end(&F); I != E; ++I)
01104     if (const AllocaInst *AI = isDirectAlloca(&*I)) {
01105       Out << "  ";
01106       printType(Out, AI->getAllocatedType(), Mang->getValueName(AI));
01107       Out << ";    /* Address exposed local */\n";
01108     } else if (I->getType() != Type::VoidTy && !isInlinableInst(*I)) {
01109       Out << "  ";
01110       printType(Out, I->getType(), Mang->getValueName(&*I));
01111       Out << ";\n";
01112       
01113       if (isa<PHINode>(*I)) {  // Print out PHI node temporaries as well...
01114         Out << "  ";
01115         printType(Out, I->getType(),
01116                   Mang->getValueName(&*I)+"__PHI_TEMPORARY");
01117         Out << ";\n";
01118       }
01119     }
01120 
01121   Out << "\n";
01122 
01123   // print the basic blocks
01124   for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB) {
01125     if (Loop *L = LI->getLoopFor(BB)) {
01126       if (L->getHeader() == BB && L->getParentLoop() == 0)
01127         printLoop(L);
01128     } else {
01129       printBasicBlock(BB);
01130     }
01131   }
01132   
01133   Out << "}\n\n";
01134 }
01135 
01136 void CWriter::printLoop(Loop *L) {
01137   Out << "  do {     /* Syntactic loop '" << L->getHeader()->getName()
01138       << "' to make GCC happy */\n";
01139   for (unsigned i = 0, e = L->getBlocks().size(); i != e; ++i) {
01140     BasicBlock *BB = L->getBlocks()[i];
01141     Loop *BBLoop = LI->getLoopFor(BB);
01142     if (BBLoop == L)
01143       printBasicBlock(BB);
01144     else if (BB == BBLoop->getHeader() && BBLoop->getParentLoop() == L)
01145       printLoop(BBLoop);      
01146   }
01147   Out << "  } while (1); /* end of syntactic loop '"
01148       << L->getHeader()->getName() << "' */\n";
01149 }
01150 
01151 void CWriter::printBasicBlock(BasicBlock *BB) {
01152 
01153   // Don't print the label for the basic block if there are no uses, or if
01154   // the only terminator use is the predecessor basic block's terminator.
01155   // We have to scan the use list because PHI nodes use basic blocks too but
01156   // do not require a label to be generated.
01157   //
01158   bool NeedsLabel = false;
01159   for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI)
01160     if (isGotoCodeNecessary(*PI, BB)) {
01161       NeedsLabel = true;
01162       break;
01163     }
01164       
01165   if (NeedsLabel) Out << Mang->getValueName(BB) << ":\n";
01166       
01167   // Output all of the instructions in the basic block...
01168   for (BasicBlock::iterator II = BB->begin(), E = --BB->end(); II != E;
01169        ++II) {
01170     if (!isInlinableInst(*II) && !isDirectAlloca(II)) {
01171       if (II->getType() != Type::VoidTy)
01172         outputLValue(II);
01173       else
01174         Out << "  ";
01175       visit(*II);
01176       Out << ";\n";
01177     }
01178   }
01179       
01180   // Don't emit prefix or suffix for the terminator...
01181   visit(*BB->getTerminator());
01182 }
01183 
01184 
01185 // Specific Instruction type classes... note that all of the casts are
01186 // necessary because we use the instruction classes as opaque types...
01187 //
01188 void CWriter::visitReturnInst(ReturnInst &I) {
01189   // Don't output a void return if this is the last basic block in the function
01190   if (I.getNumOperands() == 0 && 
01191       &*--I.getParent()->getParent()->end() == I.getParent() &&
01192       !I.getParent()->size() == 1) {
01193     return;
01194   }
01195 
01196   Out << "  return";
01197   if (I.getNumOperands()) {
01198     Out << " ";
01199     writeOperand(I.getOperand(0));
01200   }
01201   Out << ";\n";
01202 }
01203 
01204 void CWriter::visitSwitchInst(SwitchInst &SI) {
01205 
01206   Out << "  switch (";
01207   writeOperand(SI.getOperand(0));
01208   Out << ") {\n  default:\n";
01209   printPHICopiesForSuccessor (SI.getParent(), SI.getDefaultDest(), 2);
01210   printBranchToBlock(SI.getParent(), SI.getDefaultDest(), 2);
01211   Out << ";\n";
01212   for (unsigned i = 2, e = SI.getNumOperands(); i != e; i += 2) {
01213     Out << "  case ";
01214     writeOperand(SI.getOperand(i));
01215     Out << ":\n";
01216     BasicBlock *Succ = cast<BasicBlock>(SI.getOperand(i+1));
01217     printPHICopiesForSuccessor (SI.getParent(), Succ, 2);
01218     printBranchToBlock(SI.getParent(), Succ, 2);
01219     if (Succ == SI.getParent()->getNext())
01220       Out << "    break;\n";
01221   }
01222   Out << "  }\n";
01223 }
01224 
01225 void CWriter::visitUnreachableInst(UnreachableInst &I) {
01226   Out << "  /*UNREACHABLE*/;\n";
01227 }
01228 
01229 bool CWriter::isGotoCodeNecessary(BasicBlock *From, BasicBlock *To) {
01230   /// FIXME: This should be reenabled, but loop reordering safe!!
01231   return true;
01232 
01233   if (From->getNext() != To) // Not the direct successor, we need a goto
01234     return true; 
01235 
01236   //isa<SwitchInst>(From->getTerminator())
01237 
01238 
01239   if (LI->getLoopFor(From) != LI->getLoopFor(To))
01240     return true;
01241   return false;
01242 }
01243 
01244 void CWriter::printPHICopiesForSuccessor (BasicBlock *CurBlock,
01245                                           BasicBlock *Successor, 
01246                                           unsigned Indent) {
01247   for (BasicBlock::iterator I = Successor->begin(); isa<PHINode>(I); ++I) {
01248     PHINode *PN = cast<PHINode>(I);
01249     // Now we have to do the printing.
01250     Value *IV = PN->getIncomingValueForBlock(CurBlock);
01251     if (!isa<UndefValue>(IV)) {
01252       Out << std::string(Indent, ' ');
01253       Out << "  " << Mang->getValueName(I) << "__PHI_TEMPORARY = ";
01254       writeOperand(IV);
01255       Out << ";   /* for PHI node */\n";
01256     }
01257   }
01258 }
01259 
01260 void CWriter::printBranchToBlock(BasicBlock *CurBB, BasicBlock *Succ,
01261                                  unsigned Indent) {
01262   if (isGotoCodeNecessary(CurBB, Succ)) {
01263     Out << std::string(Indent, ' ') << "  goto ";
01264     writeOperand(Succ);
01265     Out << ";\n";
01266   }
01267 }
01268 
01269 // Branch instruction printing - Avoid printing out a branch to a basic block
01270 // that immediately succeeds the current one.
01271 //
01272 void CWriter::visitBranchInst(BranchInst &I) {
01273 
01274   if (I.isConditional()) {
01275     if (isGotoCodeNecessary(I.getParent(), I.getSuccessor(0))) {
01276       Out << "  if (";
01277       writeOperand(I.getCondition());
01278       Out << ") {\n";
01279       
01280       printPHICopiesForSuccessor (I.getParent(), I.getSuccessor(0), 2);
01281       printBranchToBlock(I.getParent(), I.getSuccessor(0), 2);
01282       
01283       if (isGotoCodeNecessary(I.getParent(), I.getSuccessor(1))) {
01284         Out << "  } else {\n";
01285         printPHICopiesForSuccessor (I.getParent(), I.getSuccessor(1), 2);
01286         printBranchToBlock(I.getParent(), I.getSuccessor(1), 2);
01287       }
01288     } else {
01289       // First goto not necessary, assume second one is...
01290       Out << "  if (!";
01291       writeOperand(I.getCondition());
01292       Out << ") {\n";
01293 
01294       printPHICopiesForSuccessor (I.getParent(), I.getSuccessor(1), 2);
01295       printBranchToBlock(I.getParent(), I.getSuccessor(1), 2);
01296     }
01297 
01298     Out << "  }\n";
01299   } else {
01300     printPHICopiesForSuccessor (I.getParent(), I.getSuccessor(0), 0);
01301     printBranchToBlock(I.getParent(), I.getSuccessor(0), 0);
01302   }
01303   Out << "\n";
01304 }
01305 
01306 // PHI nodes get copied into temporary values at the end of predecessor basic
01307 // blocks.  We now need to copy these temporary values into the REAL value for
01308 // the PHI.
01309 void CWriter::visitPHINode(PHINode &I) {
01310   writeOperand(&I);
01311   Out << "__PHI_TEMPORARY";
01312 }
01313 
01314 
01315 void CWriter::visitBinaryOperator(Instruction &I) {
01316   // binary instructions, shift instructions, setCond instructions.
01317   assert(!isa<PointerType>(I.getType()));
01318 
01319   // We must cast the results of binary operations which might be promoted.
01320   bool needsCast = false;
01321   if ((I.getType() == Type::UByteTy) || (I.getType() == Type::SByteTy)
01322       || (I.getType() == Type::UShortTy) || (I.getType() == Type::ShortTy)
01323       || (I.getType() == Type::FloatTy)) {
01324     needsCast = true;
01325     Out << "((";
01326     printType(Out, I.getType());
01327     Out << ")(";
01328   }
01329       
01330   writeOperand(I.getOperand(0));
01331 
01332   switch (I.getOpcode()) {
01333   case Instruction::Add: Out << " + "; break;
01334   case Instruction::Sub: Out << " - "; break;
01335   case Instruction::Mul: Out << "*"; break;
01336   case Instruction::Div: Out << "/"; break;
01337   case Instruction::Rem: Out << "%"; break;
01338   case Instruction::And: Out << " & "; break;
01339   case Instruction::Or: Out << " | "; break;
01340   case Instruction::Xor: Out << " ^ "; break;
01341   case Instruction::SetEQ: Out << " == "; break;
01342   case Instruction::SetNE: Out << " != "; break;
01343   case Instruction::SetLE: Out << " <= "; break;
01344   case Instruction::SetGE: Out << " >= "; break;
01345   case Instruction::SetLT: Out << " < "; break;
01346   case Instruction::SetGT: Out << " > "; break;
01347   case Instruction::Shl : Out << " << "; break;
01348   case Instruction::Shr : Out << " >> "; break;
01349   default: std::cerr << "Invalid operator type!" << I; abort();
01350   }
01351 
01352   writeOperand(I.getOperand(1));
01353 
01354   if (needsCast) {
01355     Out << "))";
01356   }
01357 }
01358 
01359 void CWriter::visitCastInst(CastInst &I) {
01360   if (I.getType() == Type::BoolTy) {
01361     Out << "(";
01362     writeOperand(I.getOperand(0));
01363     Out << " != 0)";
01364     return;
01365   }
01366   Out << "(";
01367   printType(Out, I.getType());
01368   Out << ")";
01369   if (isa<PointerType>(I.getType())&&I.getOperand(0)->getType()->isIntegral() ||
01370       isa<PointerType>(I.getOperand(0)->getType())&&I.getType()->isIntegral()) {
01371     // Avoid "cast to pointer from integer of different size" warnings
01372     Out << "(long)";  
01373   }
01374   
01375   writeOperand(I.getOperand(0));
01376 }
01377 
01378 void CWriter::visitSelectInst(SelectInst &I) {
01379   Out << "((";
01380   writeOperand(I.getCondition());
01381   Out << ") ? (";
01382   writeOperand(I.getTrueValue());
01383   Out << ") : (";
01384   writeOperand(I.getFalseValue());
01385   Out << "))";    
01386 }
01387 
01388 
01389 void CWriter::lowerIntrinsics(Function &F) {
01390   for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
01391     for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; )
01392       if (CallInst *CI = dyn_cast<CallInst>(I++))
01393         if (Function *F = CI->getCalledFunction())
01394           switch (F->getIntrinsicID()) {
01395           case Intrinsic::not_intrinsic:
01396           case Intrinsic::vastart:
01397           case Intrinsic::vacopy:
01398           case Intrinsic::vaend:
01399           case Intrinsic::returnaddress:
01400           case Intrinsic::frameaddress:
01401           case Intrinsic::setjmp:
01402           case Intrinsic::longjmp:
01403             // We directly implement these intrinsics
01404             break;
01405           default:
01406             // All other intrinsic calls we must lower.
01407             Instruction *Before = CI->getPrev();
01408             IL.LowerIntrinsicCall(CI);
01409             if (Before) {        // Move iterator to instruction after call
01410               I = Before; ++I;
01411             } else {
01412               I = BB->begin();
01413             }
01414           }
01415 }
01416 
01417 
01418 
01419 void CWriter::visitCallInst(CallInst &I) {
01420   // Handle intrinsic function calls first...
01421   if (Function *F = I.getCalledFunction())
01422     if (Intrinsic::ID ID = (Intrinsic::ID)F->getIntrinsicID()) {
01423       switch (ID) {
01424       default: assert(0 && "Unknown LLVM intrinsic!");
01425       case Intrinsic::vastart: 
01426         Out << "0; ";
01427         
01428         Out << "va_start(*(va_list*)&" << Mang->getValueName(&I) << ", ";
01429         // Output the last argument to the enclosing function...
01430         if (I.getParent()->getParent()->aempty()) {
01431           std::cerr << "The C backend does not currently support zero "
01432                     << "argument varargs functions, such as '"
01433                     << I.getParent()->getParent()->getName() << "'!\n";
01434           abort();
01435         }
01436         writeOperand(&I.getParent()->getParent()->aback());
01437         Out << ")";
01438         return;
01439       case Intrinsic::vaend:
01440         if (!isa<ConstantPointerNull>(I.getOperand(1))) {
01441           Out << "va_end(*(va_list*)&";
01442           writeOperand(I.getOperand(1));
01443           Out << ")";
01444         } else {
01445           Out << "va_end(*(va_list*)0)";
01446         }
01447         return;
01448       case Intrinsic::vacopy:
01449         Out << "0;";
01450         Out << "va_copy(*(va_list*)&" << Mang->getValueName(&I) << ", ";
01451         Out << "*(va_list*)&";
01452         writeOperand(I.getOperand(1));
01453         Out << ")";
01454         return;
01455       case Intrinsic::returnaddress:
01456         Out << "__builtin_return_address(";
01457         writeOperand(I.getOperand(1));
01458         Out << ")";
01459         return;
01460       case Intrinsic::frameaddress:
01461         Out << "__builtin_frame_address(";
01462         writeOperand(I.getOperand(1));
01463         Out << ")";
01464         return;
01465       case Intrinsic::setjmp:
01466         Out << "setjmp(*(jmp_buf*)";
01467         writeOperand(I.getOperand(1));
01468         Out << ")";
01469         return;
01470       case Intrinsic::longjmp:
01471         Out << "longjmp(*(jmp_buf*)";
01472         writeOperand(I.getOperand(1));
01473         Out << ", ";
01474         writeOperand(I.getOperand(2));
01475         Out << ")";
01476         return;
01477       }
01478     }
01479 
01480   Value *Callee = I.getCalledValue();
01481   
01482   // GCC is really a PITA.  It does not permit codegening casts of functions to
01483   // function pointers if they are in a call (it generates a trap instruction
01484   // instead!).  We work around this by inserting a cast to void* in between the
01485   // function and the function pointer cast.  Unfortunately, we can't just form
01486   // the constant expression here, because the folder will immediately nuke it.
01487   //
01488   // Note finally, that this is completely unsafe.  ANSI C does not guarantee
01489   // that void* and function pointers have the same size. :( To deal with this
01490   // in the common case, we handle casts where the number of arguments passed
01491   // match exactly.
01492   //
01493   bool WroteCallee = false;
01494   if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Callee))
01495     if (CE->getOpcode() == Instruction::Cast)
01496       if (Function *RF = dyn_cast<Function>(CE->getOperand(0))) {
01497         const FunctionType *RFTy = RF->getFunctionType();
01498         if (RFTy->getNumParams() == I.getNumOperands()-1) {
01499           // If the call site expects a value, and the actual callee doesn't
01500           // provide one, return 0.
01501           if (I.getType() != Type::VoidTy &&
01502               RFTy->getReturnType() == Type::VoidTy)
01503             Out << "0 /*actual callee doesn't return value*/; ";
01504           Callee = RF;
01505         } else {
01506           // Ok, just cast the pointer type.
01507           Out << "((";
01508           printType(Out, CE->getType());
01509           Out << ")(void*)";
01510           printConstant(RF);
01511           Out << ")";
01512           WroteCallee = true;
01513         }
01514       }
01515 
01516   const PointerType  *PTy   = cast<PointerType>(Callee->getType());
01517   const FunctionType *FTy   = cast<FunctionType>(PTy->getElementType());
01518   const Type         *RetTy = FTy->getReturnType();
01519   
01520   if (!WroteCallee) writeOperand(Callee);
01521   Out << "(";
01522 
01523   unsigned NumDeclaredParams = FTy->getNumParams();
01524 
01525   if (I.getNumOperands() != 1) {
01526     CallSite::arg_iterator AI = I.op_begin()+1, AE = I.op_end();
01527     if (NumDeclaredParams && (*AI)->getType() != FTy->getParamType(0)) {
01528       Out << "(";
01529       printType(Out, FTy->getParamType(0));
01530       Out << ")";
01531     }
01532 
01533     writeOperand(*AI);
01534 
01535     unsigned ArgNo;
01536     for (ArgNo = 1, ++AI; AI != AE; ++AI, ++ArgNo) {
01537       Out << ", ";
01538       if (ArgNo < NumDeclaredParams &&
01539           (*AI)->getType() != FTy->getParamType(ArgNo)) {
01540         Out << "(";
01541         printType(Out, FTy->getParamType(ArgNo));
01542         Out << ")";
01543       }
01544       writeOperand(*AI);
01545     }
01546   }
01547   Out << ")";
01548 }  
01549 
01550 void CWriter::visitMallocInst(MallocInst &I) {
01551   assert(0 && "lowerallocations pass didn't work!");
01552 }
01553 
01554 void CWriter::visitAllocaInst(AllocaInst &I) {
01555   Out << "(";
01556   printType(Out, I.getType());
01557   Out << ") alloca(sizeof(";
01558   printType(Out, I.getType()->getElementType());
01559   Out << ")";
01560   if (I.isArrayAllocation()) {
01561     Out << " * " ;
01562     writeOperand(I.getOperand(0));
01563   }
01564   Out << ")";
01565 }
01566 
01567 void CWriter::visitFreeInst(FreeInst &I) {
01568   assert(0 && "lowerallocations pass didn't work!");
01569 }
01570 
01571 void CWriter::printIndexingExpression(Value *Ptr, gep_type_iterator I,
01572                                       gep_type_iterator E) {
01573   bool HasImplicitAddress = false;
01574   // If accessing a global value with no indexing, avoid *(&GV) syndrome
01575   if (GlobalValue *V = dyn_cast<GlobalValue>(Ptr)) {
01576     HasImplicitAddress = true;
01577   } else if (isDirectAlloca(Ptr)) {
01578     HasImplicitAddress = true;
01579   }
01580 
01581   if (I == E) {
01582     if (!HasImplicitAddress)
01583       Out << "*";  // Implicit zero first argument: '*x' is equivalent to 'x[0]'
01584 
01585     writeOperandInternal(Ptr);
01586     return;
01587   }
01588 
01589   const Constant *CI = dyn_cast<Constant>(I.getOperand());
01590   if (HasImplicitAddress && (!CI || !CI->isNullValue()))
01591     Out << "(&";
01592 
01593   writeOperandInternal(Ptr);
01594 
01595   if (HasImplicitAddress && (!CI || !CI->isNullValue())) {
01596     Out << ")";
01597     HasImplicitAddress = false;  // HIA is only true if we haven't addressed yet
01598   }
01599 
01600   assert(!HasImplicitAddress || (CI && CI->isNullValue()) &&
01601          "Can only have implicit address with direct accessing");
01602 
01603   if (HasImplicitAddress) {
01604     ++I;
01605   } else if (CI && CI->isNullValue()) {
01606     gep_type_iterator TmpI = I; ++TmpI;
01607 
01608     // Print out the -> operator if possible...
01609     if (TmpI != E && isa<StructType>(*TmpI)) {
01610       Out << (HasImplicitAddress ? "." : "->");
01611       Out << "field" << cast<ConstantUInt>(TmpI.getOperand())->getValue();
01612       I = ++TmpI;
01613     }
01614   }
01615 
01616   for (; I != E; ++I)
01617     if (isa<StructType>(*I)) {
01618       Out << ".field" << cast<ConstantUInt>(I.getOperand())->getValue();
01619     } else {
01620       Out << "[";
01621       writeOperand(I.getOperand());
01622       Out << "]";
01623     }
01624 }
01625 
01626 void CWriter::visitLoadInst(LoadInst &I) {
01627   Out << "*";
01628   writeOperand(I.getOperand(0));
01629 }
01630 
01631 void CWriter::visitStoreInst(StoreInst &I) {
01632   Out << "*";
01633   writeOperand(I.getPointerOperand());
01634   Out << " = ";
01635   writeOperand(I.getOperand(0));
01636 }
01637 
01638 void CWriter::visitGetElementPtrInst(GetElementPtrInst &I) {
01639   Out << "&";
01640   printIndexingExpression(I.getPointerOperand(), gep_type_begin(I),
01641                           gep_type_end(I));
01642 }
01643 
01644 void CWriter::visitVANextInst(VANextInst &I) {
01645   Out << Mang->getValueName(I.getOperand(0));
01646   Out << ";  va_arg(*(va_list*)&" << Mang->getValueName(&I) << ", ";
01647   printType(Out, I.getArgType());
01648   Out << ")";  
01649 }
01650 
01651 void CWriter::visitVAArgInst(VAArgInst &I) {
01652   Out << "0;\n";
01653   Out << "{ va_list Tmp; va_copy(Tmp, *(va_list*)&";
01654   writeOperand(I.getOperand(0));
01655   Out << ");\n  " << Mang->getValueName(&I) << " = va_arg(Tmp, ";
01656   printType(Out, I.getType());
01657   Out << ");\n  va_end(Tmp); }";
01658 }
01659 
01660 //===----------------------------------------------------------------------===//
01661 //                       External Interface declaration
01662 //===----------------------------------------------------------------------===//
01663 
01664 bool CTargetMachine::addPassesToEmitAssembly(PassManager &PM, std::ostream &o) {
01665   PM.add(createLowerGCPass());
01666   PM.add(createLowerAllocationsPass());
01667   PM.add(createLowerInvokePass());
01668   PM.add(new CBackendNameAllUsedStructs());
01669   PM.add(new CWriter(o, getIntrinsicLowering()));
01670   return false;
01671 }
01672 
01673 // vim: sw=2