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