* Print structures types correctly
[oota-llvm.git] / lib / Target / CBackend / CBackend.cpp
1 //===-- Writer.cpp - Library for writing C files --------------------------===//
2 //
3 // This library implements the functionality defined in llvm/Assembly/CWriter.h
4 // and CLocalVars.h
5 //
6 // TODO : Recursive types.
7 //
8 //===-----------------------------------------------------------------------==//
9
10 #include "llvm/Assembly/CWriter.h"
11 #include "CLocalVars.h"
12 #include "llvm/SlotCalculator.h"
13 #include "llvm/Constants.h"
14 #include "llvm/DerivedTypes.h"
15 #include "llvm/Module.h"
16 #include "llvm/GlobalVariable.h"
17 #include "llvm/Function.h"
18 #include "llvm/Argument.h"
19 #include "llvm/BasicBlock.h"
20 #include "llvm/iMemory.h"
21 #include "llvm/iTerminators.h"
22 #include "llvm/iPHINode.h"
23 #include "llvm/iOther.h"
24 #include "llvm/iOperators.h"
25 #include "llvm/SymbolTable.h"
26 #include "llvm/Support/InstVisitor.h"
27 #include "Support/StringExtras.h"
28 #include "Support/STLExtras.h"
29
30 #include <algorithm>
31 #include <strstream>
32 using std::string;
33 using std::map;
34 using std::vector;
35 using std::ostream;
36
37 //===-----------------------------------------------------------------------==//
38 //
39 // Implementation of the CLocalVars methods
40
41 // Appends a variable to the LocalVars map if it does not already exist
42 // Also check that the type exists on the map.
43 void CLocalVars::addLocalVar(const Type *t, const string & var) {
44   if (!LocalVars.count(t) || 
45       find(LocalVars[t].begin(), LocalVars[t].end(), var) 
46       == LocalVars[t].end()) {
47       LocalVars[t].push_back(var);
48   } 
49 }
50
51 static std::string getConstStrValue(const Constant* CPV);
52
53
54 static std::string getConstArrayStrValue(const Constant* CPV) {
55   std::string Result;
56   
57   // As a special case, print the array as a string if it is an array of
58   // ubytes or an array of sbytes with positive values.
59   // 
60   const Type *ETy = cast<ArrayType>(CPV->getType())->getElementType();
61   bool isString = (ETy == Type::SByteTy || ETy == Type::UByteTy);
62
63   if (ETy == Type::SByteTy) {
64     for (unsigned i = 0; i < CPV->getNumOperands(); ++i)
65       if (ETy == Type::SByteTy &&
66           cast<ConstantSInt>(CPV->getOperand(i))->getValue() < 0) {
67         isString = false;
68         break;
69       }
70   }
71   if (isString) {
72     // Make sure the last character is a null char, as automatically added by C
73     if (CPV->getNumOperands() == 0 ||
74         !cast<Constant>(*(CPV->op_end()-1))->isNullValue())
75       isString = false;
76   }
77   
78   if (isString) {
79     Result = "\"";
80     // Do not include the last character, which we know is null
81     for (unsigned i = 0, e = CPV->getNumOperands()-1; i != e; ++i) {
82       unsigned char C = (ETy == Type::SByteTy) ?
83         (unsigned char)cast<ConstantSInt>(CPV->getOperand(i))->getValue() :
84         (unsigned char)cast<ConstantUInt>(CPV->getOperand(i))->getValue();
85       
86       if (isprint(C)) {
87         Result += C;
88       } else {
89         switch (C) {
90         case '\n': Result += "\\n"; break;
91         case '\t': Result += "\\t"; break;
92         case '\r': Result += "\\r"; break;
93         case '\v': Result += "\\v"; break;
94         case '\a': Result += "\\a"; break;
95         default:
96           Result += "\\x";
97           Result += ( C/16  < 10) ? ( C/16 +'0') : ( C/16 -10+'A');
98           Result += ((C&15) < 10) ? ((C&15)+'0') : ((C&15)-10+'A');
99           break;
100         }
101       }
102     }
103     Result += "\"";
104     
105   } else {
106     Result = "{";
107     if (CPV->getNumOperands()) {
108       Result += " " +  getConstStrValue(cast<Constant>(CPV->getOperand(0)));
109       for (unsigned i = 1; i < CPV->getNumOperands(); i++)
110         Result += ", " + getConstStrValue(cast<Constant>(CPV->getOperand(i)));
111     }
112     Result += " }";
113   }
114   
115   return Result;
116 }
117
118 static std::string getConstStrValue(const Constant* CPV) {
119   switch (CPV->getType()->getPrimitiveID()) {
120   case Type::BoolTyID:
121     return CPV == ConstantBool::False ? "0" : "1";
122   case Type::SByteTyID:
123   case Type::ShortTyID:
124   case Type::IntTyID:
125     return itostr(cast<ConstantSInt>(CPV)->getValue());
126   case Type::LongTyID:
127     return itostr(cast<ConstantSInt>(CPV)->getValue()) + "ll";
128
129   case Type::UByteTyID:
130     return utostr(cast<ConstantUInt>(CPV)->getValue());
131   case Type::UShortTyID:
132     return utostr(cast<ConstantUInt>(CPV)->getValue());
133   case Type::UIntTyID:
134     return utostr(cast<ConstantUInt>(CPV)->getValue())+"u";
135   case Type::ULongTyID:
136     return utostr(cast<ConstantUInt>(CPV)->getValue())+"ull";
137
138   case Type::FloatTyID:
139   case Type::DoubleTyID:
140     return ftostr(cast<ConstantFP>(CPV)->getValue());
141
142   case Type::ArrayTyID:
143     return getConstArrayStrValue(CPV);
144
145   case Type::StructTyID: {
146     std::string Result = "{";
147     if (CPV->getNumOperands()) {
148       Result += " " + getConstStrValue(cast<Constant>(CPV->getOperand(0)));
149       for (unsigned i = 1; i < CPV->getNumOperands(); i++)
150         Result += ", " + getConstStrValue(cast<Constant>(CPV->getOperand(i)));
151     }
152     return Result + " }";
153   }
154
155   default:
156     cerr << "Unknown constant type: " << CPV << "\n";
157     abort();
158   }
159 }
160
161 // Pass the Type* variable and and the variable name and this prints out the 
162 // variable declaration.
163 //
164 static string calcTypeNameVar(const Type *Ty,
165                               map<const Type *, string> &TypeNames, 
166                               const string &NameSoFar, bool ignoreName = false){
167   if (Ty->isPrimitiveType())
168     switch (Ty->getPrimitiveID()) {
169     case Type::VoidTyID:   return "void " + NameSoFar;
170     case Type::BoolTyID:   return "bool " + NameSoFar;
171     case Type::UByteTyID:  return "unsigned char " + NameSoFar;
172     case Type::SByteTyID:  return "signed char " + NameSoFar;
173     case Type::UShortTyID: return "unsigned short " + NameSoFar;
174     case Type::ShortTyID:  return "short " + NameSoFar;
175     case Type::UIntTyID:   return "unsigned " + NameSoFar;
176     case Type::IntTyID:    return "int " + NameSoFar;
177     case Type::ULongTyID:  return "unsigned long long " + NameSoFar;
178     case Type::LongTyID:   return "signed long long " + NameSoFar;
179     default :
180       cerr << "Unknown primitive type: " << Ty << "\n";
181       abort();
182     }
183   
184   // Check to see if the type is named.
185   if (!ignoreName) {
186     map<const Type *, string>::iterator I = TypeNames.find(Ty);
187     if (I != TypeNames.end())
188       return I->second + " " + NameSoFar;
189   }  
190
191   string Result;
192   switch (Ty->getPrimitiveID()) {
193   case Type::FunctionTyID: {
194     const FunctionType *MTy = cast<const FunctionType>(Ty);
195     Result += calcTypeNameVar(MTy->getReturnType(), TypeNames, "");
196     Result += " " + NameSoFar;
197     Result += " (";
198     for (FunctionType::ParamTypes::const_iterator
199            I = MTy->getParamTypes().begin(),
200            E = MTy->getParamTypes().end(); I != E; ++I) {
201       if (I != MTy->getParamTypes().begin())
202         Result += ", ";
203       Result += calcTypeNameVar(*I, TypeNames, "");
204     }
205     if (MTy->isVarArg()) {
206       if (!MTy->getParamTypes().empty()) 
207         Result += ", ";
208       Result += "...";
209     }
210     Result += ")";
211     break;
212   }
213   case Type::StructTyID: {
214     const StructType *STy = cast<const StructType>(Ty);
215     Result = NameSoFar + " {\n";
216     unsigned indx = 0;
217     for (StructType::ElementTypes::const_iterator
218            I = STy->getElementTypes().begin(),
219            E = STy->getElementTypes().end(); I != E; ++I) {
220       Result += "  " +calcTypeNameVar(*I, TypeNames, "field" + utostr(indx++));
221       Result += ";\n";
222     }
223     Result += "}";
224     break;
225   }  
226
227   case Type::PointerTyID: {
228     Result = calcTypeNameVar(cast<const PointerType>(Ty)->getElementType(), 
229                              TypeNames, "*" + NameSoFar);
230     break;
231   }
232   
233   case Type::ArrayTyID: {
234     const ArrayType *ATy = cast<const ArrayType>(Ty);
235     int NumElements = ATy->getNumElements();
236     Result = calcTypeNameVar(ATy->getElementType(), TypeNames, 
237                              NameSoFar + "[" + itostr(NumElements) + "]");
238     break;
239   }
240   default:
241     assert(0 && "Unhandled case in getTypeProps!");
242     Result = "<error>";
243   }
244
245   return Result;
246 }
247
248 namespace {
249   class CWriter {
250     ostream& Out; 
251     SlotCalculator &Table;
252     const Module *TheModule;
253     map<const Type *, string> TypeNames;
254   public:
255     inline CWriter(ostream &o, SlotCalculator &Tab, const Module *M)
256       : Out(o), Table(Tab), TheModule(M) {
257     }
258     
259     inline void write(Module *M) { printModule(M); }
260
261     ostream& printTypeVar(const Type *Ty, const string &VariableName) {
262       return Out << calcTypeNameVar(Ty, TypeNames, VariableName);
263     }
264
265     ostream& printType(const Type *Ty) {
266       return Out << calcTypeNameVar(Ty, TypeNames, "");
267     }
268
269     void writeOperand(const Value *Operand);
270
271     string getValueName(const Value *V);
272   private :
273
274     void printModule(Module *M);
275     void printSymbolTable(const SymbolTable &ST);
276     void printGlobal(const GlobalVariable *GV);
277     void printFunctionSignature(const Function *F);
278     void printFunctionDecl(const Function *F); // Print just the forward decl
279     
280     void printFunction(Function *);
281   };
282   /* END class CWriter */
283
284
285   /* CLASS InstLocalVarsVisitor */
286   class InstLocalVarsVisitor : public InstVisitor<InstLocalVarsVisitor> {
287     CWriter& CW;
288     void handleTerminator(TerminatorInst *tI, int indx);
289   public:
290     CLocalVars CLV;
291     
292     InstLocalVarsVisitor(CWriter &cw) : CW(cw) {}
293     
294     void visitInstruction(Instruction *I) {
295       if (I->getType() != Type::VoidTy)
296         CLV.addLocalVar(I->getType(), CW.getValueName(I));
297     }
298
299     void visitBranchInst(BranchInst *I) {
300       handleTerminator(I, 0);
301       if (I->isConditional())
302         handleTerminator(I, 1);
303     }
304   };
305 }
306
307 void InstLocalVarsVisitor::handleTerminator(TerminatorInst *tI,int indx) {
308   BasicBlock *bb = tI->getSuccessor(indx);
309
310   BasicBlock::const_iterator insIt = bb->begin();
311   while (insIt != bb->end()) {
312     if (const PHINode *pI = dyn_cast<PHINode>(*insIt)) {
313       // Its a phinode!
314       // Calculate the incoming index for this
315       assert(pI->getBasicBlockIndex(tI->getParent()) != -1);
316
317       CLV.addLocalVar(pI->getType(), CW.getValueName(pI));
318     } else
319       break;
320     insIt++;
321   }
322 }
323
324 namespace {
325   /* CLASS CInstPrintVisitor */
326
327   class CInstPrintVisitor: public InstVisitor<CInstPrintVisitor> {
328     CWriter& CW;
329     SlotCalculator& Table;
330     ostream &Out;
331
332     void outputLValue(Instruction *);
333     void printPhiFromNextBlock(TerminatorInst *tI, int indx);
334     void printIndexingExpr(MemAccessInst *MAI);
335
336   public:
337     CInstPrintVisitor (CWriter &cw, SlotCalculator& table, ostream& o) 
338       : CW(cw), Table(table), Out(o) {}
339     
340     void visitCastInst(CastInst *I);
341     void visitCallInst(CallInst *I);
342     void visitShiftInst(ShiftInst *I) { visitBinaryOperator(I); }
343     void visitReturnInst(ReturnInst *I);
344     void visitBranchInst(BranchInst *I);
345     void visitSwitchInst(SwitchInst *I);
346     void visitInvokeInst(InvokeInst *I) ;
347     void visitMallocInst(MallocInst *I);
348     void visitAllocaInst(AllocaInst *I);
349     void visitFreeInst(FreeInst   *I);
350     void visitLoadInst(LoadInst   *I);
351     void visitStoreInst(StoreInst  *I);
352     void visitGetElementPtrInst(GetElementPtrInst *I);
353     void visitPHINode(PHINode *I) {}
354
355     void visitNot(GenericUnaryInst *I);
356     void visitBinaryOperator(Instruction *I);
357   };
358 }
359
360 void CInstPrintVisitor::outputLValue(Instruction *I) {
361   Out << "  " << CW.getValueName(I) << " = ";
362 }
363
364 void CInstPrintVisitor::printPhiFromNextBlock(TerminatorInst *tI, int indx) {
365   BasicBlock *bb = tI->getSuccessor(indx);
366   BasicBlock::const_iterator insIt = bb->begin();
367   while (insIt != bb->end()) {
368     if (PHINode *pI = dyn_cast<PHINode>(*insIt)) {
369       //Its a phinode!
370       //Calculate the incoming index for this
371       int incindex = pI->getBasicBlockIndex(tI->getParent());
372       if (incindex != -1) {
373         //now we have to do the printing
374         outputLValue(pI);
375         CW.writeOperand(pI->getIncomingValue(incindex));
376         Out << ";\n";
377       }
378     }
379     else break;
380     insIt++;
381   }
382 }
383
384 // Implement all "other" instructions, except for PHINode
385 void CInstPrintVisitor::visitCastInst(CastInst *I) {
386   outputLValue(I);
387   Out << "(";
388   CW.printType(I->getType());
389   Out << ")";
390   CW.writeOperand(I->getOperand(0));
391   Out << ";\n";
392 }
393
394 void CInstPrintVisitor::visitCallInst(CallInst *I) {
395   if (I->getType() != Type::VoidTy)
396     outputLValue(I);
397   else
398     Out << "  ";
399
400   const PointerType  *PTy   = cast<PointerType>(I->getCalledValue()->getType());
401   const FunctionType *FTy   = cast<FunctionType>(PTy->getElementType());
402   const Type         *RetTy = FTy->getReturnType();
403   
404   Out << CW.getValueName(I->getOperand(0)) << "(";
405
406   if (I->getNumOperands() > 1) {
407     CW.writeOperand(I->getOperand(1));
408
409     for (unsigned op = 2, Eop = I->getNumOperands(); op != Eop; ++op) {
410       Out << ", ";
411       CW.writeOperand(I->getOperand(op));
412     }
413   }
414   Out << ");\n";
415
416  
417 // Specific Instruction type classes... note that all of the casts are
418 // neccesary because we use the instruction classes as opaque types...
419 //
420 void CInstPrintVisitor::visitReturnInst(ReturnInst *I) {
421   Out << "  return";
422   if (I->getNumOperands()) {
423     Out << " ";
424     CW.writeOperand(I->getOperand(0));
425   }
426   Out << ";\n";
427 }
428
429 // Return true if BB1 immediately preceeds BB2.
430 static bool BBFollowsBB(BasicBlock *BB1, BasicBlock *BB2) {
431   Function *F = BB1->getParent();
432   Function::iterator I = find(F->begin(), F->end(), BB1);
433   assert(I != F->end() && "BB not in function!");
434   return *(I+1) == BB2;  
435 }
436
437 // Brach instruction printing - Avoid printing out a brach to a basic block that
438 // immediately succeeds the current one.
439 //
440 void CInstPrintVisitor::visitBranchInst(BranchInst *I) {
441   TerminatorInst *tI = cast<TerminatorInst>(I);
442   if (I->isConditional()) {
443     Out << "  if (";
444     CW.writeOperand(I->getCondition());
445     Out << ") {\n";
446     printPhiFromNextBlock(tI,0);
447
448     if (!BBFollowsBB(I->getParent(), cast<BasicBlock>(I->getOperand(0)))) {
449       Out << "    goto ";
450       CW.writeOperand(I->getOperand(0));
451       Out << ";\n";
452     }
453     Out << "  } else {\n";
454     printPhiFromNextBlock(tI,1);
455
456     if (!BBFollowsBB(I->getParent(), cast<BasicBlock>(I->getOperand(1)))) {
457       Out << "    goto ";
458       CW.writeOperand(I->getOperand(1));
459       Out << ";\n";
460     }
461     Out << "  }\n";
462   } else {
463     printPhiFromNextBlock(tI,0);
464
465     if (!BBFollowsBB(I->getParent(), cast<BasicBlock>(I->getOperand(0)))) {
466       Out << "  goto ";
467       CW.writeOperand(I->getOperand(0));
468       Out << ";\n";
469     }
470   }
471   Out << "\n";
472 }
473
474 void CInstPrintVisitor::visitSwitchInst(SwitchInst *I) {
475   assert(0 && "Switch not implemented!");
476 }
477
478 void CInstPrintVisitor::visitInvokeInst(InvokeInst *I) {
479   assert(0 && "Invoke not implemented!");
480 }
481
482 void CInstPrintVisitor::visitMallocInst(MallocInst *I) {
483   outputLValue(I);
484   Out << "(";
485   CW.printType(I->getType());
486   Out << ")malloc(sizeof(";
487   CW.printType(I->getType()->getElementType());
488   Out << ")";
489
490   if (I->isArrayAllocation()) {
491     Out << " * " ;
492     CW.writeOperand(I->getOperand(0));
493   }
494   Out << ");\n";
495 }
496
497 void CInstPrintVisitor::visitAllocaInst(AllocaInst *I) {
498   outputLValue(I);
499   Out << "(";
500   CW.printType(I->getType());
501   Out << ") alloca(sizeof(";
502   CW.printType(I->getType()->getElementType());
503   Out << ")";
504   if (I->isArrayAllocation()) {
505     Out << " * " ;
506     CW.writeOperand(I->getOperand(0));
507   }
508   Out << ");\n";
509 }
510
511 void CInstPrintVisitor::visitFreeInst(FreeInst   *I) {
512   Out << "free(";
513   CW.writeOperand(I->getOperand(0));
514   Out << ");\n";
515 }
516
517 void CInstPrintVisitor::printIndexingExpr(MemAccessInst *MAI) {
518   CW.writeOperand(MAI->getPointerOperand());
519
520   for (MemAccessInst::op_iterator I = MAI->idx_begin(), E = MAI->idx_end();
521        I != E; ++I)
522     if ((*I)->getType() == Type::UIntTy) {
523       Out << "[";
524       CW.writeOperand(*I);
525       Out << "]";
526     } else {
527       Out << ".field" << cast<ConstantUInt>(*I)->getValue();
528     }
529 }
530
531 void CInstPrintVisitor::visitLoadInst(LoadInst *I) {
532   outputLValue(I);
533   printIndexingExpr(I);
534   Out << ";\n";
535 }
536
537 void CInstPrintVisitor::visitStoreInst(StoreInst *I) {
538   Out << "  ";
539   printIndexingExpr(I);
540   Out << " = ";
541   CW.writeOperand(I->getOperand(0));
542   Out << ";\n";
543 }
544
545 void CInstPrintVisitor::visitGetElementPtrInst(GetElementPtrInst *I) {
546   outputLValue(I);
547   Out << "&";
548   printIndexingExpr(I);
549   Out << ";\n";
550 }
551
552 void CInstPrintVisitor::visitNot(GenericUnaryInst *I) {
553   outputLValue(I);
554   Out << "~";
555   CW.writeOperand(I->getOperand(0));
556   Out << ";\n";
557 }
558
559 void CInstPrintVisitor::visitBinaryOperator(Instruction *I) {
560   // binary instructions, shift instructions, setCond instructions.
561   outputLValue(I);
562   if (isa<PointerType>(I->getType())) {
563     Out << "(";
564     CW.printType(I->getType());
565     Out << ")";
566   }
567       
568   if (isa<PointerType>(I->getType())) Out << "(long long)";
569   CW.writeOperand(I->getOperand(0));
570
571   switch (I->getOpcode()) {
572   case Instruction::Add: Out << " + "; break;
573   case Instruction::Sub: Out << " - "; break;
574   case Instruction::Mul: Out << "*"; break;
575   case Instruction::Div: Out << "/"; break;
576   case Instruction::Rem: Out << "%"; break;
577   case Instruction::And: Out << " & "; break;
578   case Instruction::Or: Out << " | "; break;
579   case Instruction::Xor: Out << " ^ "; break;
580   case Instruction::SetEQ: Out << " == "; break;
581   case Instruction::SetNE: Out << " != "; break;
582   case Instruction::SetLE: Out << " <= "; break;
583   case Instruction::SetGE: Out << " >= "; break;
584   case Instruction::SetLT: Out << " < "; break;
585   case Instruction::SetGT: Out << " > "; break;
586   case Instruction::Shl : Out << " << "; break;
587   case Instruction::Shr : Out << " >> "; break;
588   default: cerr << "Invalid operator type!" << I; abort();
589   }
590
591   if (isa<PointerType>(I->getType())) Out << "(long long)";
592   CW.writeOperand(I->getOperand(1));
593   Out << ";\n";
594 }
595
596 /* END : CInstPrintVisitor implementation */
597
598 // We dont want identifier names with ., space, -  in them. 
599 // So we replace them with _
600 static string makeNameProper(string x) {
601   string tmp;
602   for (string::iterator sI = x.begin(), sEnd = x.end(); sI != sEnd; sI++)
603     switch (*sI) {
604     case '.': tmp += "d_"; break;
605     case ' ': tmp += "s_"; break;
606     case '-': tmp += "D_"; break;
607     case '_': tmp += "__"; break;
608     default:  tmp += *sI;
609     }
610
611   return tmp;
612 }
613
614 string CWriter::getValueName(const Value *V) {
615   if (V->hasName()) {             // Print out the label if it exists...
616     if (isa<GlobalValue>(V))  // Do not mangle globals...
617       return makeNameProper(V->getName());
618
619     return "l" + utostr(V->getType()->getUniqueID()) + "_" +
620            makeNameProper(V->getName());      
621   }
622
623   int Slot = Table.getValSlot(V);
624   assert(Slot >= 0 && "Invalid value!");
625   return "ltmp_" + itostr(Slot) + "_" + utostr(V->getType()->getUniqueID());
626 }
627
628 void CWriter::printModule(Module *M) {
629   // printing stdlib inclusion
630   // Out << "#include <stdlib.h>\n";
631
632   // get declaration for alloca
633   Out << "/* Provide Declarations */\n"
634       << "#include <alloca.h>\n\n"
635
636     // Provide a definition for null if one does not already exist.
637       << "#ifndef NULL\n#define NULL 0\n#endif\n\n"
638       << "typedef unsigned char bool;\n"
639
640       << "\n\n/* Global Symbols */\n";
641
642   // Loop over the symbol table, emitting all named constants...
643   if (M->hasSymbolTable())
644     printSymbolTable(*M->getSymbolTable());
645
646   Out << "\n\n/* Global Data */\n";
647   for (Module::const_giterator I = M->gbegin(), E = M->gend(); I != E; ++I) {
648     GlobalVariable *GV = *I;
649     if (GV->hasInternalLinkage()) Out << "static ";
650     printTypeVar(GV->getType()->getElementType(), getValueName(GV));
651
652     if (GV->hasInitializer()) {
653       Out << " = " ;
654       writeOperand(GV->getInitializer());
655     }
656     Out << ";\n";
657   }
658
659   // First output all the declarations of the functions as C requires Functions 
660   // be declared before they are used.
661   //
662   Out << "\n\n/* Function Declarations */\n";
663   for_each(M->begin(), M->end(), bind_obj(this, &CWriter::printFunctionDecl));
664   
665   // Output all of the functions...
666   Out << "\n\n/* Function Bodies */\n";
667   for_each(M->begin(), M->end(), bind_obj(this, &CWriter::printFunction));
668 }
669
670
671 // printSymbolTable - Run through symbol table looking for named constants
672 // if a named constant is found, emit it's declaration...
673 // Assuming that symbol table has only types and constants.
674 void CWriter::printSymbolTable(const SymbolTable &ST) {
675   for (SymbolTable::const_iterator TI = ST.begin(); TI != ST.end(); ++TI) {
676     SymbolTable::type_const_iterator I = ST.type_begin(TI->first);
677     SymbolTable::type_const_iterator End = ST.type_end(TI->first);
678     
679     for (; I != End; ++I)
680       if (const Type *Ty = dyn_cast<const StructType>(I->second)) {
681         string Name = "struct l_" + I->first;
682         Out << Name << ";\n";
683
684         TypeNames.insert(std::make_pair(Ty, Name));
685       }
686   }
687
688   Out << "\n";
689
690   for (SymbolTable::const_iterator TI = ST.begin(); TI != ST.end(); ++TI) {
691     SymbolTable::type_const_iterator I = ST.type_begin(TI->first);
692     SymbolTable::type_const_iterator End = ST.type_end(TI->first);
693     
694     for (; I != End; ++I) {
695       const Value *V = I->second;
696       if (const Type *Ty = dyn_cast<const Type>(V)) {
697         Out << "typedef ";
698         string Name = "l_" + I->first;
699         if (isa<StructType>(Ty)) Name = "struct " + Name;
700         Out << calcTypeNameVar(Ty, TypeNames, Name, true) << ";\n";
701       }
702     }
703   }
704 }
705
706
707 // printFunctionDecl - Print function declaration
708 //
709 void CWriter::printFunctionDecl(const Function *F) {
710   printFunctionSignature(F);
711   Out << ";\n";
712 }
713
714 void CWriter::printFunctionSignature(const Function *F) {
715   if (F->hasInternalLinkage()) Out << "static ";
716   
717   // Loop over the arguments, printing them...
718   const FunctionType *FT = cast<FunctionType>(F->getFunctionType());
719   
720   // Print out the return type and name...
721   printType(F->getReturnType());
722   Out << " " << getValueName(F) << "(";
723     
724   if (!F->isExternal()) {
725     if (!F->getArgumentList().empty()) {
726       printTypeVar(F->getArgumentList().front()->getType(),
727                    getValueName(F->getArgumentList().front()));
728
729       for (Function::ArgumentListType::const_iterator
730              I = F->getArgumentList().begin()+1,
731              E = F->getArgumentList().end(); I != E; ++I) {
732         Out << ", ";
733         printTypeVar((*I)->getType(), getValueName(*I));
734       }
735     }
736   } else {
737     // Loop over the arguments, printing them...
738     for (FunctionType::ParamTypes::const_iterator I = 
739            FT->getParamTypes().begin(),
740            E = FT->getParamTypes().end(); I != E; ++I) {
741       if (I != FT->getParamTypes().begin()) Out << ", ";
742       printType(*I);
743     }
744   }
745
746   // Finish printing arguments...
747   if (FT->isVarArg()) {
748     if (FT->getParamTypes().size()) Out << ", ";
749     Out << "...";  // Output varargs portion of signature!
750   }
751   Out << ")";
752 }
753
754
755 void CWriter::printFunction(Function *F) {
756   if (F->isExternal()) return;
757
758   Table.incorporateFunction(F);
759
760   printFunctionSignature(F);
761   Out << " {\n";
762
763   // Process each of the basic blocks, gather information and call the  
764   // output methods on the CLocalVars and Function* objects.
765     
766   // gather local variable information for each basic block
767   InstLocalVarsVisitor ILV(*this);
768   ILV.visit(F);
769
770   // print the local variables
771   // we assume that every local variable is alloca'ed in the C code.
772   std::map<const Type*, VarListType> &locals = ILV.CLV.LocalVars;
773   
774   map<const Type*, VarListType>::iterator iter;
775   for (iter = locals.begin(); iter != locals.end(); ++iter) {
776     VarListType::iterator listiter;
777     for (listiter = iter->second.begin(); listiter != iter->second.end(); 
778          ++listiter) {
779       Out << "  ";
780       printTypeVar(iter->first, *listiter);
781       Out << ";\n";
782     }
783   }
784  
785   // print the basic blocks
786   for (Function::iterator I = F->begin(), E = F->end(); I != E; ++I) {
787     BasicBlock *BB = *I, *Prev = I != F->begin() ? *(I-1) : 0;
788
789     // Don't print the label for the basic block if there are no uses, or if the
790     // only terminator use is the precessor basic block's terminator.  We have
791     // to scan the use list because PHI nodes use basic blocks too but do not
792     // require a label to be generated.
793     //
794     bool NeedsLabel = false;
795     for (Value::use_iterator UI = BB->use_begin(), UE = BB->use_end();
796          UI != UE; ++UI)
797       if (TerminatorInst *TI = dyn_cast<TerminatorInst>(*UI))
798         if (TI != Prev->getTerminator()) {
799           NeedsLabel = true;
800           break;        
801         }
802
803     if (NeedsLabel) Out << getValueName(BB) << ":\n";
804
805     // Output all of the instructions in the basic block...
806     // print the basic blocks
807     CInstPrintVisitor CIPV(*this, Table, Out);
808     CIPV.visit(BB);
809   }
810   
811   Out << "}\n\n";
812   Table.purgeFunction();
813 }
814
815 void CWriter::writeOperand(const Value *Operand) {
816   if (isa<GlobalVariable>(Operand))
817     Out << "(&";  // Global variables are references as their addresses by llvm
818
819   if (Operand->hasName()) {   
820     Out << getValueName(Operand);
821   } else if (const Constant *CPV = dyn_cast<const Constant>(Operand)) {
822     if (isa<ConstantPointerNull>(CPV))
823       Out << "NULL";
824     else
825       Out << getConstStrValue(CPV); 
826   } else {
827     int Slot = Table.getValSlot(Operand);
828     assert(Slot >= 0 && "Malformed LLVM!");
829     Out << "ltmp_" << Slot << "_" << Operand->getType()->getUniqueID();
830   }
831
832   if (isa<GlobalVariable>(Operand))
833     Out << ")";
834 }
835
836
837 //===----------------------------------------------------------------------===//
838 //                       External Interface declaration
839 //===----------------------------------------------------------------------===//
840
841 void WriteToC(const Module *M, ostream &Out) {
842   assert(M && "You can't write a null module!!");
843   SlotCalculator SlotTable(M, false);
844   CWriter W(Out, SlotTable, M);
845   W.write((Module*)M);
846   Out.flush();
847 }