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