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