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