Fix typeo
[oota-llvm.git] / lib / Target / CBackend / Writer.cpp
1 //===-- Writer.cpp - Library for converting LLVM code to C ----------------===//
2 //
3 // This library converts LLVM code to C code, compilable by GCC.
4 //
5 //===----------------------------------------------------------------------===//
6
7 #include "llvm/Assembly/CWriter.h"
8 #include "llvm/Constants.h"
9 #include "llvm/DerivedTypes.h"
10 #include "llvm/Module.h"
11 #include "llvm/Instructions.h"
12 #include "llvm/Pass.h"
13 #include "llvm/SymbolTable.h"
14 #include "llvm/Intrinsics.h"
15 #include "llvm/SlotCalculator.h"
16 #include "llvm/Analysis/FindUsedTypes.h"
17 #include "llvm/Analysis/ConstantsScanner.h"
18 #include "llvm/Support/InstVisitor.h"
19 #include "llvm/Support/InstIterator.h"
20 #include "Support/StringExtras.h"
21 #include "Support/STLExtras.h"
22 #include <algorithm>
23 #include <set>
24 #include <sstream>
25
26 namespace {
27   class CWriter : public Pass, public InstVisitor<CWriter> {
28     std::ostream &Out; 
29     SlotCalculator *Table;
30     const Module *TheModule;
31     std::map<const Type *, std::string> TypeNames;
32     std::set<const Value*> MangledGlobals;
33     bool needsMalloc;
34
35     std::map<const ConstantFP *, unsigned> FPConstantMap;
36   public:
37     CWriter(std::ostream &o) : Out(o) {}
38
39     void getAnalysisUsage(AnalysisUsage &AU) const {
40       AU.setPreservesAll();
41       AU.addRequired<FindUsedTypes>();
42     }
43
44     virtual bool run(Module &M) {
45       // Initialize
46       Table = new SlotCalculator(&M, false);
47       TheModule = &M;
48
49       // Ensure that all structure types have names...
50       bool Changed = nameAllUsedStructureTypes(M);
51
52       // Run...
53       printModule(&M);
54
55       // Free memory...
56       delete Table;
57       TypeNames.clear();
58       MangledGlobals.clear();
59       return false;
60     }
61
62     std::ostream &printType(std::ostream &Out, const Type *Ty,
63                             const std::string &VariableName = "",
64                             bool IgnoreName = false, bool namedContext = true);
65
66     void writeOperand(Value *Operand);
67     void writeOperandInternal(Value *Operand);
68
69     std::string getValueName(const Value *V);
70
71   private :
72     bool nameAllUsedStructureTypes(Module &M);
73     void printModule(Module *M);
74     void printSymbolTable(const SymbolTable &ST);
75     void printContainedStructs(const Type *Ty, std::set<const StructType *> &);
76     void printFunctionSignature(const Function *F, bool Prototype);
77
78     void printFunction(Function *);
79
80     void printConstant(Constant *CPV);
81     void printConstantArray(ConstantArray *CPA);
82
83     // isInlinableInst - Attempt to inline instructions into their uses to build
84     // trees as much as possible.  To do this, we have to consistently decide
85     // what is acceptable to inline, so that variable declarations don't get
86     // printed and an extra copy of the expr is not emitted.
87     //
88     static bool isInlinableInst(const Instruction &I) {
89       // Must be an expression, must be used exactly once.  If it is dead, we
90       // emit it inline where it would go.
91       if (I.getType() == Type::VoidTy || I.use_size() != 1 ||
92           isa<TerminatorInst>(I) || isa<CallInst>(I) || isa<PHINode>(I) || 
93           isa<LoadInst>(I)) // Don't inline a load across a store!
94         return false;
95
96       // Only inline instruction it it's use is in the same BB as the inst.
97       return I.getParent() == cast<Instruction>(I.use_back())->getParent();
98     }
99
100     // Instruction visitation functions
101     friend class InstVisitor<CWriter>;
102
103     void visitReturnInst(ReturnInst &I);
104     void visitBranchInst(BranchInst &I);
105     void visitSwitchInst(SwitchInst &I);
106
107     void visitPHINode(PHINode &I);
108     void visitBinaryOperator(Instruction &I);
109
110     void visitCastInst (CastInst &I);
111     void visitCallInst (CallInst &I);
112     void visitShiftInst(ShiftInst &I) { visitBinaryOperator(I); }
113
114     void visitMallocInst(MallocInst &I);
115     void visitAllocaInst(AllocaInst &I);
116     void visitFreeInst  (FreeInst   &I);
117     void visitLoadInst  (LoadInst   &I);
118     void visitStoreInst (StoreInst  &I);
119     void visitGetElementPtrInst(GetElementPtrInst &I);
120     void visitVarArgInst(VarArgInst &I);
121
122     void visitInstruction(Instruction &I) {
123       std::cerr << "C Writer does not know about " << I;
124       abort();
125     }
126
127     void outputLValue(Instruction *I) {
128       Out << "  " << getValueName(I) << " = ";
129     }
130     void printBranchToBlock(BasicBlock *CurBlock, BasicBlock *SuccBlock,
131                             unsigned Indent);
132     void printIndexingExpression(Value *Ptr, User::op_iterator I,
133                                  User::op_iterator E);
134   };
135 }
136
137 // We dont want identifier names with ., space, -  in them. 
138 // So we replace them with _
139 static std::string makeNameProper(std::string x) {
140   std::string tmp;
141   for (std::string::iterator sI = x.begin(), sEnd = x.end(); sI != sEnd; sI++)
142     switch (*sI) {
143     case '.': tmp += "d_"; break;
144     case ' ': tmp += "s_"; break;
145     case '-': tmp += "D_"; break;
146     default:  tmp += *sI;
147     }
148
149   return tmp;
150 }
151
152 std::string CWriter::getValueName(const Value *V) {
153   if (V->hasName()) {              // Print out the label if it exists...
154     if (isa<GlobalValue>(V) &&     // Do not mangle globals...
155         (cast<GlobalValue>(V)->hasExternalLinkage() &&// Unless it's internal or
156          !MangledGlobals.count(V))) // Unless the name would collide if we don't
157       return makeNameProper(V->getName());
158
159     return "l" + utostr(V->getType()->getUniqueID()) + "_" +
160            makeNameProper(V->getName());      
161   }
162
163   int Slot = Table->getValSlot(V);
164   assert(Slot >= 0 && "Invalid value!");
165   return "ltmp_" + itostr(Slot) + "_" + utostr(V->getType()->getUniqueID());
166 }
167
168 // A pointer type should not use parens around *'s alone, e.g., (**)
169 inline bool ptrTypeNameNeedsParens(const std::string &NameSoFar) {
170   return (NameSoFar.find_last_not_of('*') != std::string::npos);
171 }
172
173 // Pass the Type* and the variable name and this prints out the variable
174 // declaration.
175 //
176 std::ostream &CWriter::printType(std::ostream &Out, const Type *Ty,
177                                  const std::string &NameSoFar,
178                                  bool IgnoreName, bool namedContext) {
179   if (Ty->isPrimitiveType())
180     switch (Ty->getPrimitiveID()) {
181     case Type::VoidTyID:   return Out << "void "               << NameSoFar;
182     case Type::BoolTyID:   return Out << "bool "               << NameSoFar;
183     case Type::UByteTyID:  return Out << "unsigned char "      << NameSoFar;
184     case Type::SByteTyID:  return Out << "signed char "        << NameSoFar;
185     case Type::UShortTyID: return Out << "unsigned short "     << NameSoFar;
186     case Type::ShortTyID:  return Out << "short "              << NameSoFar;
187     case Type::UIntTyID:   return Out << "unsigned "           << NameSoFar;
188     case Type::IntTyID:    return Out << "int "                << NameSoFar;
189     case Type::ULongTyID:  return Out << "unsigned long long " << NameSoFar;
190     case Type::LongTyID:   return Out << "signed long long "   << NameSoFar;
191     case Type::FloatTyID:  return Out << "float "              << NameSoFar;
192     case Type::DoubleTyID: return Out << "double "             << NameSoFar;
193     default :
194       std::cerr << "Unknown primitive type: " << Ty << "\n";
195       abort();
196     }
197   
198   // Check to see if the type is named.
199   if (!IgnoreName || isa<OpaqueType>(Ty)) {
200     std::map<const Type *, std::string>::iterator I = TypeNames.find(Ty);
201     if (I != TypeNames.end()) {
202       return Out << I->second << " " << NameSoFar;
203     }
204   }
205
206   switch (Ty->getPrimitiveID()) {
207   case Type::FunctionTyID: {
208     const FunctionType *MTy = cast<FunctionType>(Ty);
209     std::stringstream FunctionInards; 
210     FunctionInards << " (" << NameSoFar << ") (";
211     for (FunctionType::ParamTypes::const_iterator
212            I = MTy->getParamTypes().begin(),
213            E = MTy->getParamTypes().end(); I != E; ++I) {
214       if (I != MTy->getParamTypes().begin())
215         FunctionInards << ", ";
216       printType(FunctionInards, *I, "");
217     }
218     if (MTy->isVarArg()) {
219       if (!MTy->getParamTypes().empty()) 
220         FunctionInards << ", ...";
221     } else if (MTy->getParamTypes().empty()) {
222       FunctionInards << "void";
223     }
224     FunctionInards << ")";
225     std::string tstr = FunctionInards.str();
226     printType(Out, MTy->getReturnType(), tstr);
227     return Out;
228   }
229   case Type::StructTyID: {
230     const StructType *STy = cast<StructType>(Ty);
231     Out << NameSoFar + " {\n";
232     unsigned Idx = 0;
233     for (StructType::ElementTypes::const_iterator
234            I = STy->getElementTypes().begin(),
235            E = STy->getElementTypes().end(); I != E; ++I) {
236       Out << "  ";
237       printType(Out, *I, "field" + utostr(Idx++));
238       Out << ";\n";
239     }
240     return Out << "}";
241   }  
242
243   case Type::PointerTyID: {
244     const PointerType *PTy = cast<PointerType>(Ty);
245     std::string ptrName = "*" + NameSoFar;
246
247     // Do not need parens around "* NameSoFar" if NameSoFar consists only
248     // of zero or more '*' chars *and* this is not an unnamed pointer type
249     // such as the result type in a cast statement.  Otherwise, enclose in ( ).
250     if (ptrTypeNameNeedsParens(NameSoFar) || !namedContext || 
251         PTy->getElementType()->getPrimitiveID() == Type::ArrayTyID)
252       ptrName = "(" + ptrName + ")";    // 
253
254     return printType(Out, PTy->getElementType(), ptrName);
255   }Out <<"--";
256
257   case Type::ArrayTyID: {
258     const ArrayType *ATy = cast<ArrayType>(Ty);
259     unsigned NumElements = ATy->getNumElements();
260     return printType(Out, ATy->getElementType(),
261                      NameSoFar + "[" + utostr(NumElements) + "]");
262   }
263
264   case Type::OpaqueTyID: {
265     static int Count = 0;
266     std::string TyName = "struct opaque_" + itostr(Count++);
267     assert(TypeNames.find(Ty) == TypeNames.end());
268     TypeNames[Ty] = TyName;
269     return Out << TyName << " " << NameSoFar;
270   }
271   default:
272     assert(0 && "Unhandled case in getTypeProps!");
273     abort();
274   }
275
276   return Out;
277 }
278
279 void CWriter::printConstantArray(ConstantArray *CPA) {
280
281   // As a special case, print the array as a string if it is an array of
282   // ubytes or an array of sbytes with positive values.
283   // 
284   const Type *ETy = CPA->getType()->getElementType();
285   bool isString = (ETy == Type::SByteTy || ETy == Type::UByteTy);
286
287   // Make sure the last character is a null char, as automatically added by C
288   if (isString && (CPA->getNumOperands() == 0 ||
289                    !cast<Constant>(*(CPA->op_end()-1))->isNullValue()))
290     isString = false;
291   
292   if (isString) {
293     Out << "\"";
294     // Keep track of whether the last number was a hexadecimal escape
295     bool LastWasHex = false;
296
297     // Do not include the last character, which we know is null
298     for (unsigned i = 0, e = CPA->getNumOperands()-1; i != e; ++i) {
299       unsigned char C = (ETy == Type::SByteTy) ?
300         (unsigned char)cast<ConstantSInt>(CPA->getOperand(i))->getValue() :
301         (unsigned char)cast<ConstantUInt>(CPA->getOperand(i))->getValue();
302       
303       // Print it out literally if it is a printable character.  The only thing
304       // to be careful about is when the last letter output was a hex escape
305       // code, in which case we have to be careful not to print out hex digits
306       // explicitly (the C compiler thinks it is a continuation of the previous
307       // character, sheesh...)
308       //
309       if (isprint(C) && (!LastWasHex || !isxdigit(C))) {
310         LastWasHex = false;
311         if (C == '"' || C == '\\')
312           Out << "\\" << C;
313         else
314           Out << C;
315       } else {
316         LastWasHex = false;
317         switch (C) {
318         case '\n': Out << "\\n"; break;
319         case '\t': Out << "\\t"; break;
320         case '\r': Out << "\\r"; break;
321         case '\v': Out << "\\v"; break;
322         case '\a': Out << "\\a"; break;
323         case '\"': Out << "\\\""; break;
324         case '\'': Out << "\\\'"; break;           
325         default:
326           Out << "\\x";
327           Out << (char)(( C/16  < 10) ? ( C/16 +'0') : ( C/16 -10+'A'));
328           Out << (char)(((C&15) < 10) ? ((C&15)+'0') : ((C&15)-10+'A'));
329           LastWasHex = true;
330           break;
331         }
332       }
333     }
334     Out << "\"";
335   } else {
336     Out << "{";
337     if (CPA->getNumOperands()) {
338       Out << " ";
339       printConstant(cast<Constant>(CPA->getOperand(0)));
340       for (unsigned i = 1, e = CPA->getNumOperands(); i != e; ++i) {
341         Out << ", ";
342         printConstant(cast<Constant>(CPA->getOperand(i)));
343       }
344     }
345     Out << " }";
346   }
347 }
348
349
350 // printConstant - The LLVM Constant to C Constant converter.
351 void CWriter::printConstant(Constant *CPV) {
352   if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(CPV)) {
353     switch (CE->getOpcode()) {
354     case Instruction::Cast:
355       Out << "((";
356       printType(Out, CPV->getType());
357       Out << ")";
358       printConstant(CE->getOperand(0));
359       Out << ")";
360       return;
361
362     case Instruction::GetElementPtr:
363       Out << "(&(";
364       printIndexingExpression(CE->getOperand(0),
365                               CPV->op_begin()+1, CPV->op_end());
366       Out << "))";
367       return;
368     case Instruction::Add:
369       Out << "(";
370       printConstant(CE->getOperand(0));
371       Out << " + ";
372       printConstant(CE->getOperand(1));
373       Out << ")";
374       return;
375     case Instruction::Sub:
376       Out << "(";
377       printConstant(CE->getOperand(0));
378       Out << " - ";
379       printConstant(CE->getOperand(1));
380       Out << ")";
381       return;
382
383     default:
384       std::cerr << "CWriter Error: Unhandled constant expression: "
385                 << CE << "\n";
386       abort();
387     }
388   }
389
390   switch (CPV->getType()->getPrimitiveID()) {
391   case Type::BoolTyID:
392     Out << (CPV == ConstantBool::False ? "0" : "1"); break;
393   case Type::SByteTyID:
394   case Type::ShortTyID:
395     Out << cast<ConstantSInt>(CPV)->getValue(); break;
396   case Type::IntTyID:
397     if ((int)cast<ConstantSInt>(CPV)->getValue() == (int)0x80000000)
398       Out << "((int)0x80000000)";   // Handle MININT specially to avoid warning
399     else
400       Out << cast<ConstantSInt>(CPV)->getValue();
401     break;
402
403   case Type::LongTyID:
404     Out << cast<ConstantSInt>(CPV)->getValue() << "ll"; break;
405
406   case Type::UByteTyID:
407   case Type::UShortTyID:
408     Out << cast<ConstantUInt>(CPV)->getValue(); break;
409   case Type::UIntTyID:
410     Out << cast<ConstantUInt>(CPV)->getValue() << "u"; break;
411   case Type::ULongTyID:
412     Out << cast<ConstantUInt>(CPV)->getValue() << "ull"; break;
413
414   case Type::FloatTyID:
415   case Type::DoubleTyID: {
416     ConstantFP *FPC = cast<ConstantFP>(CPV);
417     std::map<const ConstantFP*, unsigned>::iterator I = FPConstantMap.find(FPC);
418     if (I != FPConstantMap.end()) {
419       // Because of FP precision problems we must load from a stack allocated
420       // value that holds the value in hex.
421       Out << "(*(" << (FPC->getType() == Type::FloatTy ? "float" : "double")
422           << "*)&FloatConstant" << I->second << ")";
423     } else {
424       Out << FPC->getValue();
425     }
426     break;
427   }
428
429   case Type::ArrayTyID:
430     printConstantArray(cast<ConstantArray>(CPV));
431     break;
432
433   case Type::StructTyID: {
434     Out << "{";
435     if (CPV->getNumOperands()) {
436       Out << " ";
437       printConstant(cast<Constant>(CPV->getOperand(0)));
438       for (unsigned i = 1, e = CPV->getNumOperands(); i != e; ++i) {
439         Out << ", ";
440         printConstant(cast<Constant>(CPV->getOperand(i)));
441       }
442     }
443     Out << " }";
444     break;
445   }
446
447   case Type::PointerTyID:
448     if (isa<ConstantPointerNull>(CPV)) {
449       Out << "((";
450       printType(Out, CPV->getType());
451       Out << ")/*NULL*/0)";
452       break;
453     } else if (ConstantPointerRef *CPR = dyn_cast<ConstantPointerRef>(CPV)) {
454       writeOperand(CPR->getValue());
455       break;
456     }
457     // FALL THROUGH
458   default:
459     std::cerr << "Unknown constant type: " << CPV << "\n";
460     abort();
461   }
462 }
463
464 void CWriter::writeOperandInternal(Value *Operand) {
465   if (Instruction *I = dyn_cast<Instruction>(Operand))
466     if (isInlinableInst(*I)) {
467       // Should we inline this instruction to build a tree?
468       Out << "(";
469       visit(*I);
470       Out << ")";    
471       return;
472     }
473   
474   if (Operand->hasName()) {  
475     Out << getValueName(Operand);
476   } else if (Constant *CPV = dyn_cast<Constant>(Operand)) {
477     printConstant(CPV); 
478   } else {
479     int Slot = Table->getValSlot(Operand);
480     assert(Slot >= 0 && "Malformed LLVM!");
481     Out << "ltmp_" << Slot << "_" << Operand->getType()->getUniqueID();
482   }
483 }
484
485 void CWriter::writeOperand(Value *Operand) {
486   if (isa<GlobalVariable>(Operand))
487     Out << "(&";  // Global variables are references as their addresses by llvm
488
489   writeOperandInternal(Operand);
490
491   if (isa<GlobalVariable>(Operand))
492     Out << ")";
493 }
494
495 // nameAllUsedStructureTypes - If there are structure types in the module that
496 // are used but do not have names assigned to them in the symbol table yet then
497 // we assign them names now.
498 //
499 bool CWriter::nameAllUsedStructureTypes(Module &M) {
500   // Get a set of types that are used by the program...
501   std::set<const Type *> UT = getAnalysis<FindUsedTypes>().getTypes();
502
503   // Loop over the module symbol table, removing types from UT that are already
504   // named.
505   //
506   SymbolTable &MST = M.getSymbolTable();
507   if (MST.find(Type::TypeTy) != MST.end())
508     for (SymbolTable::type_iterator I = MST.type_begin(Type::TypeTy),
509            E = MST.type_end(Type::TypeTy); I != E; ++I)
510       UT.erase(cast<Type>(I->second));
511
512   // UT now contains types that are not named.  Loop over it, naming structure
513   // types.
514   //
515   bool Changed = false;
516   for (std::set<const Type *>::const_iterator I = UT.begin(), E = UT.end();
517        I != E; ++I)
518     if (const StructType *ST = dyn_cast<StructType>(*I)) {
519       ((Value*)ST)->setName("unnamed", &MST);
520       Changed = true;
521     }
522   return Changed;
523 }
524
525 static void generateAllocaDecl(std::ostream& Out) {
526   // On SunOS, we need to insert the alloca macro & proto for the builtin.
527   Out << "#ifdef sun\n"
528       << "extern void *__builtin_alloca(unsigned long);\n"
529       << "#define alloca(x) __builtin_alloca(x)\n"
530       << "#else\n"
531       << "#include <alloca.h>\n"
532       << "#endif\n\n";
533 }
534
535 void CWriter::printModule(Module *M) {
536   // Calculate which global values have names that will collide when we throw
537   // away type information.
538   {  // Scope to delete the FoundNames set when we are done with it...
539     std::set<std::string> FoundNames;
540     for (Module::iterator I = M->begin(), E = M->end(); I != E; ++I)
541       if (I->hasName())                      // If the global has a name...
542         if (FoundNames.count(I->getName()))  // And the name is already used
543           MangledGlobals.insert(I);          // Mangle the name
544         else
545           FoundNames.insert(I->getName());   // Otherwise, keep track of name
546
547     for (Module::giterator I = M->gbegin(), E = M->gend(); I != E; ++I)
548       if (I->hasName())                      // If the global has a name...
549         if (FoundNames.count(I->getName()))  // And the name is already used
550           MangledGlobals.insert(I);          // Mangle the name
551         else
552           FoundNames.insert(I->getName());   // Otherwise, keep track of name
553   }
554
555   // get declaration for alloca
556   Out << "/* Provide Declarations */\n";
557   generateAllocaDecl(Out);
558   Out << "#include <stdarg.h>\n";
559   Out << "#include <setjmp.h>\n";
560   
561   // Provide a definition for `bool' if not compiling with a C++ compiler.
562   Out << "\n"
563       << "#ifndef __cplusplus\ntypedef unsigned char bool;\n#endif\n"
564     
565       << "\n\n/* Support for floating point constants */\n"
566       << "typedef unsigned long long ConstantDoubleTy;\n"
567       << "typedef unsigned int        ConstantFloatTy;\n"
568     
569       << "\n\n/* Global Declarations */\n";
570
571   // First output all the declarations for the program, because C requires
572   // Functions & globals to be declared before they are used.
573   //
574
575   // Loop over the symbol table, emitting all named constants...
576   printSymbolTable(M->getSymbolTable());
577
578   // Global variable declarations...
579   if (!M->gempty()) {
580     Out << "\n/* External Global Variable Declarations */\n";
581     for (Module::giterator I = M->gbegin(), E = M->gend(); I != E; ++I) {
582       if (I->hasExternalLinkage()) {
583         Out << "extern ";
584         printType(Out, I->getType()->getElementType(), getValueName(I));
585         Out << ";\n";
586       }
587     }
588   }
589
590   // Function declarations
591   if (!M->empty()) {
592     Out << "\n/* Function Declarations */\n";
593     needsMalloc = true;
594     for (Module::iterator I = M->begin(), E = M->end(); I != E; ++I) {
595       // If the function is external and the name collides don't print it.
596       // Sometimes the bytecode likes to have multiple "declarations" for
597       // external functions
598       if ((I->hasInternalLinkage() || !MangledGlobals.count(I)) &&
599           !I->getIntrinsicID()) {
600         printFunctionSignature(I, true);
601         Out << ";\n";
602       }
603     }
604   }
605
606   // Print Malloc prototype if needed
607   if (needsMalloc){
608     Out << "\n/* Malloc to make sun happy */\n";
609     Out << "extern void * malloc(size_t);\n\n";
610   }
611
612   // Output the global variable declerations
613   if (!M->gempty()) {
614     Out << "\n\n/* Global Variable Declerations */\n";
615     for (Module::giterator I = M->gbegin(), E = M->gend(); I != E; ++I)
616       if (!I->isExternal()) {
617         Out << "extern ";
618         printType(Out, I->getType()->getElementType(), getValueName(I));
619       
620         Out << ";\n";
621       }
622   }
623
624   
625   // Output the global variable definitions and contents...
626   if (!M->gempty()) {
627     Out << "\n\n/* Global Variable Definitions and Initialization */\n";
628     for (Module::giterator I = M->gbegin(), E = M->gend(); I != E; ++I)
629       if (!I->isExternal()) {
630         if (I->hasInternalLinkage())
631           Out << "static ";
632         printType(Out, I->getType()->getElementType(), getValueName(I));
633         if (!I->getInitializer()->isNullValue()) {
634           Out << " = " ;
635           writeOperand(I->getInitializer());
636         }
637         Out << ";\n";
638       }
639   }
640
641   // Output all of the functions...
642   if (!M->empty()) {
643     Out << "\n\n/* Function Bodies */\n";
644     for (Module::iterator I = M->begin(), E = M->end(); I != E; ++I)
645       printFunction(I);
646   }
647 }
648
649
650 /// printSymbolTable - Run through symbol table looking for type names.  If a
651 /// type name is found, emit it's declaration...
652 ///
653 void CWriter::printSymbolTable(const SymbolTable &ST) {
654   // If there are no type names, exit early.
655   if (ST.find(Type::TypeTy) == ST.end())
656     return;
657
658   // We are only interested in the type plane of the symbol table...
659   SymbolTable::type_const_iterator I   = ST.type_begin(Type::TypeTy);
660   SymbolTable::type_const_iterator End = ST.type_end(Type::TypeTy);
661   
662   // Print out forward declarations for structure types before anything else!
663   Out << "/* Structure forward decls */\n";
664   for (; I != End; ++I)
665     if (const Type *STy = dyn_cast<StructType>(I->second)) {
666       std::string Name = "struct l_" + makeNameProper(I->first);
667       Out << Name << ";\n";
668       TypeNames.insert(std::make_pair(STy, Name));
669     }
670
671   Out << "\n";
672
673   // Now we can print out typedefs...
674   Out << "/* Typedefs */\n";
675   for (I = ST.type_begin(Type::TypeTy); I != End; ++I) {
676     const Type *Ty = cast<Type>(I->second);
677     std::string Name = "l_" + makeNameProper(I->first);
678     Out << "typedef ";
679     printType(Out, Ty, Name);
680     Out << ";\n";
681   }
682
683   Out << "\n";
684
685   // Keep track of which structures have been printed so far...
686   std::set<const StructType *> StructPrinted;
687
688   // Loop over all structures then push them into the stack so they are
689   // printed in the correct order.
690   //
691   Out << "/* Structure contents */\n";
692   for (I = ST.type_begin(Type::TypeTy); I != End; ++I)
693     if (const StructType *STy = dyn_cast<StructType>(I->second))
694       printContainedStructs(STy, StructPrinted);
695 }
696
697 // Push the struct onto the stack and recursively push all structs
698 // this one depends on.
699 void CWriter::printContainedStructs(const Type *Ty,
700                                     std::set<const StructType*> &StructPrinted){
701   if (const StructType *STy = dyn_cast<StructType>(Ty)){
702     //Check to see if we have already printed this struct
703     if (StructPrinted.count(STy) == 0) {
704       // Print all contained types first...
705       for (StructType::ElementTypes::const_iterator
706              I = STy->getElementTypes().begin(),
707              E = STy->getElementTypes().end(); I != E; ++I) {
708         const Type *Ty1 = I->get();
709         if (isa<StructType>(Ty1) || isa<ArrayType>(Ty1))
710           printContainedStructs(*I, StructPrinted);
711       }
712       
713       //Print structure type out..
714       StructPrinted.insert(STy);
715       std::string Name = TypeNames[STy];  
716       printType(Out, STy, Name, true);
717       Out << ";\n\n";
718     }
719
720     // If it is an array, check contained types and continue
721   } else if (const ArrayType *ATy = dyn_cast<ArrayType>(Ty)){
722     const Type *Ty1 = ATy->getElementType();
723     if (isa<StructType>(Ty1) || isa<ArrayType>(Ty1))
724       printContainedStructs(Ty1, StructPrinted);
725   }
726 }
727
728
729 void CWriter::printFunctionSignature(const Function *F, bool Prototype) {
730   // If the program provides it's own malloc prototype we don't need
731   // to include the general one.  
732   if (getValueName(F) == "malloc")
733     needsMalloc = false;
734   if (F->hasInternalLinkage()) Out << "static ";  
735   // Loop over the arguments, printing them...
736   const FunctionType *FT = cast<FunctionType>(F->getFunctionType());
737   
738   std::stringstream FunctionInards; 
739     
740   // Print out the name...
741   FunctionInards << getValueName(F) << "(";
742     
743   if (!F->isExternal()) {
744     if (!F->aempty()) {
745       std::string ArgName;
746       if (F->abegin()->hasName() || !Prototype)
747         ArgName = getValueName(F->abegin());
748       printType(FunctionInards, F->afront().getType(), ArgName);
749       for (Function::const_aiterator I = ++F->abegin(), E = F->aend();
750            I != E; ++I) {
751         FunctionInards << ", ";
752         if (I->hasName() || !Prototype)
753           ArgName = getValueName(I);
754         else 
755           ArgName = "";
756         printType(FunctionInards, I->getType(), ArgName);
757       }
758     }
759   } else {
760     // Loop over the arguments, printing them...
761     for (FunctionType::ParamTypes::const_iterator I = 
762            FT->getParamTypes().begin(),
763            E = FT->getParamTypes().end(); I != E; ++I) {
764       if (I != FT->getParamTypes().begin()) FunctionInards << ", ";
765       printType(FunctionInards, *I);
766     }
767   }
768
769   // Finish printing arguments... if this is a vararg function, print the ...,
770   // unless there are no known types, in which case, we just emit ().
771   //
772   if (FT->isVarArg() && !FT->getParamTypes().empty()) {
773     if (FT->getParamTypes().size()) FunctionInards << ", ";
774     FunctionInards << "...";  // Output varargs portion of signature!
775   }
776   FunctionInards << ")";
777   // Print out the return type and the entire signature for that matter
778   printType(Out, F->getReturnType(), FunctionInards.str());
779   
780 }
781
782
783 void CWriter::printFunction(Function *F) {
784   if (F->isExternal()) return;
785
786   Table->incorporateFunction(F);
787
788   printFunctionSignature(F, false);
789   Out << " {\n";
790
791   // print local variable information for the function
792   for (inst_iterator I = inst_begin(F), E = inst_end(F); I != E; ++I)
793     if ((*I)->getType() != Type::VoidTy && !isInlinableInst(**I)) {
794       Out << "  ";
795       printType(Out, (*I)->getType(), getValueName(*I));
796       Out << ";\n";
797
798       if (isa<PHINode>(*I)) {  // Print out PHI node temporaries as well...
799         Out << "  ";
800         printType(Out, (*I)->getType(), getValueName(*I)+"__PHI_TEMPORARY");
801         Out << ";\n";
802       }
803     }
804
805   Out << "\n";
806
807   // Scan the function for floating point constants.  If any FP constant is used
808   // in the function, we want to redirect it here so that we do not depend on
809   // the precision of the printed form.
810   //
811   unsigned FPCounter = 0;
812   for (constant_iterator I = constant_begin(F), E = constant_end(F); I != E;++I)
813     if (const ConstantFP *FPC = dyn_cast<ConstantFP>(*I))
814       if (FPConstantMap.find(FPC) == FPConstantMap.end()) {
815         double Val = FPC->getValue();
816         
817         FPConstantMap[FPC] = FPCounter;  // Number the FP constants
818
819         if (FPC->getType() == Type::DoubleTy)
820           Out << "  const ConstantDoubleTy FloatConstant" << FPCounter++
821               << " = 0x" << std::hex << *(unsigned long long*)&Val << std::dec
822               << ";    /* " << Val << " */\n";
823         else if (FPC->getType() == Type::FloatTy) {
824           float fVal = Val;
825           Out << "  const ConstantFloatTy FloatConstant" << FPCounter++
826               << " = 0x" << std::hex << *(unsigned*)&fVal << std::dec
827               << ";    /* " << Val << " */\n";
828         } else
829           assert(0 && "Unknown float type!");
830       }
831
832   Out << "\n";
833  
834   // print the basic blocks
835   for (Function::iterator BB = F->begin(), E = F->end(); BB != E; ++BB) {
836     BasicBlock *Prev = BB->getPrev();
837
838     // Don't print the label for the basic block if there are no uses, or if the
839     // only terminator use is the precessor basic block's terminator.  We have
840     // to scan the use list because PHI nodes use basic blocks too but do not
841     // require a label to be generated.
842     //
843     bool NeedsLabel = false;
844     for (Value::use_iterator UI = BB->use_begin(), UE = BB->use_end();
845          UI != UE; ++UI)
846       if (TerminatorInst *TI = dyn_cast<TerminatorInst>(*UI))
847         if (TI != Prev->getTerminator() ||
848             isa<SwitchInst>(Prev->getTerminator())) {
849           NeedsLabel = true;
850           break;        
851         }
852
853     if (NeedsLabel) Out << getValueName(BB) << ":\n";
854
855     // Output all of the instructions in the basic block...
856     for (BasicBlock::iterator II = BB->begin(), E = --BB->end(); II != E; ++II){
857       if (!isInlinableInst(*II)) {
858         if (II->getType() != Type::VoidTy)
859           outputLValue(II);
860         else
861           Out << "  ";
862         visit(*II);
863         Out << ";\n";
864       }
865     }
866
867     // Don't emit prefix or suffix for the terminator...
868     visit(*BB->getTerminator());
869   }
870   
871   Out << "}\n\n";
872   Table->purgeFunction();
873   FPConstantMap.clear();
874 }
875
876 // Specific Instruction type classes... note that all of the casts are
877 // neccesary because we use the instruction classes as opaque types...
878 //
879 void CWriter::visitReturnInst(ReturnInst &I) {
880   // Don't output a void return if this is the last basic block in the function
881   if (I.getNumOperands() == 0 && 
882       &*--I.getParent()->getParent()->end() == I.getParent() &&
883       !I.getParent()->size() == 1) {
884     return;
885   }
886
887   Out << "  return";
888   if (I.getNumOperands()) {
889     Out << " ";
890     writeOperand(I.getOperand(0));
891   }
892   Out << ";\n";
893 }
894
895 void CWriter::visitSwitchInst(SwitchInst &SI) {
896   Out << "  switch (";
897   writeOperand(SI.getOperand(0));
898   Out << ") {\n  default:\n";
899   printBranchToBlock(SI.getParent(), SI.getDefaultDest(), 2);
900   Out << ";\n";
901   for (unsigned i = 2, e = SI.getNumOperands(); i != e; i += 2) {
902     Out << "  case ";
903     writeOperand(SI.getOperand(i));
904     Out << ":\n";
905     BasicBlock *Succ = cast<BasicBlock>(SI.getOperand(i+1));
906     printBranchToBlock(SI.getParent(), Succ, 2);
907     if (Succ == SI.getParent()->getNext())
908       Out << "    break;\n";
909   }
910   Out << "  }\n";
911 }
912
913
914 static bool isGotoCodeNeccessary(BasicBlock *From, BasicBlock *To) {
915   // If PHI nodes need copies, we need the copy code...
916   if (isa<PHINode>(To->front()) ||
917       From->getNext() != To)      // Not directly successor, need goto
918     return true;
919
920   // Otherwise we don't need the code.
921   return false;
922 }
923
924 void CWriter::printBranchToBlock(BasicBlock *CurBB, BasicBlock *Succ,
925                                            unsigned Indent) {
926   for (BasicBlock::iterator I = Succ->begin();
927        PHINode *PN = dyn_cast<PHINode>(I); ++I) {
928     //  now we have to do the printing
929     Out << std::string(Indent, ' ');
930     Out << "  " << getValueName(I) << "__PHI_TEMPORARY = ";
931     writeOperand(PN->getIncomingValue(PN->getBasicBlockIndex(CurBB)));
932     Out << ";   /* for PHI node */\n";
933   }
934
935   if (CurBB->getNext() != Succ) {
936     Out << std::string(Indent, ' ') << "  goto ";
937     writeOperand(Succ);
938     Out << ";\n";
939   }
940 }
941
942 // Brach instruction printing - Avoid printing out a brach to a basic block that
943 // immediately succeeds the current one.
944 //
945 void CWriter::visitBranchInst(BranchInst &I) {
946   if (I.isConditional()) {
947     if (isGotoCodeNeccessary(I.getParent(), I.getSuccessor(0))) {
948       Out << "  if (";
949       writeOperand(I.getCondition());
950       Out << ") {\n";
951       
952       printBranchToBlock(I.getParent(), I.getSuccessor(0), 2);
953       
954       if (isGotoCodeNeccessary(I.getParent(), I.getSuccessor(1))) {
955         Out << "  } else {\n";
956         printBranchToBlock(I.getParent(), I.getSuccessor(1), 2);
957       }
958     } else {
959       // First goto not neccesary, assume second one is...
960       Out << "  if (!";
961       writeOperand(I.getCondition());
962       Out << ") {\n";
963
964       printBranchToBlock(I.getParent(), I.getSuccessor(1), 2);
965     }
966
967     Out << "  }\n";
968   } else {
969     printBranchToBlock(I.getParent(), I.getSuccessor(0), 0);
970   }
971   Out << "\n";
972 }
973
974 // PHI nodes get copied into temporary values at the end of predecessor basic
975 // blocks.  We now need to copy these temporary values into the REAL value for
976 // the PHI.
977 void CWriter::visitPHINode(PHINode &I) {
978   writeOperand(&I);
979   Out << "__PHI_TEMPORARY";
980 }
981
982
983 void CWriter::visitBinaryOperator(Instruction &I) {
984   // binary instructions, shift instructions, setCond instructions.
985   assert(!isa<PointerType>(I.getType()));
986       
987   writeOperand(I.getOperand(0));
988
989   switch (I.getOpcode()) {
990   case Instruction::Add: Out << " + "; break;
991   case Instruction::Sub: Out << " - "; break;
992   case Instruction::Mul: Out << "*"; break;
993   case Instruction::Div: Out << "/"; break;
994   case Instruction::Rem: Out << "%"; break;
995   case Instruction::And: Out << " & "; break;
996   case Instruction::Or: Out << " | "; break;
997   case Instruction::Xor: Out << " ^ "; break;
998   case Instruction::SetEQ: Out << " == "; break;
999   case Instruction::SetNE: Out << " != "; break;
1000   case Instruction::SetLE: Out << " <= "; break;
1001   case Instruction::SetGE: Out << " >= "; break;
1002   case Instruction::SetLT: Out << " < "; break;
1003   case Instruction::SetGT: Out << " > "; break;
1004   case Instruction::Shl : Out << " << "; break;
1005   case Instruction::Shr : Out << " >> "; break;
1006   default: std::cerr << "Invalid operator type!" << I; abort();
1007   }
1008
1009   writeOperand(I.getOperand(1));
1010 }
1011
1012 void CWriter::visitCastInst(CastInst &I) {
1013   if (I.getType() == Type::BoolTy) {
1014     Out << "(";
1015     writeOperand(I.getOperand(0));
1016     Out << " != 0)";
1017     return;
1018   }
1019   Out << "(";
1020   printType(Out, I.getType(), "", /*ignoreName*/false, /*namedContext*/false);
1021   Out << ")";
1022   if (isa<PointerType>(I.getType())&&I.getOperand(0)->getType()->isIntegral() ||
1023       isa<PointerType>(I.getOperand(0)->getType())&&I.getType()->isIntegral()) {
1024     // Avoid "cast to pointer from integer of different size" warnings
1025     Out << "(long)";  
1026   }
1027   
1028   writeOperand(I.getOperand(0));
1029 }
1030
1031 void CWriter::visitCallInst(CallInst &I) {
1032   // Handle intrinsic function calls first...
1033   if (Function *F = I.getCalledFunction())
1034     if (LLVMIntrinsic::ID ID = (LLVMIntrinsic::ID)F->getIntrinsicID()) {
1035       switch (ID) {
1036       default:  assert(0 && "Unknown LLVM intrinsic!");
1037       case LLVMIntrinsic::va_start: 
1038         Out << "va_start((va_list)*";
1039         writeOperand(I.getOperand(1));
1040         Out << ", ";
1041         // Output the last argument to the enclosing function...
1042         writeOperand(&I.getParent()->getParent()->aback());
1043         Out << ")";
1044         return;
1045       case LLVMIntrinsic::va_end:
1046         Out << "va_end((va_list)*";
1047         writeOperand(I.getOperand(1));
1048         Out << ")";
1049         return;
1050       case LLVMIntrinsic::va_copy:
1051         Out << "va_copy((va_list)*";
1052         writeOperand(I.getOperand(1));
1053         Out << ", (va_list)";
1054         writeOperand(I.getOperand(2));
1055         Out << ")";
1056         return;
1057         
1058       case LLVMIntrinsic::setjmp:
1059         Out << "setjmp((jmp_buf)";
1060         writeOperand(I.getOperand(1));
1061         Out << ")";
1062         return;
1063       case LLVMIntrinsic::longjmp:
1064         Out << "longjmp((jmp_buf)";
1065         writeOperand(I.getOperand(1));
1066         Out << ", ";
1067         writeOperand(I.getOperand(2));
1068         Out << ")";
1069         return;
1070       }
1071     }
1072
1073   const PointerType  *PTy   = cast<PointerType>(I.getCalledValue()->getType());
1074   const FunctionType *FTy   = cast<FunctionType>(PTy->getElementType());
1075   const Type         *RetTy = FTy->getReturnType();
1076   
1077   writeOperand(I.getOperand(0));
1078   Out << "(";
1079
1080   if (I.getNumOperands() > 1) {
1081     writeOperand(I.getOperand(1));
1082
1083     for (unsigned op = 2, Eop = I.getNumOperands(); op != Eop; ++op) {
1084       Out << ", ";
1085       writeOperand(I.getOperand(op));
1086     }
1087   }
1088   Out << ")";
1089 }  
1090
1091 void CWriter::visitMallocInst(MallocInst &I) {
1092   Out << "(";
1093   printType(Out, I.getType());
1094   Out << ")malloc(sizeof(";
1095   printType(Out, I.getType()->getElementType());
1096   Out << ")";
1097
1098   if (I.isArrayAllocation()) {
1099     Out << " * " ;
1100     writeOperand(I.getOperand(0));
1101   }
1102   Out << ")";
1103 }
1104
1105 void CWriter::visitAllocaInst(AllocaInst &I) {
1106   Out << "(";
1107   printType(Out, I.getType());
1108   Out << ") alloca(sizeof(";
1109   printType(Out, I.getType()->getElementType());
1110   Out << ")";
1111   if (I.isArrayAllocation()) {
1112     Out << " * " ;
1113     writeOperand(I.getOperand(0));
1114   }
1115   Out << ")";
1116 }
1117
1118 void CWriter::visitFreeInst(FreeInst &I) {
1119   Out << "free(";
1120   writeOperand(I.getOperand(0));
1121   Out << ")";
1122 }
1123
1124 void CWriter::printIndexingExpression(Value *Ptr, User::op_iterator I,
1125                                       User::op_iterator E) {
1126   bool HasImplicitAddress = false;
1127   // If accessing a global value with no indexing, avoid *(&GV) syndrome
1128   if (GlobalValue *V = dyn_cast<GlobalValue>(Ptr)) {
1129     HasImplicitAddress = true;
1130   } else if (ConstantPointerRef *CPR = dyn_cast<ConstantPointerRef>(Ptr)) {
1131     HasImplicitAddress = true;
1132     Ptr = CPR->getValue();         // Get to the global...
1133   }
1134
1135   if (I == E) {
1136     if (!HasImplicitAddress)
1137       Out << "*";  // Implicit zero first argument: '*x' is equivalent to 'x[0]'
1138
1139     writeOperandInternal(Ptr);
1140     return;
1141   }
1142
1143   const Constant *CI = dyn_cast<Constant>(I);
1144   if (HasImplicitAddress && (!CI || !CI->isNullValue()))
1145     Out << "(&";
1146
1147   writeOperandInternal(Ptr);
1148
1149   if (HasImplicitAddress && (!CI || !CI->isNullValue())) {
1150     Out << ")";
1151     HasImplicitAddress = false;  // HIA is only true if we haven't addressed yet
1152   }
1153
1154   assert(!HasImplicitAddress || (CI && CI->isNullValue()) &&
1155          "Can only have implicit address with direct accessing");
1156
1157   if (HasImplicitAddress) {
1158     ++I;
1159   } else if (CI && CI->isNullValue() && I+1 != E) {
1160     // Print out the -> operator if possible...
1161     if ((*(I+1))->getType() == Type::UByteTy) {
1162       Out << (HasImplicitAddress ? "." : "->");
1163       Out << "field" << cast<ConstantUInt>(*(I+1))->getValue();
1164       I += 2;
1165     } 
1166   }
1167
1168   for (; I != E; ++I)
1169     if ((*I)->getType() == Type::LongTy) {
1170       Out << "[";
1171       writeOperand(*I);
1172       Out << "]";
1173     } else {
1174       Out << ".field" << cast<ConstantUInt>(*I)->getValue();
1175     }
1176 }
1177
1178 void CWriter::visitLoadInst(LoadInst &I) {
1179   Out << "*";
1180   writeOperand(I.getOperand(0));
1181 }
1182
1183 void CWriter::visitStoreInst(StoreInst &I) {
1184   Out << "*";
1185   writeOperand(I.getPointerOperand());
1186   Out << " = ";
1187   writeOperand(I.getOperand(0));
1188 }
1189
1190 void CWriter::visitGetElementPtrInst(GetElementPtrInst &I) {
1191   Out << "&";
1192   printIndexingExpression(I.getPointerOperand(), I.idx_begin(), I.idx_end());
1193 }
1194
1195 void CWriter::visitVarArgInst(VarArgInst &I) {
1196   Out << "va_arg((va_list)*";
1197   writeOperand(I.getOperand(0));
1198   Out << ", ";
1199   printType(Out, I.getType(), "", /*ignoreName*/false, /*namedContext*/false);
1200   Out << ")";  
1201 }
1202
1203
1204 //===----------------------------------------------------------------------===//
1205 //                       External Interface declaration
1206 //===----------------------------------------------------------------------===//
1207
1208 Pass *createWriteToCPass(std::ostream &o) { return new CWriter(o); }