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