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