Two things:
[oota-llvm.git] / lib / Target / CBackend / Writer.cpp
1 //===-- Writer.cpp - Library for converting LLVM code to C ----------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file was developed by the LLVM research group and is distributed under
6 // the University of Illinois Open Source License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This library converts LLVM code to C code, compilable by GCC and other C
11 // compilers.
12 //
13 //===----------------------------------------------------------------------===//
14
15 #include "CTargetMachine.h"
16 #include "llvm/Constants.h"
17 #include "llvm/DerivedTypes.h"
18 #include "llvm/Module.h"
19 #include "llvm/Instructions.h"
20 #include "llvm/Pass.h"
21 #include "llvm/PassManager.h"
22 #include "llvm/SymbolTable.h"
23 #include "llvm/Intrinsics.h"
24 #include "llvm/Analysis/ConstantsScanner.h"
25 #include "llvm/Analysis/FindUsedTypes.h"
26 #include "llvm/Analysis/LoopInfo.h"
27 #include "llvm/CodeGen/IntrinsicLowering.h"
28 #include "llvm/Transforms/Scalar.h"
29 #include "llvm/Target/TargetMachineRegistry.h"
30 #include "llvm/Support/CallSite.h"
31 #include "llvm/Support/CFG.h"
32 #include "llvm/Support/GetElementPtrTypeIterator.h"
33 #include "llvm/Support/InstVisitor.h"
34 #include "llvm/Support/Mangler.h"
35 #include "llvm/Support/MathExtras.h"
36 #include "llvm/ADT/StringExtras.h"
37 #include "llvm/ADT/STLExtras.h"
38 #include "llvm/Support/MathExtras.h"
39 #include "llvm/Config/config.h"
40 #include <algorithm>
41 #include <iostream>
42 #include <ios>
43 #include <sstream>
44 using namespace llvm;
45
46 namespace {
47   // Register the target.
48   RegisterTarget<CTargetMachine> X("c", "  C backend");
49
50   /// CBackendNameAllUsedStructsAndMergeFunctions - This pass inserts names for
51   /// any unnamed structure types that are used by the program, and merges
52   /// external functions with the same name.
53   ///
54   class CBackendNameAllUsedStructsAndMergeFunctions : public ModulePass {
55     void getAnalysisUsage(AnalysisUsage &AU) const {
56       AU.addRequired<FindUsedTypes>();
57     }
58
59     virtual const char *getPassName() const {
60       return "C backend type canonicalizer";
61     }
62
63     virtual bool runOnModule(Module &M);
64   };
65
66   /// CWriter - This class is the main chunk of code that converts an LLVM
67   /// module to a C translation unit.
68   class CWriter : public FunctionPass, public InstVisitor<CWriter> {
69     std::ostream &Out;
70     IntrinsicLowering &IL;
71     Mangler *Mang;
72     LoopInfo *LI;
73     const Module *TheModule;
74     std::map<const Type *, std::string> TypeNames;
75
76     std::map<const ConstantFP *, unsigned> FPConstantMap;
77   public:
78     CWriter(std::ostream &o, IntrinsicLowering &il) : Out(o), IL(il) {}
79
80     virtual const char *getPassName() const { return "C backend"; }
81
82     void getAnalysisUsage(AnalysisUsage &AU) const {
83       AU.addRequired<LoopInfo>();
84       AU.setPreservesAll();
85     }
86
87     virtual bool doInitialization(Module &M);
88
89     bool runOnFunction(Function &F) {
90       LI = &getAnalysis<LoopInfo>();
91
92       // Get rid of intrinsics we can't handle.
93       lowerIntrinsics(F);
94
95       // Output all floating point constants that cannot be printed accurately.
96       printFloatingPointConstants(F);
97
98       // Ensure that no local symbols conflict with global symbols.
99       F.renameLocalSymbols();
100
101       printFunction(F);
102       FPConstantMap.clear();
103       return false;
104     }
105
106     virtual bool doFinalization(Module &M) {
107       // Free memory...
108       delete Mang;
109       TypeNames.clear();
110       return false;
111     }
112
113     std::ostream &printType(std::ostream &Out, const Type *Ty,
114                             const std::string &VariableName = "",
115                             bool IgnoreName = false);
116
117     void writeOperand(Value *Operand);
118     void writeOperandInternal(Value *Operand);
119
120   private :
121     void lowerIntrinsics(Function &F);
122
123     void printModule(Module *M);
124     void printModuleTypes(const SymbolTable &ST);
125     void printContainedStructs(const Type *Ty, std::set<const StructType *> &);
126     void printFloatingPointConstants(Function &F);
127     void printFunctionSignature(const Function *F, bool Prototype);
128
129     void printFunction(Function &);
130     void printBasicBlock(BasicBlock *BB);
131     void printLoop(Loop *L);
132
133     void printConstant(Constant *CPV);
134     void printConstantArray(ConstantArray *CPA);
135     void printConstantPacked(ConstantPacked *CP);
136
137     // isInlinableInst - Attempt to inline instructions into their uses to build
138     // trees as much as possible.  To do this, we have to consistently decide
139     // what is acceptable to inline, so that variable declarations don't get
140     // printed and an extra copy of the expr is not emitted.
141     //
142     static bool isInlinableInst(const Instruction &I) {
143       // Always inline setcc instructions, even if they are shared by multiple
144       // expressions.  GCC generates horrible code if we don't.
145       if (isa<SetCondInst>(I)) return true;
146
147       // Must be an expression, must be used exactly once.  If it is dead, we
148       // emit it inline where it would go.
149       if (I.getType() == Type::VoidTy || !I.hasOneUse() ||
150           isa<TerminatorInst>(I) || isa<CallInst>(I) || isa<PHINode>(I) ||
151           isa<LoadInst>(I) || isa<VAArgInst>(I))
152         // Don't inline a load across a store or other bad things!
153         return false;
154
155       // Only inline instruction it it's use is in the same BB as the inst.
156       return I.getParent() == cast<Instruction>(I.use_back())->getParent();
157     }
158
159     // isDirectAlloca - Define fixed sized allocas in the entry block as direct
160     // variables which are accessed with the & operator.  This causes GCC to
161     // generate significantly better code than to emit alloca calls directly.
162     //
163     static const AllocaInst *isDirectAlloca(const Value *V) {
164       const AllocaInst *AI = dyn_cast<AllocaInst>(V);
165       if (!AI) return false;
166       if (AI->isArrayAllocation())
167         return 0;   // FIXME: we can also inline fixed size array allocas!
168       if (AI->getParent() != &AI->getParent()->getParent()->getEntryBlock())
169         return 0;
170       return AI;
171     }
172
173     // Instruction visitation functions
174     friend class InstVisitor<CWriter>;
175
176     void visitReturnInst(ReturnInst &I);
177     void visitBranchInst(BranchInst &I);
178     void visitSwitchInst(SwitchInst &I);
179     void visitInvokeInst(InvokeInst &I) {
180       assert(0 && "Lowerinvoke pass didn't work!");
181     }
182
183     void visitUnwindInst(UnwindInst &I) {
184       assert(0 && "Lowerinvoke pass didn't work!");
185     }
186     void visitUnreachableInst(UnreachableInst &I);
187
188     void visitPHINode(PHINode &I);
189     void visitBinaryOperator(Instruction &I);
190
191     void visitCastInst (CastInst &I);
192     void visitSelectInst(SelectInst &I);
193     void visitCallInst (CallInst &I);
194     void visitShiftInst(ShiftInst &I) { visitBinaryOperator(I); }
195
196     void visitMallocInst(MallocInst &I);
197     void visitAllocaInst(AllocaInst &I);
198     void visitFreeInst  (FreeInst   &I);
199     void visitLoadInst  (LoadInst   &I);
200     void visitStoreInst (StoreInst  &I);
201     void visitGetElementPtrInst(GetElementPtrInst &I);
202     void visitVAArgInst (VAArgInst &I);
203
204     void visitInstruction(Instruction &I) {
205       std::cerr << "C Writer does not know about " << I;
206       abort();
207     }
208
209     void outputLValue(Instruction *I) {
210       Out << "  " << Mang->getValueName(I) << " = ";
211     }
212
213     bool isGotoCodeNecessary(BasicBlock *From, BasicBlock *To);
214     void printPHICopiesForSuccessor(BasicBlock *CurBlock,
215                                     BasicBlock *Successor, unsigned Indent);
216     void printBranchToBlock(BasicBlock *CurBlock, BasicBlock *SuccBlock,
217                             unsigned Indent);
218     void printIndexingExpression(Value *Ptr, gep_type_iterator I,
219                                  gep_type_iterator E);
220   };
221 }
222
223 /// This method inserts names for any unnamed structure types that are used by
224 /// the program, and removes names from structure types that are not used by the
225 /// program.
226 ///
227 bool CBackendNameAllUsedStructsAndMergeFunctions::runOnModule(Module &M) {
228   // Get a set of types that are used by the program...
229   std::set<const Type *> UT = getAnalysis<FindUsedTypes>().getTypes();
230
231   // Loop over the module symbol table, removing types from UT that are
232   // already named, and removing names for types that are not used.
233   //
234   SymbolTable &MST = M.getSymbolTable();
235   for (SymbolTable::type_iterator TI = MST.type_begin(), TE = MST.type_end();
236        TI != TE; ) {
237     SymbolTable::type_iterator I = TI++;
238
239     // If this is not used, remove it from the symbol table.
240     std::set<const Type *>::iterator UTI = UT.find(I->second);
241     if (UTI == UT.end())
242       MST.remove(I);
243     else
244       UT.erase(UTI);    // Only keep one name for this type.
245   }
246
247   // UT now contains types that are not named.  Loop over it, naming
248   // structure types.
249   //
250   bool Changed = false;
251   unsigned RenameCounter = 0;
252   for (std::set<const Type *>::const_iterator I = UT.begin(), E = UT.end();
253        I != E; ++I)
254     if (const StructType *ST = dyn_cast<StructType>(*I)) {
255       while (M.addTypeName("unnamed"+utostr(RenameCounter), ST))
256         ++RenameCounter;
257       Changed = true;
258     }
259       
260       
261   // Loop over all external functions and globals.  If we have two with
262   // identical names, merge them.
263   // FIXME: This code should disappear when we don't allow values with the same
264   // names when they have different types!
265   std::map<std::string, GlobalValue*> ExtSymbols;
266   for (Module::iterator I = M.begin(), E = M.end(); I != E;) {
267     Function *GV = I++;
268     if (GV->isExternal() && GV->hasName()) {
269       std::pair<std::map<std::string, GlobalValue*>::iterator, bool> X
270         = ExtSymbols.insert(std::make_pair(GV->getName(), GV));
271       if (!X.second) {
272         // Found a conflict, replace this global with the previous one.
273         GlobalValue *OldGV = X.first->second;
274         GV->replaceAllUsesWith(ConstantExpr::getCast(OldGV, GV->getType()));
275         GV->eraseFromParent();
276         Changed = true;
277       }
278     }
279   }
280   // Do the same for globals.
281   for (Module::global_iterator I = M.global_begin(), E = M.global_end();
282        I != E;) {
283     GlobalVariable *GV = I++;
284     if (GV->isExternal() && GV->hasName()) {
285       std::pair<std::map<std::string, GlobalValue*>::iterator, bool> X
286         = ExtSymbols.insert(std::make_pair(GV->getName(), GV));
287       if (!X.second) {
288         // Found a conflict, replace this global with the previous one.
289         GlobalValue *OldGV = X.first->second;
290         GV->replaceAllUsesWith(ConstantExpr::getCast(OldGV, GV->getType()));
291         GV->eraseFromParent();
292         Changed = true;
293       }
294     }
295   }
296   
297   return Changed;
298 }
299
300
301 // Pass the Type* and the variable name and this prints out the variable
302 // declaration.
303 //
304 std::ostream &CWriter::printType(std::ostream &Out, const Type *Ty,
305                                  const std::string &NameSoFar,
306                                  bool IgnoreName) {
307   if (Ty->isPrimitiveType())
308     switch (Ty->getTypeID()) {
309     case Type::VoidTyID:   return Out << "void "               << NameSoFar;
310     case Type::BoolTyID:   return Out << "bool "               << NameSoFar;
311     case Type::UByteTyID:  return Out << "unsigned char "      << NameSoFar;
312     case Type::SByteTyID:  return Out << "signed char "        << NameSoFar;
313     case Type::UShortTyID: return Out << "unsigned short "     << NameSoFar;
314     case Type::ShortTyID:  return Out << "short "              << NameSoFar;
315     case Type::UIntTyID:   return Out << "unsigned "           << NameSoFar;
316     case Type::IntTyID:    return Out << "int "                << NameSoFar;
317     case Type::ULongTyID:  return Out << "unsigned long long " << NameSoFar;
318     case Type::LongTyID:   return Out << "signed long long "   << NameSoFar;
319     case Type::FloatTyID:  return Out << "float "              << NameSoFar;
320     case Type::DoubleTyID: return Out << "double "             << NameSoFar;
321     default :
322       std::cerr << "Unknown primitive type: " << *Ty << "\n";
323       abort();
324     }
325
326   // Check to see if the type is named.
327   if (!IgnoreName || isa<OpaqueType>(Ty)) {
328     std::map<const Type *, std::string>::iterator I = TypeNames.find(Ty);
329     if (I != TypeNames.end()) return Out << I->second << ' ' << NameSoFar;
330   }
331
332   switch (Ty->getTypeID()) {
333   case Type::FunctionTyID: {
334     const FunctionType *MTy = cast<FunctionType>(Ty);
335     std::stringstream FunctionInnards;
336     FunctionInnards << " (" << NameSoFar << ") (";
337     for (FunctionType::param_iterator I = MTy->param_begin(),
338            E = MTy->param_end(); I != E; ++I) {
339       if (I != MTy->param_begin())
340         FunctionInnards << ", ";
341       printType(FunctionInnards, *I, "");
342     }
343     if (MTy->isVarArg()) {
344       if (MTy->getNumParams())
345         FunctionInnards << ", ...";
346     } else if (!MTy->getNumParams()) {
347       FunctionInnards << "void";
348     }
349     FunctionInnards << ')';
350     std::string tstr = FunctionInnards.str();
351     printType(Out, MTy->getReturnType(), tstr);
352     return Out;
353   }
354   case Type::StructTyID: {
355     const StructType *STy = cast<StructType>(Ty);
356     Out << NameSoFar + " {\n";
357     unsigned Idx = 0;
358     for (StructType::element_iterator I = STy->element_begin(),
359            E = STy->element_end(); I != E; ++I) {
360       Out << "  ";
361       printType(Out, *I, "field" + utostr(Idx++));
362       Out << ";\n";
363     }
364     return Out << '}';
365   }
366
367   case Type::PointerTyID: {
368     const PointerType *PTy = cast<PointerType>(Ty);
369     std::string ptrName = "*" + NameSoFar;
370
371     if (isa<ArrayType>(PTy->getElementType()) ||
372         isa<PackedType>(PTy->getElementType()))
373       ptrName = "(" + ptrName + ")";
374
375     return printType(Out, PTy->getElementType(), ptrName);
376   }
377
378   case Type::ArrayTyID: {
379     const ArrayType *ATy = cast<ArrayType>(Ty);
380     unsigned NumElements = ATy->getNumElements();
381     if (NumElements == 0) NumElements = 1;
382     return printType(Out, ATy->getElementType(),
383                      NameSoFar + "[" + utostr(NumElements) + "]");
384   }
385
386   case Type::PackedTyID: {
387     const PackedType *PTy = cast<PackedType>(Ty);
388     unsigned NumElements = PTy->getNumElements();
389     if (NumElements == 0) NumElements = 1;
390     return printType(Out, PTy->getElementType(),
391                      NameSoFar + "[" + utostr(NumElements) + "]");
392   }
393
394   case Type::OpaqueTyID: {
395     static int Count = 0;
396     std::string TyName = "struct opaque_" + itostr(Count++);
397     assert(TypeNames.find(Ty) == TypeNames.end());
398     TypeNames[Ty] = TyName;
399     return Out << TyName << ' ' << NameSoFar;
400   }
401   default:
402     assert(0 && "Unhandled case in getTypeProps!");
403     abort();
404   }
405
406   return Out;
407 }
408
409 void CWriter::printConstantArray(ConstantArray *CPA) {
410
411   // As a special case, print the array as a string if it is an array of
412   // ubytes or an array of sbytes with positive values.
413   //
414   const Type *ETy = CPA->getType()->getElementType();
415   bool isString = (ETy == Type::SByteTy || ETy == Type::UByteTy);
416
417   // Make sure the last character is a null char, as automatically added by C
418   if (isString && (CPA->getNumOperands() == 0 ||
419                    !cast<Constant>(*(CPA->op_end()-1))->isNullValue()))
420     isString = false;
421
422   if (isString) {
423     Out << '\"';
424     // Keep track of whether the last number was a hexadecimal escape
425     bool LastWasHex = false;
426
427     // Do not include the last character, which we know is null
428     for (unsigned i = 0, e = CPA->getNumOperands()-1; i != e; ++i) {
429       unsigned char C = cast<ConstantInt>(CPA->getOperand(i))->getRawValue();
430
431       // Print it out literally if it is a printable character.  The only thing
432       // to be careful about is when the last letter output was a hex escape
433       // code, in which case we have to be careful not to print out hex digits
434       // explicitly (the C compiler thinks it is a continuation of the previous
435       // character, sheesh...)
436       //
437       if (isprint(C) && (!LastWasHex || !isxdigit(C))) {
438         LastWasHex = false;
439         if (C == '"' || C == '\\')
440           Out << "\\" << C;
441         else
442           Out << C;
443       } else {
444         LastWasHex = false;
445         switch (C) {
446         case '\n': Out << "\\n"; break;
447         case '\t': Out << "\\t"; break;
448         case '\r': Out << "\\r"; break;
449         case '\v': Out << "\\v"; break;
450         case '\a': Out << "\\a"; break;
451         case '\"': Out << "\\\""; break;
452         case '\'': Out << "\\\'"; break;
453         default:
454           Out << "\\x";
455           Out << (char)(( C/16  < 10) ? ( C/16 +'0') : ( C/16 -10+'A'));
456           Out << (char)(((C&15) < 10) ? ((C&15)+'0') : ((C&15)-10+'A'));
457           LastWasHex = true;
458           break;
459         }
460       }
461     }
462     Out << '\"';
463   } else {
464     Out << '{';
465     if (CPA->getNumOperands()) {
466       Out << ' ';
467       printConstant(cast<Constant>(CPA->getOperand(0)));
468       for (unsigned i = 1, e = CPA->getNumOperands(); i != e; ++i) {
469         Out << ", ";
470         printConstant(cast<Constant>(CPA->getOperand(i)));
471       }
472     }
473     Out << " }";
474   }
475 }
476
477 void CWriter::printConstantPacked(ConstantPacked *CP) {
478   Out << '{';
479   if (CP->getNumOperands()) {
480     Out << ' ';
481     printConstant(cast<Constant>(CP->getOperand(0)));
482     for (unsigned i = 1, e = CP->getNumOperands(); i != e; ++i) {
483       Out << ", ";
484       printConstant(cast<Constant>(CP->getOperand(i)));
485     }
486   }
487   Out << " }";
488 }
489
490 // isFPCSafeToPrint - Returns true if we may assume that CFP may be written out
491 // textually as a double (rather than as a reference to a stack-allocated
492 // variable). We decide this by converting CFP to a string and back into a
493 // double, and then checking whether the conversion results in a bit-equal
494 // double to the original value of CFP. This depends on us and the target C
495 // compiler agreeing on the conversion process (which is pretty likely since we
496 // only deal in IEEE FP).
497 //
498 static bool isFPCSafeToPrint(const ConstantFP *CFP) {
499 #if HAVE_PRINTF_A
500   char Buffer[100];
501   sprintf(Buffer, "%a", CFP->getValue());
502
503   if (!strncmp(Buffer, "0x", 2) ||
504       !strncmp(Buffer, "-0x", 3) ||
505       !strncmp(Buffer, "+0x", 3))
506     return atof(Buffer) == CFP->getValue();
507   return false;
508 #else
509   std::string StrVal = ftostr(CFP->getValue());
510
511   while (StrVal[0] == ' ')
512     StrVal.erase(StrVal.begin());
513
514   // Check to make sure that the stringized number is not some string like "Inf"
515   // or NaN.  Check that the string matches the "[-+]?[0-9]" regex.
516   if ((StrVal[0] >= '0' && StrVal[0] <= '9') ||
517       ((StrVal[0] == '-' || StrVal[0] == '+') &&
518        (StrVal[1] >= '0' && StrVal[1] <= '9')))
519     // Reparse stringized version!
520     return atof(StrVal.c_str()) == CFP->getValue();
521   return false;
522 #endif
523 }
524
525 // printConstant - The LLVM Constant to C Constant converter.
526 void CWriter::printConstant(Constant *CPV) {
527   if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(CPV)) {
528     switch (CE->getOpcode()) {
529     case Instruction::Cast:
530       Out << "((";
531       printType(Out, CPV->getType());
532       Out << ')';
533       printConstant(CE->getOperand(0));
534       Out << ')';
535       return;
536
537     case Instruction::GetElementPtr:
538       Out << "(&(";
539       printIndexingExpression(CE->getOperand(0), gep_type_begin(CPV),
540                               gep_type_end(CPV));
541       Out << "))";
542       return;
543     case Instruction::Select:
544       Out << '(';
545       printConstant(CE->getOperand(0));
546       Out << '?';
547       printConstant(CE->getOperand(1));
548       Out << ':';
549       printConstant(CE->getOperand(2));
550       Out << ')';
551       return;
552     case Instruction::Add:
553     case Instruction::Sub:
554     case Instruction::Mul:
555     case Instruction::Div:
556     case Instruction::Rem:
557     case Instruction::And:
558     case Instruction::Or:
559     case Instruction::Xor:
560     case Instruction::SetEQ:
561     case Instruction::SetNE:
562     case Instruction::SetLT:
563     case Instruction::SetLE:
564     case Instruction::SetGT:
565     case Instruction::SetGE:
566     case Instruction::Shl:
567     case Instruction::Shr:
568       Out << '(';
569       printConstant(CE->getOperand(0));
570       switch (CE->getOpcode()) {
571       case Instruction::Add: Out << " + "; break;
572       case Instruction::Sub: Out << " - "; break;
573       case Instruction::Mul: Out << " * "; break;
574       case Instruction::Div: Out << " / "; break;
575       case Instruction::Rem: Out << " % "; break;
576       case Instruction::And: Out << " & "; break;
577       case Instruction::Or:  Out << " | "; break;
578       case Instruction::Xor: Out << " ^ "; break;
579       case Instruction::SetEQ: Out << " == "; break;
580       case Instruction::SetNE: Out << " != "; break;
581       case Instruction::SetLT: Out << " < "; break;
582       case Instruction::SetLE: Out << " <= "; break;
583       case Instruction::SetGT: Out << " > "; break;
584       case Instruction::SetGE: Out << " >= "; break;
585       case Instruction::Shl: Out << " << "; break;
586       case Instruction::Shr: Out << " >> "; break;
587       default: assert(0 && "Illegal opcode here!");
588       }
589       printConstant(CE->getOperand(1));
590       Out << ')';
591       return;
592
593     default:
594       std::cerr << "CWriter Error: Unhandled constant expression: "
595                 << *CE << "\n";
596       abort();
597     }
598   } else if (isa<UndefValue>(CPV) && CPV->getType()->isFirstClassType()) {
599     Out << "((";
600     printType(Out, CPV->getType());
601     Out << ")/*UNDEF*/0)";
602     return;
603   }
604
605   switch (CPV->getType()->getTypeID()) {
606   case Type::BoolTyID:
607     Out << (CPV == ConstantBool::False ? '0' : '1'); break;
608   case Type::SByteTyID:
609   case Type::ShortTyID:
610     Out << cast<ConstantSInt>(CPV)->getValue(); break;
611   case Type::IntTyID:
612     if ((int)cast<ConstantSInt>(CPV)->getValue() == (int)0x80000000)
613       Out << "((int)0x80000000U)";   // Handle MININT specially to avoid warning
614     else
615       Out << cast<ConstantSInt>(CPV)->getValue();
616     break;
617
618   case Type::LongTyID:
619     if (cast<ConstantSInt>(CPV)->isMinValue())
620       Out << "(/*INT64_MIN*/(-9223372036854775807LL)-1)";
621     else
622       Out << cast<ConstantSInt>(CPV)->getValue() << "ll"; break;
623
624   case Type::UByteTyID:
625   case Type::UShortTyID:
626     Out << cast<ConstantUInt>(CPV)->getValue(); break;
627   case Type::UIntTyID:
628     Out << cast<ConstantUInt>(CPV)->getValue() << 'u'; break;
629   case Type::ULongTyID:
630     Out << cast<ConstantUInt>(CPV)->getValue() << "ull"; break;
631
632   case Type::FloatTyID:
633   case Type::DoubleTyID: {
634     ConstantFP *FPC = cast<ConstantFP>(CPV);
635     std::map<const ConstantFP*, unsigned>::iterator I = FPConstantMap.find(FPC);
636     if (I != FPConstantMap.end()) {
637       // Because of FP precision problems we must load from a stack allocated
638       // value that holds the value in hex.
639       Out << "(*(" << (FPC->getType() == Type::FloatTy ? "float" : "double")
640           << "*)&FPConstant" << I->second << ')';
641     } else {
642       if (IsNAN(FPC->getValue())) {
643         // The value is NaN
644
645         // The prefix for a quiet NaN is 0x7FF8. For a signalling NaN,
646         // it's 0x7ff4.
647         const unsigned long QuietNaN = 0x7ff8UL;
648         const unsigned long SignalNaN = 0x7ff4UL;
649
650         // We need to grab the first part of the FP #
651         char Buffer[100];
652
653         uint64_t ll = DoubleToBits(FPC->getValue());
654         sprintf(Buffer, "0x%llx", (unsigned long long)ll);
655
656         std::string Num(&Buffer[0], &Buffer[6]);
657         unsigned long Val = strtoul(Num.c_str(), 0, 16);
658
659         if (FPC->getType() == Type::FloatTy)
660           Out << "LLVM_NAN" << (Val == QuietNaN ? "" : "S") << "F(\""
661               << Buffer << "\") /*nan*/ ";
662         else
663           Out << "LLVM_NAN" << (Val == QuietNaN ? "" : "S") << "(\""
664               << Buffer << "\") /*nan*/ ";
665       } else if (IsInf(FPC->getValue())) {
666         // The value is Inf
667         if (FPC->getValue() < 0) Out << '-';
668         Out << "LLVM_INF" << (FPC->getType() == Type::FloatTy ? "F" : "")
669             << " /*inf*/ ";
670       } else {
671         std::string Num;
672 #if HAVE_PRINTF_A
673         // Print out the constant as a floating point number.
674         char Buffer[100];
675         sprintf(Buffer, "%a", FPC->getValue());
676         Num = Buffer;
677 #else
678         Num = ftostr(FPC->getValue());
679 #endif
680         Out << Num;
681       }
682     }
683     break;
684   }
685
686   case Type::ArrayTyID:
687     if (isa<ConstantAggregateZero>(CPV) || isa<UndefValue>(CPV)) {
688       const ArrayType *AT = cast<ArrayType>(CPV->getType());
689       Out << '{';
690       if (AT->getNumElements()) {
691         Out << ' ';
692         Constant *CZ = Constant::getNullValue(AT->getElementType());
693         printConstant(CZ);
694         for (unsigned i = 1, e = AT->getNumElements(); i != e; ++i) {
695           Out << ", ";
696           printConstant(CZ);
697         }
698       }
699       Out << " }";
700     } else {
701       printConstantArray(cast<ConstantArray>(CPV));
702     }
703     break;
704
705   case Type::PackedTyID:
706     if (isa<ConstantAggregateZero>(CPV) || isa<UndefValue>(CPV)) {
707       const PackedType *AT = cast<PackedType>(CPV->getType());
708       Out << '{';
709       if (AT->getNumElements()) {
710         Out << ' ';
711         Constant *CZ = Constant::getNullValue(AT->getElementType());
712         printConstant(CZ);
713         for (unsigned i = 1, e = AT->getNumElements(); i != e; ++i) {
714           Out << ", ";
715           printConstant(CZ);
716         }
717       }
718       Out << " }";
719     } else {
720       printConstantPacked(cast<ConstantPacked>(CPV));
721     }
722     break;
723
724   case Type::StructTyID:
725     if (isa<ConstantAggregateZero>(CPV) || isa<UndefValue>(CPV)) {
726       const StructType *ST = cast<StructType>(CPV->getType());
727       Out << '{';
728       if (ST->getNumElements()) {
729         Out << ' ';
730         printConstant(Constant::getNullValue(ST->getElementType(0)));
731         for (unsigned i = 1, e = ST->getNumElements(); i != e; ++i) {
732           Out << ", ";
733           printConstant(Constant::getNullValue(ST->getElementType(i)));
734         }
735       }
736       Out << " }";
737     } else {
738       Out << '{';
739       if (CPV->getNumOperands()) {
740         Out << ' ';
741         printConstant(cast<Constant>(CPV->getOperand(0)));
742         for (unsigned i = 1, e = CPV->getNumOperands(); i != e; ++i) {
743           Out << ", ";
744           printConstant(cast<Constant>(CPV->getOperand(i)));
745         }
746       }
747       Out << " }";
748     }
749     break;
750
751   case Type::PointerTyID:
752     if (isa<ConstantPointerNull>(CPV)) {
753       Out << "((";
754       printType(Out, CPV->getType());
755       Out << ")/*NULL*/0)";
756       break;
757     } else if (GlobalValue *GV = dyn_cast<GlobalValue>(CPV)) {
758       writeOperand(GV);
759       break;
760     }
761     // FALL THROUGH
762   default:
763     std::cerr << "Unknown constant type: " << *CPV << "\n";
764     abort();
765   }
766 }
767
768 void CWriter::writeOperandInternal(Value *Operand) {
769   if (Instruction *I = dyn_cast<Instruction>(Operand))
770     if (isInlinableInst(*I) && !isDirectAlloca(I)) {
771       // Should we inline this instruction to build a tree?
772       Out << '(';
773       visit(*I);
774       Out << ')';
775       return;
776     }
777
778   Constant* CPV = dyn_cast<Constant>(Operand);
779   if (CPV && !isa<GlobalValue>(CPV)) {
780     printConstant(CPV);
781   } else {
782     Out << Mang->getValueName(Operand);
783   }
784 }
785
786 void CWriter::writeOperand(Value *Operand) {
787   if (isa<GlobalVariable>(Operand) || isDirectAlloca(Operand))
788     Out << "(&";  // Global variables are references as their addresses by llvm
789
790   writeOperandInternal(Operand);
791
792   if (isa<GlobalVariable>(Operand) || isDirectAlloca(Operand))
793     Out << ')';
794 }
795
796 // generateCompilerSpecificCode - This is where we add conditional compilation
797 // directives to cater to specific compilers as need be.
798 //
799 static void generateCompilerSpecificCode(std::ostream& Out) {
800   // Alloca is hard to get, and we don't want to include stdlib.h here.
801   Out << "/* get a declaration for alloca */\n"
802       << "#if defined(__CYGWIN__)\n"
803       << "extern void *_alloca(unsigned long);\n"
804       << "#define alloca(x) _alloca(x)\n"
805       << "#elif defined(__APPLE__)\n"
806       << "extern void *__builtin_alloca(unsigned long);\n"
807       << "#define alloca(x) __builtin_alloca(x)\n"
808       << "#elif defined(__sun__)\n"
809       << "#if defined(__sparcv9)\n"
810       << "extern void *__builtin_alloca(unsigned long);\n"
811       << "#else\n"
812       << "extern void *__builtin_alloca(unsigned int);\n"
813       << "#endif\n"
814       << "#define alloca(x) __builtin_alloca(x)\n"
815       << "#elif defined(__FreeBSD__)\n"
816       << "#define alloca(x) __builtin_alloca(x)\n"
817       << "#elif !defined(_MSC_VER)\n"
818       << "#include <alloca.h>\n"
819       << "#endif\n\n";
820
821   // We output GCC specific attributes to preserve 'linkonce'ness on globals.
822   // If we aren't being compiled with GCC, just drop these attributes.
823   Out << "#ifndef __GNUC__  /* Can only support \"linkonce\" vars with GCC */\n"
824       << "#define __attribute__(X)\n"
825       << "#endif\n\n";
826
827 #if 0
828   // At some point, we should support "external weak" vs. "weak" linkages.
829   // On Mac OS X, "external weak" is spelled "__attribute__((weak_import))".
830   Out << "#if defined(__GNUC__) && defined(__APPLE_CC__)\n"
831       << "#define __EXTERNAL_WEAK__ __attribute__((weak_import))\n"
832       << "#elif defined(__GNUC__)\n"
833       << "#define __EXTERNAL_WEAK__ __attribute__((weak))\n"
834       << "#else\n"
835       << "#define __EXTERNAL_WEAK__\n"
836       << "#endif\n\n";
837 #endif
838
839   // For now, turn off the weak linkage attribute on Mac OS X. (See above.)
840   Out << "#if defined(__GNUC__) && defined(__APPLE_CC__)\n"
841       << "#define __ATTRIBUTE_WEAK__\n"
842       << "#elif defined(__GNUC__)\n"
843       << "#define __ATTRIBUTE_WEAK__ __attribute__((weak))\n"
844       << "#else\n"
845       << "#define __ATTRIBUTE_WEAK__\n"
846       << "#endif\n\n";
847
848   // Define NaN and Inf as GCC builtins if using GCC, as 0 otherwise
849   // From the GCC documentation:
850   //
851   //   double __builtin_nan (const char *str)
852   //
853   // This is an implementation of the ISO C99 function nan.
854   //
855   // Since ISO C99 defines this function in terms of strtod, which we do
856   // not implement, a description of the parsing is in order. The string is
857   // parsed as by strtol; that is, the base is recognized by leading 0 or
858   // 0x prefixes. The number parsed is placed in the significand such that
859   // the least significant bit of the number is at the least significant
860   // bit of the significand. The number is truncated to fit the significand
861   // field provided. The significand is forced to be a quiet NaN.
862   //
863   // This function, if given a string literal, is evaluated early enough
864   // that it is considered a compile-time constant.
865   //
866   //   float __builtin_nanf (const char *str)
867   //
868   // Similar to __builtin_nan, except the return type is float.
869   //
870   //   double __builtin_inf (void)
871   //
872   // Similar to __builtin_huge_val, except a warning is generated if the
873   // target floating-point format does not support infinities. This
874   // function is suitable for implementing the ISO C99 macro INFINITY.
875   //
876   //   float __builtin_inff (void)
877   //
878   // Similar to __builtin_inf, except the return type is float.
879   Out << "#ifdef __GNUC__\n"
880       << "#define LLVM_NAN(NanStr)   __builtin_nan(NanStr)   /* Double */\n"
881       << "#define LLVM_NANF(NanStr)  __builtin_nanf(NanStr)  /* Float */\n"
882       << "#define LLVM_NANS(NanStr)  __builtin_nans(NanStr)  /* Double */\n"
883       << "#define LLVM_NANSF(NanStr) __builtin_nansf(NanStr) /* Float */\n"
884       << "#define LLVM_INF           __builtin_inf()         /* Double */\n"
885       << "#define LLVM_INFF          __builtin_inff()        /* Float */\n"
886       << "#define LLVM_PREFETCH(addr,rw,locality) "
887                               "__builtin_prefetch(addr,rw,locality)\n"
888       << "#define __ATTRIBUTE_CTOR__ __attribute__((constructor))\n"
889       << "#define __ATTRIBUTE_DTOR__ __attribute__((destructor))\n"
890       << "#else\n"
891       << "#define LLVM_NAN(NanStr)   ((double)0.0)           /* Double */\n"
892       << "#define LLVM_NANF(NanStr)  0.0F                    /* Float */\n"
893       << "#define LLVM_NANS(NanStr)  ((double)0.0)           /* Double */\n"
894       << "#define LLVM_NANSF(NanStr) 0.0F                    /* Float */\n"
895       << "#define LLVM_INF           ((double)0.0)           /* Double */\n"
896       << "#define LLVM_INFF          0.0F                    /* Float */\n"
897       << "#define LLVM_PREFETCH(addr,rw,locality)            /* PREFETCH */\n"
898       << "#define __ATTRIBUTE_CTOR__\n"
899       << "#define __ATTRIBUTE_DTOR__\n"
900       << "#endif\n\n";
901
902   // Output target-specific code that should be inserted into main.
903   Out << "#define CODE_FOR_MAIN() /* Any target-specific code for main()*/\n";
904   // On X86, set the FP control word to 64-bits of precision instead of 80 bits.
905   Out << "#if defined(__GNUC__) && !defined(__llvm__)\n"
906       << "#if defined(i386) || defined(__i386__) || defined(__i386)\n"
907       << "#undef CODE_FOR_MAIN\n"
908       << "#define CODE_FOR_MAIN() \\\n"
909       << "  {short F;__asm__ (\"fnstcw %0\" : \"=m\" (*&F)); \\\n"
910       << "  F=(F&~0x300)|0x200;__asm__(\"fldcw %0\"::\"m\"(*&F));}\n"
911       << "#endif\n#endif\n";
912
913 }
914
915 /// FindStaticTors - Given a static ctor/dtor list, unpack its contents into
916 /// the StaticTors set.
917 static void FindStaticTors(GlobalVariable *GV, std::set<Function*> &StaticTors){
918   ConstantArray *InitList = dyn_cast<ConstantArray>(GV->getInitializer());
919   if (!InitList) return;
920   
921   for (unsigned i = 0, e = InitList->getNumOperands(); i != e; ++i)
922     if (ConstantStruct *CS = dyn_cast<ConstantStruct>(InitList->getOperand(i))){
923       if (CS->getNumOperands() != 2) return;  // Not array of 2-element structs.
924       
925       if (CS->getOperand(1)->isNullValue())
926         return;  // Found a null terminator, exit printing.
927       Constant *FP = CS->getOperand(1);
928       if (ConstantExpr *CE = dyn_cast<ConstantExpr>(FP))
929         if (CE->getOpcode() == Instruction::Cast)
930           FP = CE->getOperand(0);
931       if (Function *F = dyn_cast<Function>(FP))
932         StaticTors.insert(F);
933     }
934 }
935
936 enum SpecialGlobalClass {
937   NotSpecial = 0,
938   GlobalCtors, GlobalDtors,
939   NotPrinted
940 };
941
942 /// getGlobalVariableClass - If this is a global that is specially recognized
943 /// by LLVM, return a code that indicates how we should handle it.
944 static SpecialGlobalClass getGlobalVariableClass(const GlobalVariable *GV) {
945   // If this is a global ctors/dtors list, handle it now.
946   if (GV->hasAppendingLinkage() && GV->use_empty()) {
947     if (GV->getName() == "llvm.global_ctors")
948       return GlobalCtors;
949     else if (GV->getName() == "llvm.global_dtors")
950       return GlobalDtors;
951   }
952   
953   // Otherwise, it it is other metadata, don't print it.  This catches things
954   // like debug information.
955   if (GV->getSection() == "llvm.metadata")
956     return NotPrinted;
957   
958   return NotSpecial;
959 }
960
961
962 bool CWriter::doInitialization(Module &M) {
963   // Initialize
964   TheModule = &M;
965
966   IL.AddPrototypes(M);
967
968   // Ensure that all structure types have names...
969   Mang = new Mangler(M);
970   Mang->markCharUnacceptable('.');
971
972   // Keep track of which functions are static ctors/dtors so they can have
973   // an attribute added to their prototypes.
974   std::set<Function*> StaticCtors, StaticDtors;
975   for (Module::global_iterator I = M.global_begin(), E = M.global_end();
976        I != E; ++I) {
977     switch (getGlobalVariableClass(I)) {
978     default: break;
979     case GlobalCtors:
980       FindStaticTors(I, StaticCtors);
981       break;
982     case GlobalDtors:
983       FindStaticTors(I, StaticDtors);
984       break;
985     }
986   }
987   
988   // get declaration for alloca
989   Out << "/* Provide Declarations */\n";
990   Out << "#include <stdarg.h>\n";      // Varargs support
991   Out << "#include <setjmp.h>\n";      // Unwind support
992   generateCompilerSpecificCode(Out);
993
994   // Provide a definition for `bool' if not compiling with a C++ compiler.
995   Out << "\n"
996       << "#ifndef __cplusplus\ntypedef unsigned char bool;\n#endif\n"
997
998       << "\n\n/* Support for floating point constants */\n"
999       << "typedef unsigned long long ConstantDoubleTy;\n"
1000       << "typedef unsigned int        ConstantFloatTy;\n"
1001
1002       << "\n\n/* Global Declarations */\n";
1003
1004   // First output all the declarations for the program, because C requires
1005   // Functions & globals to be declared before they are used.
1006   //
1007
1008   // Loop over the symbol table, emitting all named constants...
1009   printModuleTypes(M.getSymbolTable());
1010
1011   // Global variable declarations...
1012   if (!M.global_empty()) {
1013     Out << "\n/* External Global Variable Declarations */\n";
1014     for (Module::global_iterator I = M.global_begin(), E = M.global_end();
1015          I != E; ++I) {
1016       if (I->hasExternalLinkage()) {
1017         Out << "extern ";
1018         printType(Out, I->getType()->getElementType(), Mang->getValueName(I));
1019         Out << ";\n";
1020       }
1021     }
1022   }
1023
1024   // Function declarations
1025   Out << "\n/* Function Declarations */\n";
1026   Out << "double fmod(double, double);\n";   // Support for FP rem
1027   Out << "float fmodf(float, float);\n";
1028   
1029   for (Module::iterator I = M.begin(), E = M.end(); I != E; ++I) {
1030     // Don't print declarations for intrinsic functions.
1031     if (!I->getIntrinsicID() &&
1032         I->getName() != "setjmp" && I->getName() != "longjmp") {
1033       printFunctionSignature(I, true);
1034       if (I->hasWeakLinkage() || I->hasLinkOnceLinkage()) 
1035         Out << " __ATTRIBUTE_WEAK__";
1036       if (StaticCtors.count(I))
1037         Out << " __ATTRIBUTE_CTOR__";
1038       if (StaticDtors.count(I))
1039         Out << " __ATTRIBUTE_DTOR__";
1040       Out << ";\n";
1041     }
1042   }
1043
1044   // Output the global variable declarations
1045   if (!M.global_empty()) {
1046     Out << "\n\n/* Global Variable Declarations */\n";
1047     for (Module::global_iterator I = M.global_begin(), E = M.global_end();
1048          I != E; ++I)
1049       if (!I->isExternal()) {
1050         // Ignore special globals, such as debug info.
1051         if (getGlobalVariableClass(I))
1052           continue;
1053         
1054         if (I->hasInternalLinkage())
1055           Out << "static ";
1056         else
1057           Out << "extern ";
1058         printType(Out, I->getType()->getElementType(), Mang->getValueName(I));
1059
1060         if (I->hasLinkOnceLinkage())
1061           Out << " __attribute__((common))";
1062         else if (I->hasWeakLinkage())
1063           Out << " __ATTRIBUTE_WEAK__";
1064         Out << ";\n";
1065       }
1066   }
1067
1068   // Output the global variable definitions and contents...
1069   if (!M.global_empty()) {
1070     Out << "\n\n/* Global Variable Definitions and Initialization */\n";
1071     for (Module::global_iterator I = M.global_begin(), E = M.global_end(); 
1072          I != E; ++I)
1073       if (!I->isExternal()) {
1074         // Ignore special globals, such as debug info.
1075         if (getGlobalVariableClass(I))
1076           continue;
1077         
1078         if (I->hasInternalLinkage())
1079           Out << "static ";
1080         printType(Out, I->getType()->getElementType(), Mang->getValueName(I));
1081         if (I->hasLinkOnceLinkage())
1082           Out << " __attribute__((common))";
1083         else if (I->hasWeakLinkage())
1084           Out << " __ATTRIBUTE_WEAK__";
1085
1086         // If the initializer is not null, emit the initializer.  If it is null,
1087         // we try to avoid emitting large amounts of zeros.  The problem with
1088         // this, however, occurs when the variable has weak linkage.  In this
1089         // case, the assembler will complain about the variable being both weak
1090         // and common, so we disable this optimization.
1091         if (!I->getInitializer()->isNullValue()) {
1092           Out << " = " ;
1093           writeOperand(I->getInitializer());
1094         } else if (I->hasWeakLinkage()) {
1095           // We have to specify an initializer, but it doesn't have to be
1096           // complete.  If the value is an aggregate, print out { 0 }, and let
1097           // the compiler figure out the rest of the zeros.
1098           Out << " = " ;
1099           if (isa<StructType>(I->getInitializer()->getType()) ||
1100               isa<ArrayType>(I->getInitializer()->getType()) ||
1101               isa<PackedType>(I->getInitializer()->getType())) {
1102             Out << "{ 0 }";
1103           } else {
1104             // Just print it out normally.
1105             writeOperand(I->getInitializer());
1106           }
1107         }
1108         Out << ";\n";
1109       }
1110   }
1111
1112   if (!M.empty())
1113     Out << "\n\n/* Function Bodies */\n";
1114   return false;
1115 }
1116
1117
1118 /// Output all floating point constants that cannot be printed accurately...
1119 void CWriter::printFloatingPointConstants(Function &F) {
1120   // Scan the module for floating point constants.  If any FP constant is used
1121   // in the function, we want to redirect it here so that we do not depend on
1122   // the precision of the printed form, unless the printed form preserves
1123   // precision.
1124   //
1125   static unsigned FPCounter = 0;
1126   for (constant_iterator I = constant_begin(&F), E = constant_end(&F);
1127        I != E; ++I)
1128     if (const ConstantFP *FPC = dyn_cast<ConstantFP>(*I))
1129       if (!isFPCSafeToPrint(FPC) && // Do not put in FPConstantMap if safe.
1130           !FPConstantMap.count(FPC)) {
1131         double Val = FPC->getValue();
1132
1133         FPConstantMap[FPC] = FPCounter;  // Number the FP constants
1134
1135         if (FPC->getType() == Type::DoubleTy) {
1136           Out << "static const ConstantDoubleTy FPConstant" << FPCounter++
1137               << " = 0x" << std::hex << DoubleToBits(Val) << std::dec
1138               << "ULL;    /* " << Val << " */\n";
1139         } else if (FPC->getType() == Type::FloatTy) {
1140           Out << "static const ConstantFloatTy FPConstant" << FPCounter++
1141               << " = 0x" << std::hex << FloatToBits(Val) << std::dec
1142               << "U;    /* " << Val << " */\n";
1143         } else
1144           assert(0 && "Unknown float type!");
1145       }
1146
1147   Out << '\n';
1148 }
1149
1150
1151 /// printSymbolTable - Run through symbol table looking for type names.  If a
1152 /// type name is found, emit its declaration...
1153 ///
1154 void CWriter::printModuleTypes(const SymbolTable &ST) {
1155   // We are only interested in the type plane of the symbol table.
1156   SymbolTable::type_const_iterator I   = ST.type_begin();
1157   SymbolTable::type_const_iterator End = ST.type_end();
1158
1159   // If there are no type names, exit early.
1160   if (I == End) return;
1161
1162   // Print out forward declarations for structure types before anything else!
1163   Out << "/* Structure forward decls */\n";
1164   for (; I != End; ++I)
1165     if (const Type *STy = dyn_cast<StructType>(I->second)) {
1166       std::string Name = "struct l_" + Mang->makeNameProper(I->first);
1167       Out << Name << ";\n";
1168       TypeNames.insert(std::make_pair(STy, Name));
1169     }
1170
1171   Out << '\n';
1172
1173   // Now we can print out typedefs...
1174   Out << "/* Typedefs */\n";
1175   for (I = ST.type_begin(); I != End; ++I) {
1176     const Type *Ty = cast<Type>(I->second);
1177     std::string Name = "l_" + Mang->makeNameProper(I->first);
1178     Out << "typedef ";
1179     printType(Out, Ty, Name);
1180     Out << ";\n";
1181   }
1182
1183   Out << '\n';
1184
1185   // Keep track of which structures have been printed so far...
1186   std::set<const StructType *> StructPrinted;
1187
1188   // Loop over all structures then push them into the stack so they are
1189   // printed in the correct order.
1190   //
1191   Out << "/* Structure contents */\n";
1192   for (I = ST.type_begin(); I != End; ++I)
1193     if (const StructType *STy = dyn_cast<StructType>(I->second))
1194       // Only print out used types!
1195       printContainedStructs(STy, StructPrinted);
1196 }
1197
1198 // Push the struct onto the stack and recursively push all structs
1199 // this one depends on.
1200 //
1201 // TODO:  Make this work properly with packed types
1202 //
1203 void CWriter::printContainedStructs(const Type *Ty,
1204                                     std::set<const StructType*> &StructPrinted){
1205   // Don't walk through pointers.
1206   if (isa<PointerType>(Ty) || Ty->isPrimitiveType()) return;
1207   
1208   // Print all contained types first.
1209   for (Type::subtype_iterator I = Ty->subtype_begin(),
1210        E = Ty->subtype_end(); I != E; ++I)
1211     printContainedStructs(*I, StructPrinted);
1212   
1213   if (const StructType *STy = dyn_cast<StructType>(Ty)) {
1214     // Check to see if we have already printed this struct.
1215     if (StructPrinted.insert(STy).second) {
1216       // Print structure type out.
1217       std::string Name = TypeNames[STy];
1218       printType(Out, STy, Name, true);
1219       Out << ";\n\n";
1220     }
1221   }
1222 }
1223
1224 void CWriter::printFunctionSignature(const Function *F, bool Prototype) {
1225   if (F->hasInternalLinkage()) Out << "static ";
1226
1227   // Loop over the arguments, printing them...
1228   const FunctionType *FT = cast<FunctionType>(F->getFunctionType());
1229
1230   std::stringstream FunctionInnards;
1231
1232   // Print out the name...
1233   FunctionInnards << Mang->getValueName(F) << '(';
1234
1235   if (!F->isExternal()) {
1236     if (!F->arg_empty()) {
1237       std::string ArgName;
1238       if (F->arg_begin()->hasName() || !Prototype)
1239         ArgName = Mang->getValueName(F->arg_begin());
1240       printType(FunctionInnards, F->arg_begin()->getType(), ArgName);
1241       for (Function::const_arg_iterator I = ++F->arg_begin(), E = F->arg_end();
1242            I != E; ++I) {
1243         FunctionInnards << ", ";
1244         if (I->hasName() || !Prototype)
1245           ArgName = Mang->getValueName(I);
1246         else
1247           ArgName = "";
1248         printType(FunctionInnards, I->getType(), ArgName);
1249       }
1250     }
1251   } else {
1252     // Loop over the arguments, printing them...
1253     for (FunctionType::param_iterator I = FT->param_begin(),
1254            E = FT->param_end(); I != E; ++I) {
1255       if (I != FT->param_begin()) FunctionInnards << ", ";
1256       printType(FunctionInnards, *I);
1257     }
1258   }
1259
1260   // Finish printing arguments... if this is a vararg function, print the ...,
1261   // unless there are no known types, in which case, we just emit ().
1262   //
1263   if (FT->isVarArg() && FT->getNumParams()) {
1264     if (FT->getNumParams()) FunctionInnards << ", ";
1265     FunctionInnards << "...";  // Output varargs portion of signature!
1266   } else if (!FT->isVarArg() && FT->getNumParams() == 0) {
1267     FunctionInnards << "void"; // ret() -> ret(void) in C.
1268   }
1269   FunctionInnards << ')';
1270   // Print out the return type and the entire signature for that matter
1271   printType(Out, F->getReturnType(), FunctionInnards.str());
1272 }
1273
1274 void CWriter::printFunction(Function &F) {
1275   printFunctionSignature(&F, false);
1276   Out << " {\n";
1277
1278   // print local variable information for the function
1279   for (inst_iterator I = inst_begin(&F), E = inst_end(&F); I != E; ++I)
1280     if (const AllocaInst *AI = isDirectAlloca(&*I)) {
1281       Out << "  ";
1282       printType(Out, AI->getAllocatedType(), Mang->getValueName(AI));
1283       Out << ";    /* Address-exposed local */\n";
1284     } else if (I->getType() != Type::VoidTy && !isInlinableInst(*I)) {
1285       Out << "  ";
1286       printType(Out, I->getType(), Mang->getValueName(&*I));
1287       Out << ";\n";
1288
1289       if (isa<PHINode>(*I)) {  // Print out PHI node temporaries as well...
1290         Out << "  ";
1291         printType(Out, I->getType(),
1292                   Mang->getValueName(&*I)+"__PHI_TEMPORARY");
1293         Out << ";\n";
1294       }
1295     }
1296
1297   Out << '\n';
1298
1299   if (F.hasExternalLinkage() && F.getName() == "main")
1300     Out << "  CODE_FOR_MAIN();\n";
1301
1302   // print the basic blocks
1303   for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB) {
1304     if (Loop *L = LI->getLoopFor(BB)) {
1305       if (L->getHeader() == BB && L->getParentLoop() == 0)
1306         printLoop(L);
1307     } else {
1308       printBasicBlock(BB);
1309     }
1310   }
1311
1312   Out << "}\n\n";
1313 }
1314
1315 void CWriter::printLoop(Loop *L) {
1316   Out << "  do {     /* Syntactic loop '" << L->getHeader()->getName()
1317       << "' to make GCC happy */\n";
1318   for (unsigned i = 0, e = L->getBlocks().size(); i != e; ++i) {
1319     BasicBlock *BB = L->getBlocks()[i];
1320     Loop *BBLoop = LI->getLoopFor(BB);
1321     if (BBLoop == L)
1322       printBasicBlock(BB);
1323     else if (BB == BBLoop->getHeader() && BBLoop->getParentLoop() == L)
1324       printLoop(BBLoop);
1325   }
1326   Out << "  } while (1); /* end of syntactic loop '"
1327       << L->getHeader()->getName() << "' */\n";
1328 }
1329
1330 void CWriter::printBasicBlock(BasicBlock *BB) {
1331
1332   // Don't print the label for the basic block if there are no uses, or if
1333   // the only terminator use is the predecessor basic block's terminator.
1334   // We have to scan the use list because PHI nodes use basic blocks too but
1335   // do not require a label to be generated.
1336   //
1337   bool NeedsLabel = false;
1338   for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI)
1339     if (isGotoCodeNecessary(*PI, BB)) {
1340       NeedsLabel = true;
1341       break;
1342     }
1343
1344   if (NeedsLabel) Out << Mang->getValueName(BB) << ":\n";
1345
1346   // Output all of the instructions in the basic block...
1347   for (BasicBlock::iterator II = BB->begin(), E = --BB->end(); II != E;
1348        ++II) {
1349     if (!isInlinableInst(*II) && !isDirectAlloca(II)) {
1350       if (II->getType() != Type::VoidTy)
1351         outputLValue(II);
1352       else
1353         Out << "  ";
1354       visit(*II);
1355       Out << ";\n";
1356     }
1357   }
1358
1359   // Don't emit prefix or suffix for the terminator...
1360   visit(*BB->getTerminator());
1361 }
1362
1363
1364 // Specific Instruction type classes... note that all of the casts are
1365 // necessary because we use the instruction classes as opaque types...
1366 //
1367 void CWriter::visitReturnInst(ReturnInst &I) {
1368   // Don't output a void return if this is the last basic block in the function
1369   if (I.getNumOperands() == 0 &&
1370       &*--I.getParent()->getParent()->end() == I.getParent() &&
1371       !I.getParent()->size() == 1) {
1372     return;
1373   }
1374
1375   Out << "  return";
1376   if (I.getNumOperands()) {
1377     Out << ' ';
1378     writeOperand(I.getOperand(0));
1379   }
1380   Out << ";\n";
1381 }
1382
1383 void CWriter::visitSwitchInst(SwitchInst &SI) {
1384
1385   Out << "  switch (";
1386   writeOperand(SI.getOperand(0));
1387   Out << ") {\n  default:\n";
1388   printPHICopiesForSuccessor (SI.getParent(), SI.getDefaultDest(), 2);
1389   printBranchToBlock(SI.getParent(), SI.getDefaultDest(), 2);
1390   Out << ";\n";
1391   for (unsigned i = 2, e = SI.getNumOperands(); i != e; i += 2) {
1392     Out << "  case ";
1393     writeOperand(SI.getOperand(i));
1394     Out << ":\n";
1395     BasicBlock *Succ = cast<BasicBlock>(SI.getOperand(i+1));
1396     printPHICopiesForSuccessor (SI.getParent(), Succ, 2);
1397     printBranchToBlock(SI.getParent(), Succ, 2);
1398     if (Function::iterator(Succ) == next(Function::iterator(SI.getParent())))
1399       Out << "    break;\n";
1400   }
1401   Out << "  }\n";
1402 }
1403
1404 void CWriter::visitUnreachableInst(UnreachableInst &I) {
1405   Out << "  /*UNREACHABLE*/;\n";
1406 }
1407
1408 bool CWriter::isGotoCodeNecessary(BasicBlock *From, BasicBlock *To) {
1409   /// FIXME: This should be reenabled, but loop reordering safe!!
1410   return true;
1411
1412   if (next(Function::iterator(From)) != Function::iterator(To))
1413     return true;  // Not the direct successor, we need a goto.
1414
1415   //isa<SwitchInst>(From->getTerminator())
1416
1417   if (LI->getLoopFor(From) != LI->getLoopFor(To))
1418     return true;
1419   return false;
1420 }
1421
1422 void CWriter::printPHICopiesForSuccessor (BasicBlock *CurBlock,
1423                                           BasicBlock *Successor,
1424                                           unsigned Indent) {
1425   for (BasicBlock::iterator I = Successor->begin(); isa<PHINode>(I); ++I) {
1426     PHINode *PN = cast<PHINode>(I);
1427     // Now we have to do the printing.
1428     Value *IV = PN->getIncomingValueForBlock(CurBlock);
1429     if (!isa<UndefValue>(IV)) {
1430       Out << std::string(Indent, ' ');
1431       Out << "  " << Mang->getValueName(I) << "__PHI_TEMPORARY = ";
1432       writeOperand(IV);
1433       Out << ";   /* for PHI node */\n";
1434     }
1435   }
1436 }
1437
1438 void CWriter::printBranchToBlock(BasicBlock *CurBB, BasicBlock *Succ,
1439                                  unsigned Indent) {
1440   if (isGotoCodeNecessary(CurBB, Succ)) {
1441     Out << std::string(Indent, ' ') << "  goto ";
1442     writeOperand(Succ);
1443     Out << ";\n";
1444   }
1445 }
1446
1447 // Branch instruction printing - Avoid printing out a branch to a basic block
1448 // that immediately succeeds the current one.
1449 //
1450 void CWriter::visitBranchInst(BranchInst &I) {
1451
1452   if (I.isConditional()) {
1453     if (isGotoCodeNecessary(I.getParent(), I.getSuccessor(0))) {
1454       Out << "  if (";
1455       writeOperand(I.getCondition());
1456       Out << ") {\n";
1457
1458       printPHICopiesForSuccessor (I.getParent(), I.getSuccessor(0), 2);
1459       printBranchToBlock(I.getParent(), I.getSuccessor(0), 2);
1460
1461       if (isGotoCodeNecessary(I.getParent(), I.getSuccessor(1))) {
1462         Out << "  } else {\n";
1463         printPHICopiesForSuccessor (I.getParent(), I.getSuccessor(1), 2);
1464         printBranchToBlock(I.getParent(), I.getSuccessor(1), 2);
1465       }
1466     } else {
1467       // First goto not necessary, assume second one is...
1468       Out << "  if (!";
1469       writeOperand(I.getCondition());
1470       Out << ") {\n";
1471
1472       printPHICopiesForSuccessor (I.getParent(), I.getSuccessor(1), 2);
1473       printBranchToBlock(I.getParent(), I.getSuccessor(1), 2);
1474     }
1475
1476     Out << "  }\n";
1477   } else {
1478     printPHICopiesForSuccessor (I.getParent(), I.getSuccessor(0), 0);
1479     printBranchToBlock(I.getParent(), I.getSuccessor(0), 0);
1480   }
1481   Out << "\n";
1482 }
1483
1484 // PHI nodes get copied into temporary values at the end of predecessor basic
1485 // blocks.  We now need to copy these temporary values into the REAL value for
1486 // the PHI.
1487 void CWriter::visitPHINode(PHINode &I) {
1488   writeOperand(&I);
1489   Out << "__PHI_TEMPORARY";
1490 }
1491
1492
1493 void CWriter::visitBinaryOperator(Instruction &I) {
1494   // binary instructions, shift instructions, setCond instructions.
1495   assert(!isa<PointerType>(I.getType()));
1496
1497   // We must cast the results of binary operations which might be promoted.
1498   bool needsCast = false;
1499   if ((I.getType() == Type::UByteTy) || (I.getType() == Type::SByteTy)
1500       || (I.getType() == Type::UShortTy) || (I.getType() == Type::ShortTy)
1501       || (I.getType() == Type::FloatTy)) {
1502     needsCast = true;
1503     Out << "((";
1504     printType(Out, I.getType());
1505     Out << ")(";
1506   }
1507
1508   // If this is a negation operation, print it out as such.  For FP, we don't
1509   // want to print "-0.0 - X".
1510   if (BinaryOperator::isNeg(&I)) {
1511     Out << "-(";
1512     writeOperand(BinaryOperator::getNegArgument(cast<BinaryOperator>(&I)));
1513     Out << ")";
1514   } else if (I.getOpcode() == Instruction::Rem && 
1515              I.getType()->isFloatingPoint()) {
1516     // Output a call to fmod/fmodf instead of emitting a%b
1517     if (I.getType() == Type::FloatTy)
1518       Out << "fmodf(";
1519     else
1520       Out << "fmod(";
1521     writeOperand(I.getOperand(0));
1522     Out << ", ";
1523     writeOperand(I.getOperand(1));
1524     Out << ")";
1525   } else {
1526     writeOperand(I.getOperand(0));
1527
1528     switch (I.getOpcode()) {
1529     case Instruction::Add: Out << " + "; break;
1530     case Instruction::Sub: Out << " - "; break;
1531     case Instruction::Mul: Out << '*'; break;
1532     case Instruction::Div: Out << '/'; break;
1533     case Instruction::Rem: Out << '%'; break;
1534     case Instruction::And: Out << " & "; break;
1535     case Instruction::Or: Out << " | "; break;
1536     case Instruction::Xor: Out << " ^ "; break;
1537     case Instruction::SetEQ: Out << " == "; break;
1538     case Instruction::SetNE: Out << " != "; break;
1539     case Instruction::SetLE: Out << " <= "; break;
1540     case Instruction::SetGE: Out << " >= "; break;
1541     case Instruction::SetLT: Out << " < "; break;
1542     case Instruction::SetGT: Out << " > "; break;
1543     case Instruction::Shl : Out << " << "; break;
1544     case Instruction::Shr : Out << " >> "; break;
1545     default: std::cerr << "Invalid operator type!" << I; abort();
1546     }
1547
1548     writeOperand(I.getOperand(1));
1549   }
1550
1551   if (needsCast) {
1552     Out << "))";
1553   }
1554 }
1555
1556 void CWriter::visitCastInst(CastInst &I) {
1557   if (I.getType() == Type::BoolTy) {
1558     Out << '(';
1559     writeOperand(I.getOperand(0));
1560     Out << " != 0)";
1561     return;
1562   }
1563   Out << '(';
1564   printType(Out, I.getType());
1565   Out << ')';
1566   if (isa<PointerType>(I.getType())&&I.getOperand(0)->getType()->isIntegral() ||
1567       isa<PointerType>(I.getOperand(0)->getType())&&I.getType()->isIntegral()) {
1568     // Avoid "cast to pointer from integer of different size" warnings
1569     Out << "(long)";
1570   }
1571
1572   writeOperand(I.getOperand(0));
1573 }
1574
1575 void CWriter::visitSelectInst(SelectInst &I) {
1576   Out << "((";
1577   writeOperand(I.getCondition());
1578   Out << ") ? (";
1579   writeOperand(I.getTrueValue());
1580   Out << ") : (";
1581   writeOperand(I.getFalseValue());
1582   Out << "))";
1583 }
1584
1585
1586 void CWriter::lowerIntrinsics(Function &F) {
1587   for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
1588     for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; )
1589       if (CallInst *CI = dyn_cast<CallInst>(I++))
1590         if (Function *F = CI->getCalledFunction())
1591           switch (F->getIntrinsicID()) {
1592           case Intrinsic::not_intrinsic:
1593           case Intrinsic::vastart:
1594           case Intrinsic::vacopy:
1595           case Intrinsic::vaend:
1596           case Intrinsic::returnaddress:
1597           case Intrinsic::frameaddress:
1598           case Intrinsic::setjmp:
1599           case Intrinsic::longjmp:
1600           case Intrinsic::prefetch:
1601             // We directly implement these intrinsics
1602             break;
1603           default:
1604             // All other intrinsic calls we must lower.
1605             Instruction *Before = 0;
1606             if (CI != &BB->front())
1607               Before = prior(BasicBlock::iterator(CI));
1608
1609             IL.LowerIntrinsicCall(CI);
1610             if (Before) {        // Move iterator to instruction after call
1611               I = Before; ++I;
1612             } else {
1613               I = BB->begin();
1614             }
1615           }
1616 }
1617
1618
1619
1620 void CWriter::visitCallInst(CallInst &I) {
1621   // Handle intrinsic function calls first...
1622   if (Function *F = I.getCalledFunction())
1623     if (Intrinsic::ID ID = (Intrinsic::ID)F->getIntrinsicID()) {
1624       switch (ID) {
1625       default: assert(0 && "Unknown LLVM intrinsic!");
1626       case Intrinsic::vastart:
1627         Out << "0; ";
1628
1629         Out << "va_start(*(va_list*)";
1630         writeOperand(I.getOperand(1));
1631         Out << ", ";
1632         // Output the last argument to the enclosing function...
1633         if (I.getParent()->getParent()->arg_empty()) {
1634           std::cerr << "The C backend does not currently support zero "
1635                     << "argument varargs functions, such as '"
1636                     << I.getParent()->getParent()->getName() << "'!\n";
1637           abort();
1638         }
1639         writeOperand(--I.getParent()->getParent()->arg_end());
1640         Out << ')';
1641         return;
1642       case Intrinsic::vaend:
1643         if (!isa<ConstantPointerNull>(I.getOperand(1))) {
1644           Out << "0; va_end(*(va_list*)";
1645           writeOperand(I.getOperand(1));
1646           Out << ')';
1647         } else {
1648           Out << "va_end(*(va_list*)0)";
1649         }
1650         return;
1651       case Intrinsic::vacopy:
1652         Out << "0; ";
1653         Out << "va_copy(*(va_list*)";
1654         writeOperand(I.getOperand(1));
1655         Out << ", *(va_list*)";
1656         writeOperand(I.getOperand(2));
1657         Out << ')';
1658         return;
1659       case Intrinsic::returnaddress:
1660         Out << "__builtin_return_address(";
1661         writeOperand(I.getOperand(1));
1662         Out << ')';
1663         return;
1664       case Intrinsic::frameaddress:
1665         Out << "__builtin_frame_address(";
1666         writeOperand(I.getOperand(1));
1667         Out << ')';
1668         return;
1669       case Intrinsic::setjmp:
1670         Out << "setjmp(*(jmp_buf*)";
1671         writeOperand(I.getOperand(1));
1672         Out << ')';
1673         return;
1674       case Intrinsic::longjmp:
1675         Out << "longjmp(*(jmp_buf*)";
1676         writeOperand(I.getOperand(1));
1677         Out << ", ";
1678         writeOperand(I.getOperand(2));
1679         Out << ')';
1680         return;
1681       case Intrinsic::prefetch:
1682         Out << "LLVM_PREFETCH((const void *)";
1683         writeOperand(I.getOperand(1));
1684         Out << ", ";
1685         writeOperand(I.getOperand(2));
1686         Out << ", ";
1687         writeOperand(I.getOperand(3));
1688         Out << ")";
1689         return;
1690       }
1691     }
1692
1693   Value *Callee = I.getCalledValue();
1694
1695   // GCC is really a PITA.  It does not permit codegening casts of functions to
1696   // function pointers if they are in a call (it generates a trap instruction
1697   // instead!).  We work around this by inserting a cast to void* in between the
1698   // function and the function pointer cast.  Unfortunately, we can't just form
1699   // the constant expression here, because the folder will immediately nuke it.
1700   //
1701   // Note finally, that this is completely unsafe.  ANSI C does not guarantee
1702   // that void* and function pointers have the same size. :( To deal with this
1703   // in the common case, we handle casts where the number of arguments passed
1704   // match exactly.
1705   //
1706   bool WroteCallee = false;
1707   if (I.isTailCall()) Out << " /*tail*/ ";
1708   if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Callee))
1709     if (CE->getOpcode() == Instruction::Cast)
1710       if (Function *RF = dyn_cast<Function>(CE->getOperand(0))) {
1711         const FunctionType *RFTy = RF->getFunctionType();
1712         if (RFTy->getNumParams() == I.getNumOperands()-1) {
1713           // If the call site expects a value, and the actual callee doesn't
1714           // provide one, return 0.
1715           if (I.getType() != Type::VoidTy &&
1716               RFTy->getReturnType() == Type::VoidTy)
1717             Out << "0 /*actual callee doesn't return value*/; ";
1718           Callee = RF;
1719         } else {
1720           // Ok, just cast the pointer type.
1721           Out << "((";
1722           printType(Out, CE->getType());
1723           Out << ")(void*)";
1724           printConstant(RF);
1725           Out << ')';
1726           WroteCallee = true;
1727         }
1728       }
1729
1730   const PointerType  *PTy   = cast<PointerType>(Callee->getType());
1731   const FunctionType *FTy   = cast<FunctionType>(PTy->getElementType());
1732   const Type         *RetTy = FTy->getReturnType();
1733
1734   if (!WroteCallee) writeOperand(Callee);
1735   Out << '(';
1736
1737   unsigned NumDeclaredParams = FTy->getNumParams();
1738
1739   if (I.getNumOperands() != 1) {
1740     CallSite::arg_iterator AI = I.op_begin()+1, AE = I.op_end();
1741     if (NumDeclaredParams && (*AI)->getType() != FTy->getParamType(0)) {
1742       Out << '(';
1743       printType(Out, FTy->getParamType(0));
1744       Out << ')';
1745     }
1746
1747     writeOperand(*AI);
1748
1749     unsigned ArgNo;
1750     for (ArgNo = 1, ++AI; AI != AE; ++AI, ++ArgNo) {
1751       Out << ", ";
1752       if (ArgNo < NumDeclaredParams &&
1753           (*AI)->getType() != FTy->getParamType(ArgNo)) {
1754         Out << '(';
1755         printType(Out, FTy->getParamType(ArgNo));
1756         Out << ')';
1757       }
1758       writeOperand(*AI);
1759     }
1760   }
1761   Out << ')';
1762 }
1763
1764 void CWriter::visitMallocInst(MallocInst &I) {
1765   assert(0 && "lowerallocations pass didn't work!");
1766 }
1767
1768 void CWriter::visitAllocaInst(AllocaInst &I) {
1769   Out << '(';
1770   printType(Out, I.getType());
1771   Out << ") alloca(sizeof(";
1772   printType(Out, I.getType()->getElementType());
1773   Out << ')';
1774   if (I.isArrayAllocation()) {
1775     Out << " * " ;
1776     writeOperand(I.getOperand(0));
1777   }
1778   Out << ')';
1779 }
1780
1781 void CWriter::visitFreeInst(FreeInst &I) {
1782   assert(0 && "lowerallocations pass didn't work!");
1783 }
1784
1785 void CWriter::printIndexingExpression(Value *Ptr, gep_type_iterator I,
1786                                       gep_type_iterator E) {
1787   bool HasImplicitAddress = false;
1788   // If accessing a global value with no indexing, avoid *(&GV) syndrome
1789   if (GlobalValue *V = dyn_cast<GlobalValue>(Ptr)) {
1790     HasImplicitAddress = true;
1791   } else if (isDirectAlloca(Ptr)) {
1792     HasImplicitAddress = true;
1793   }
1794
1795   if (I == E) {
1796     if (!HasImplicitAddress)
1797       Out << '*';  // Implicit zero first argument: '*x' is equivalent to 'x[0]'
1798
1799     writeOperandInternal(Ptr);
1800     return;
1801   }
1802
1803   const Constant *CI = dyn_cast<Constant>(I.getOperand());
1804   if (HasImplicitAddress && (!CI || !CI->isNullValue()))
1805     Out << "(&";
1806
1807   writeOperandInternal(Ptr);
1808
1809   if (HasImplicitAddress && (!CI || !CI->isNullValue())) {
1810     Out << ')';
1811     HasImplicitAddress = false;  // HIA is only true if we haven't addressed yet
1812   }
1813
1814   assert(!HasImplicitAddress || (CI && CI->isNullValue()) &&
1815          "Can only have implicit address with direct accessing");
1816
1817   if (HasImplicitAddress) {
1818     ++I;
1819   } else if (CI && CI->isNullValue()) {
1820     gep_type_iterator TmpI = I; ++TmpI;
1821
1822     // Print out the -> operator if possible...
1823     if (TmpI != E && isa<StructType>(*TmpI)) {
1824       Out << (HasImplicitAddress ? "." : "->");
1825       Out << "field" << cast<ConstantUInt>(TmpI.getOperand())->getValue();
1826       I = ++TmpI;
1827     }
1828   }
1829
1830   for (; I != E; ++I)
1831     if (isa<StructType>(*I)) {
1832       Out << ".field" << cast<ConstantUInt>(I.getOperand())->getValue();
1833     } else {
1834       Out << '[';
1835       writeOperand(I.getOperand());
1836       Out << ']';
1837     }
1838 }
1839
1840 void CWriter::visitLoadInst(LoadInst &I) {
1841   Out << '*';
1842   if (I.isVolatile()) {
1843     Out << "((";
1844     printType(Out, I.getType(), "volatile*");
1845     Out << ")";
1846   }
1847
1848   writeOperand(I.getOperand(0));
1849
1850   if (I.isVolatile())
1851     Out << ')';
1852 }
1853
1854 void CWriter::visitStoreInst(StoreInst &I) {
1855   Out << '*';
1856   if (I.isVolatile()) {
1857     Out << "((";
1858     printType(Out, I.getOperand(0)->getType(), " volatile*");
1859     Out << ")";
1860   }
1861   writeOperand(I.getPointerOperand());
1862   if (I.isVolatile()) Out << ')';
1863   Out << " = ";
1864   writeOperand(I.getOperand(0));
1865 }
1866
1867 void CWriter::visitGetElementPtrInst(GetElementPtrInst &I) {
1868   Out << '&';
1869   printIndexingExpression(I.getPointerOperand(), gep_type_begin(I),
1870                           gep_type_end(I));
1871 }
1872
1873 void CWriter::visitVAArgInst(VAArgInst &I) {
1874   Out << "va_arg(*(va_list*)";
1875   writeOperand(I.getOperand(0));
1876   Out << ", ";
1877   printType(Out, I.getType());
1878   Out << ");\n ";
1879 }
1880
1881 //===----------------------------------------------------------------------===//
1882 //                       External Interface declaration
1883 //===----------------------------------------------------------------------===//
1884
1885 bool CTargetMachine::addPassesToEmitFile(PassManager &PM, std::ostream &o,
1886                                          CodeGenFileType FileType, bool Fast) {
1887   if (FileType != TargetMachine::AssemblyFile) return true;
1888
1889   PM.add(createLowerGCPass());
1890   PM.add(createLowerAllocationsPass(true));
1891   PM.add(createLowerInvokePass());
1892   PM.add(createCFGSimplificationPass());   // clean up after lower invoke.
1893   PM.add(new CBackendNameAllUsedStructsAndMergeFunctions());
1894   PM.add(new CWriter(o, getIntrinsicLowering()));
1895   return false;
1896 }