What should be the last unnecessary <iostream>s in the library.
[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/CallingConv.h"
17 #include "llvm/Constants.h"
18 #include "llvm/DerivedTypes.h"
19 #include "llvm/Module.h"
20 #include "llvm/Instructions.h"
21 #include "llvm/Pass.h"
22 #include "llvm/PassManager.h"
23 #include "llvm/SymbolTable.h"
24 #include "llvm/Intrinsics.h"
25 #include "llvm/IntrinsicInst.h"
26 #include "llvm/InlineAsm.h"
27 #include "llvm/Analysis/ConstantsScanner.h"
28 #include "llvm/Analysis/FindUsedTypes.h"
29 #include "llvm/Analysis/LoopInfo.h"
30 #include "llvm/CodeGen/IntrinsicLowering.h"
31 #include "llvm/Transforms/Scalar.h"
32 #include "llvm/Target/TargetMachineRegistry.h"
33 #include "llvm/Target/TargetAsmInfo.h"
34 #include "llvm/Support/CallSite.h"
35 #include "llvm/Support/CFG.h"
36 #include "llvm/Support/GetElementPtrTypeIterator.h"
37 #include "llvm/Support/InstVisitor.h"
38 #include "llvm/Support/Mangler.h"
39 #include "llvm/Support/MathExtras.h"
40 #include "llvm/ADT/StringExtras.h"
41 #include "llvm/ADT/STLExtras.h"
42 #include "llvm/Support/MathExtras.h"
43 #include "llvm/Config/config.h"
44 #include <algorithm>
45 #include <ios>
46 using namespace llvm;
47
48 namespace {
49   // Register the target.
50   RegisterTarget<CTargetMachine> X("c", "  C backend");
51
52   /// CBackendNameAllUsedStructsAndMergeFunctions - This pass inserts names for
53   /// any unnamed structure types that are used by the program, and merges
54   /// external functions with the same name.
55   ///
56   class CBackendNameAllUsedStructsAndMergeFunctions : public ModulePass {
57     void getAnalysisUsage(AnalysisUsage &AU) const {
58       AU.addRequired<FindUsedTypes>();
59     }
60
61     virtual const char *getPassName() const {
62       return "C backend type canonicalizer";
63     }
64
65     virtual bool runOnModule(Module &M);
66   };
67
68   /// CWriter - This class is the main chunk of code that converts an LLVM
69   /// module to a C translation unit.
70   class CWriter : public FunctionPass, public InstVisitor<CWriter> {
71     std::ostream &Out;
72     IntrinsicLowering IL;
73     Mangler *Mang;
74     LoopInfo *LI;
75     const Module *TheModule;
76     const TargetAsmInfo* TAsm;
77     std::map<const Type *, std::string> TypeNames;
78
79     std::map<const ConstantFP *, unsigned> FPConstantMap;
80   public:
81     CWriter(std::ostream &o) : Out(o), TAsm(0) {}
82
83     virtual const char *getPassName() const { return "C backend"; }
84
85     void getAnalysisUsage(AnalysisUsage &AU) const {
86       AU.addRequired<LoopInfo>();
87       AU.setPreservesAll();
88     }
89
90     virtual bool doInitialization(Module &M);
91
92     bool runOnFunction(Function &F) {
93       LI = &getAnalysis<LoopInfo>();
94
95       // Get rid of intrinsics we can't handle.
96       lowerIntrinsics(F);
97
98       // Output all floating point constants that cannot be printed accurately.
99       printFloatingPointConstants(F);
100
101       // Ensure that no local symbols conflict with global symbols.
102       F.renameLocalSymbols();
103
104       printFunction(F);
105       FPConstantMap.clear();
106       return false;
107     }
108
109     virtual bool doFinalization(Module &M) {
110       // Free memory...
111       delete Mang;
112       TypeNames.clear();
113       return false;
114     }
115
116     std::ostream &printType(std::ostream &Out, const Type *Ty,
117                             const std::string &VariableName = "",
118                             bool IgnoreName = false);
119
120     void printStructReturnPointerFunctionType(std::ostream &Out,
121                                               const PointerType *Ty);
122     
123     void writeOperand(Value *Operand);
124     void writeOperandRaw(Value *Operand);
125     void writeOperandInternal(Value *Operand);
126     void writeOperandWithCast(Value* Operand, unsigned Opcode);
127     bool writeInstructionCast(const Instruction &I);
128
129   private :
130     std::string InterpretASMConstraint(InlineAsm::ConstraintInfo& c);
131
132     void lowerIntrinsics(Function &F);
133
134     void printModule(Module *M);
135     void printModuleTypes(const SymbolTable &ST);
136     void printContainedStructs(const Type *Ty, std::set<const StructType *> &);
137     void printFloatingPointConstants(Function &F);
138     void printFunctionSignature(const Function *F, bool Prototype);
139
140     void printFunction(Function &);
141     void printBasicBlock(BasicBlock *BB);
142     void printLoop(Loop *L);
143
144     void printCast(unsigned opcode, const Type *SrcTy, const Type *DstTy);
145     void printConstant(Constant *CPV);
146     void printConstantWithCast(Constant *CPV, unsigned Opcode);
147     bool printConstExprCast(const ConstantExpr *CE);
148     void printConstantArray(ConstantArray *CPA);
149     void printConstantPacked(ConstantPacked *CP);
150
151     // isInlinableInst - Attempt to inline instructions into their uses to build
152     // trees as much as possible.  To do this, we have to consistently decide
153     // what is acceptable to inline, so that variable declarations don't get
154     // printed and an extra copy of the expr is not emitted.
155     //
156     static bool isInlinableInst(const Instruction &I) {
157       // Always inline setcc instructions, even if they are shared by multiple
158       // expressions.  GCC generates horrible code if we don't.
159       if (isa<SetCondInst>(I)) return true;
160
161       // Must be an expression, must be used exactly once.  If it is dead, we
162       // emit it inline where it would go.
163       if (I.getType() == Type::VoidTy || !I.hasOneUse() ||
164           isa<TerminatorInst>(I) || isa<CallInst>(I) || isa<PHINode>(I) ||
165           isa<LoadInst>(I) || isa<VAArgInst>(I))
166         // Don't inline a load across a store or other bad things!
167         return false;
168
169       // Must not be used in inline asm
170       if (I.hasOneUse() && isInlineAsm(*I.use_back())) return false;
171
172       // Only inline instruction it it's use is in the same BB as the inst.
173       return I.getParent() == cast<Instruction>(I.use_back())->getParent();
174     }
175
176     // isDirectAlloca - Define fixed sized allocas in the entry block as direct
177     // variables which are accessed with the & operator.  This causes GCC to
178     // generate significantly better code than to emit alloca calls directly.
179     //
180     static const AllocaInst *isDirectAlloca(const Value *V) {
181       const AllocaInst *AI = dyn_cast<AllocaInst>(V);
182       if (!AI) return false;
183       if (AI->isArrayAllocation())
184         return 0;   // FIXME: we can also inline fixed size array allocas!
185       if (AI->getParent() != &AI->getParent()->getParent()->getEntryBlock())
186         return 0;
187       return AI;
188     }
189     
190     // isInlineAsm - Check if the instruction is a call to an inline asm chunk
191     static bool isInlineAsm(const Instruction& I) {
192       if (isa<CallInst>(&I) && isa<InlineAsm>(I.getOperand(0)))
193         return true;
194       return false;
195     }
196     
197     // Instruction visitation functions
198     friend class InstVisitor<CWriter>;
199
200     void visitReturnInst(ReturnInst &I);
201     void visitBranchInst(BranchInst &I);
202     void visitSwitchInst(SwitchInst &I);
203     void visitInvokeInst(InvokeInst &I) {
204       assert(0 && "Lowerinvoke pass didn't work!");
205     }
206
207     void visitUnwindInst(UnwindInst &I) {
208       assert(0 && "Lowerinvoke pass didn't work!");
209     }
210     void visitUnreachableInst(UnreachableInst &I);
211
212     void visitPHINode(PHINode &I);
213     void visitBinaryOperator(Instruction &I);
214
215     void visitCastInst (CastInst &I);
216     void visitSelectInst(SelectInst &I);
217     void visitCallInst (CallInst &I);
218     void visitInlineAsm(CallInst &I);
219     void visitShiftInst(ShiftInst &I) { visitBinaryOperator(I); }
220
221     void visitMallocInst(MallocInst &I);
222     void visitAllocaInst(AllocaInst &I);
223     void visitFreeInst  (FreeInst   &I);
224     void visitLoadInst  (LoadInst   &I);
225     void visitStoreInst (StoreInst  &I);
226     void visitGetElementPtrInst(GetElementPtrInst &I);
227     void visitVAArgInst (VAArgInst &I);
228
229     void visitInstruction(Instruction &I) {
230       cerr << "C Writer does not know about " << I;
231       abort();
232     }
233
234     void outputLValue(Instruction *I) {
235       Out << "  " << Mang->getValueName(I) << " = ";
236     }
237
238     bool isGotoCodeNecessary(BasicBlock *From, BasicBlock *To);
239     void printPHICopiesForSuccessor(BasicBlock *CurBlock,
240                                     BasicBlock *Successor, unsigned Indent);
241     void printBranchToBlock(BasicBlock *CurBlock, BasicBlock *SuccBlock,
242                             unsigned Indent);
243     void printIndexingExpression(Value *Ptr, gep_type_iterator I,
244                                  gep_type_iterator E);
245   };
246 }
247
248 /// This method inserts names for any unnamed structure types that are used by
249 /// the program, and removes names from structure types that are not used by the
250 /// program.
251 ///
252 bool CBackendNameAllUsedStructsAndMergeFunctions::runOnModule(Module &M) {
253   // Get a set of types that are used by the program...
254   std::set<const Type *> UT = getAnalysis<FindUsedTypes>().getTypes();
255
256   // Loop over the module symbol table, removing types from UT that are
257   // already named, and removing names for types that are not used.
258   //
259   SymbolTable &MST = M.getSymbolTable();
260   for (SymbolTable::type_iterator TI = MST.type_begin(), TE = MST.type_end();
261        TI != TE; ) {
262     SymbolTable::type_iterator I = TI++;
263
264     // If this is not used, remove it from the symbol table.
265     std::set<const Type *>::iterator UTI = UT.find(I->second);
266     if (UTI == UT.end())
267       MST.remove(I);
268     else
269       UT.erase(UTI);    // Only keep one name for this type.
270   }
271
272   // UT now contains types that are not named.  Loop over it, naming
273   // structure types.
274   //
275   bool Changed = false;
276   unsigned RenameCounter = 0;
277   for (std::set<const Type *>::const_iterator I = UT.begin(), E = UT.end();
278        I != E; ++I)
279     if (const StructType *ST = dyn_cast<StructType>(*I)) {
280       while (M.addTypeName("unnamed"+utostr(RenameCounter), ST))
281         ++RenameCounter;
282       Changed = true;
283     }
284       
285       
286   // Loop over all external functions and globals.  If we have two with
287   // identical names, merge them.
288   // FIXME: This code should disappear when we don't allow values with the same
289   // names when they have different types!
290   std::map<std::string, GlobalValue*> ExtSymbols;
291   for (Module::iterator I = M.begin(), E = M.end(); I != E;) {
292     Function *GV = I++;
293     if (GV->isExternal() && GV->hasName()) {
294       std::pair<std::map<std::string, GlobalValue*>::iterator, bool> X
295         = ExtSymbols.insert(std::make_pair(GV->getName(), GV));
296       if (!X.second) {
297         // Found a conflict, replace this global with the previous one.
298         GlobalValue *OldGV = X.first->second;
299         GV->replaceAllUsesWith(ConstantExpr::getCast(OldGV, GV->getType()));
300         GV->eraseFromParent();
301         Changed = true;
302       }
303     }
304   }
305   // Do the same for globals.
306   for (Module::global_iterator I = M.global_begin(), E = M.global_end();
307        I != E;) {
308     GlobalVariable *GV = I++;
309     if (GV->isExternal() && GV->hasName()) {
310       std::pair<std::map<std::string, GlobalValue*>::iterator, bool> X
311         = ExtSymbols.insert(std::make_pair(GV->getName(), GV));
312       if (!X.second) {
313         // Found a conflict, replace this global with the previous one.
314         GlobalValue *OldGV = X.first->second;
315         GV->replaceAllUsesWith(ConstantExpr::getCast(OldGV, GV->getType()));
316         GV->eraseFromParent();
317         Changed = true;
318       }
319     }
320   }
321   
322   return Changed;
323 }
324
325 /// printStructReturnPointerFunctionType - This is like printType for a struct
326 /// return type, except, instead of printing the type as void (*)(Struct*, ...)
327 /// print it as "Struct (*)(...)", for struct return functions.
328 void CWriter::printStructReturnPointerFunctionType(std::ostream &Out,
329                                                    const PointerType *TheTy) {
330   const FunctionType *FTy = cast<FunctionType>(TheTy->getElementType());
331   std::stringstream FunctionInnards;
332   FunctionInnards << " (*) (";
333   bool PrintedType = false;
334
335   FunctionType::param_iterator I = FTy->param_begin(), E = FTy->param_end();
336   const Type *RetTy = cast<PointerType>(I->get())->getElementType();
337   for (++I; I != E; ++I) {
338     if (PrintedType)
339       FunctionInnards << ", ";
340     printType(FunctionInnards, *I, "");
341     PrintedType = true;
342   }
343   if (FTy->isVarArg()) {
344     if (PrintedType)
345       FunctionInnards << ", ...";
346   } else if (!PrintedType) {
347     FunctionInnards << "void";
348   }
349   FunctionInnards << ')';
350   std::string tstr = FunctionInnards.str();
351   printType(Out, RetTy, tstr);
352 }
353
354
355 // Pass the Type* and the variable name and this prints out the variable
356 // declaration.
357 //
358 std::ostream &CWriter::printType(std::ostream &Out, const Type *Ty,
359                                  const std::string &NameSoFar,
360                                  bool IgnoreName) {
361   if (Ty->isPrimitiveType())
362     switch (Ty->getTypeID()) {
363     case Type::VoidTyID:   return Out << "void "               << NameSoFar;
364     case Type::BoolTyID:   return Out << "bool "               << NameSoFar;
365     case Type::UByteTyID:  return Out << "unsigned char "      << NameSoFar;
366     case Type::SByteTyID:  return Out << "signed char "        << NameSoFar;
367     case Type::UShortTyID: return Out << "unsigned short "     << NameSoFar;
368     case Type::ShortTyID:  return Out << "short "              << NameSoFar;
369     case Type::UIntTyID:   return Out << "unsigned "           << NameSoFar;
370     case Type::IntTyID:    return Out << "int "                << NameSoFar;
371     case Type::ULongTyID:  return Out << "unsigned long long " << NameSoFar;
372     case Type::LongTyID:   return Out << "signed long long "   << NameSoFar;
373     case Type::FloatTyID:  return Out << "float "              << NameSoFar;
374     case Type::DoubleTyID: return Out << "double "             << NameSoFar;
375     default :
376       cerr << "Unknown primitive type: " << *Ty << "\n";
377       abort();
378     }
379
380   // Check to see if the type is named.
381   if (!IgnoreName || isa<OpaqueType>(Ty)) {
382     std::map<const Type *, std::string>::iterator I = TypeNames.find(Ty);
383     if (I != TypeNames.end()) return Out << I->second << ' ' << NameSoFar;
384   }
385
386   switch (Ty->getTypeID()) {
387   case Type::FunctionTyID: {
388     const FunctionType *FTy = cast<FunctionType>(Ty);
389     std::stringstream FunctionInnards;
390     FunctionInnards << " (" << NameSoFar << ") (";
391     for (FunctionType::param_iterator I = FTy->param_begin(),
392            E = FTy->param_end(); I != E; ++I) {
393       if (I != FTy->param_begin())
394         FunctionInnards << ", ";
395       printType(FunctionInnards, *I, "");
396     }
397     if (FTy->isVarArg()) {
398       if (FTy->getNumParams())
399         FunctionInnards << ", ...";
400     } else if (!FTy->getNumParams()) {
401       FunctionInnards << "void";
402     }
403     FunctionInnards << ')';
404     std::string tstr = FunctionInnards.str();
405     printType(Out, FTy->getReturnType(), tstr);
406     return Out;
407   }
408   case Type::StructTyID: {
409     const StructType *STy = cast<StructType>(Ty);
410     Out << NameSoFar + " {\n";
411     unsigned Idx = 0;
412     for (StructType::element_iterator I = STy->element_begin(),
413            E = STy->element_end(); I != E; ++I) {
414       Out << "  ";
415       printType(Out, *I, "field" + utostr(Idx++));
416       Out << ";\n";
417     }
418     return Out << '}';
419   }
420
421   case Type::PointerTyID: {
422     const PointerType *PTy = cast<PointerType>(Ty);
423     std::string ptrName = "*" + NameSoFar;
424
425     if (isa<ArrayType>(PTy->getElementType()) ||
426         isa<PackedType>(PTy->getElementType()))
427       ptrName = "(" + ptrName + ")";
428
429     return printType(Out, PTy->getElementType(), ptrName);
430   }
431
432   case Type::ArrayTyID: {
433     const ArrayType *ATy = cast<ArrayType>(Ty);
434     unsigned NumElements = ATy->getNumElements();
435     if (NumElements == 0) NumElements = 1;
436     return printType(Out, ATy->getElementType(),
437                      NameSoFar + "[" + utostr(NumElements) + "]");
438   }
439
440   case Type::PackedTyID: {
441     const PackedType *PTy = cast<PackedType>(Ty);
442     unsigned NumElements = PTy->getNumElements();
443     if (NumElements == 0) NumElements = 1;
444     return printType(Out, PTy->getElementType(),
445                      NameSoFar + "[" + utostr(NumElements) + "]");
446   }
447
448   case Type::OpaqueTyID: {
449     static int Count = 0;
450     std::string TyName = "struct opaque_" + itostr(Count++);
451     assert(TypeNames.find(Ty) == TypeNames.end());
452     TypeNames[Ty] = TyName;
453     return Out << TyName << ' ' << NameSoFar;
454   }
455   default:
456     assert(0 && "Unhandled case in getTypeProps!");
457     abort();
458   }
459
460   return Out;
461 }
462
463 void CWriter::printConstantArray(ConstantArray *CPA) {
464
465   // As a special case, print the array as a string if it is an array of
466   // ubytes or an array of sbytes with positive values.
467   //
468   const Type *ETy = CPA->getType()->getElementType();
469   bool isString = (ETy == Type::SByteTy || ETy == Type::UByteTy);
470
471   // Make sure the last character is a null char, as automatically added by C
472   if (isString && (CPA->getNumOperands() == 0 ||
473                    !cast<Constant>(*(CPA->op_end()-1))->isNullValue()))
474     isString = false;
475
476   if (isString) {
477     Out << '\"';
478     // Keep track of whether the last number was a hexadecimal escape
479     bool LastWasHex = false;
480
481     // Do not include the last character, which we know is null
482     for (unsigned i = 0, e = CPA->getNumOperands()-1; i != e; ++i) {
483       unsigned char C = cast<ConstantInt>(CPA->getOperand(i))->getZExtValue();
484
485       // Print it out literally if it is a printable character.  The only thing
486       // to be careful about is when the last letter output was a hex escape
487       // code, in which case we have to be careful not to print out hex digits
488       // explicitly (the C compiler thinks it is a continuation of the previous
489       // character, sheesh...)
490       //
491       if (isprint(C) && (!LastWasHex || !isxdigit(C))) {
492         LastWasHex = false;
493         if (C == '"' || C == '\\')
494           Out << "\\" << C;
495         else
496           Out << C;
497       } else {
498         LastWasHex = false;
499         switch (C) {
500         case '\n': Out << "\\n"; break;
501         case '\t': Out << "\\t"; break;
502         case '\r': Out << "\\r"; break;
503         case '\v': Out << "\\v"; break;
504         case '\a': Out << "\\a"; break;
505         case '\"': Out << "\\\""; break;
506         case '\'': Out << "\\\'"; break;
507         default:
508           Out << "\\x";
509           Out << (char)(( C/16  < 10) ? ( C/16 +'0') : ( C/16 -10+'A'));
510           Out << (char)(((C&15) < 10) ? ((C&15)+'0') : ((C&15)-10+'A'));
511           LastWasHex = true;
512           break;
513         }
514       }
515     }
516     Out << '\"';
517   } else {
518     Out << '{';
519     if (CPA->getNumOperands()) {
520       Out << ' ';
521       printConstant(cast<Constant>(CPA->getOperand(0)));
522       for (unsigned i = 1, e = CPA->getNumOperands(); i != e; ++i) {
523         Out << ", ";
524         printConstant(cast<Constant>(CPA->getOperand(i)));
525       }
526     }
527     Out << " }";
528   }
529 }
530
531 void CWriter::printConstantPacked(ConstantPacked *CP) {
532   Out << '{';
533   if (CP->getNumOperands()) {
534     Out << ' ';
535     printConstant(cast<Constant>(CP->getOperand(0)));
536     for (unsigned i = 1, e = CP->getNumOperands(); i != e; ++i) {
537       Out << ", ";
538       printConstant(cast<Constant>(CP->getOperand(i)));
539     }
540   }
541   Out << " }";
542 }
543
544 // isFPCSafeToPrint - Returns true if we may assume that CFP may be written out
545 // textually as a double (rather than as a reference to a stack-allocated
546 // variable). We decide this by converting CFP to a string and back into a
547 // double, and then checking whether the conversion results in a bit-equal
548 // double to the original value of CFP. This depends on us and the target C
549 // compiler agreeing on the conversion process (which is pretty likely since we
550 // only deal in IEEE FP).
551 //
552 static bool isFPCSafeToPrint(const ConstantFP *CFP) {
553 #if HAVE_PRINTF_A && ENABLE_CBE_PRINTF_A
554   char Buffer[100];
555   sprintf(Buffer, "%a", CFP->getValue());
556
557   if (!strncmp(Buffer, "0x", 2) ||
558       !strncmp(Buffer, "-0x", 3) ||
559       !strncmp(Buffer, "+0x", 3))
560     return atof(Buffer) == CFP->getValue();
561   return false;
562 #else
563   std::string StrVal = ftostr(CFP->getValue());
564
565   while (StrVal[0] == ' ')
566     StrVal.erase(StrVal.begin());
567
568   // Check to make sure that the stringized number is not some string like "Inf"
569   // or NaN.  Check that the string matches the "[-+]?[0-9]" regex.
570   if ((StrVal[0] >= '0' && StrVal[0] <= '9') ||
571       ((StrVal[0] == '-' || StrVal[0] == '+') &&
572        (StrVal[1] >= '0' && StrVal[1] <= '9')))
573     // Reparse stringized version!
574     return atof(StrVal.c_str()) == CFP->getValue();
575   return false;
576 #endif
577 }
578
579 /// Print out the casting for a cast operation. This does the double casting
580 /// necessary for conversion to the destination type, if necessary. 
581 /// @returns true if a closing paren is necessary
582 /// @brief Print a cast
583 void CWriter::printCast(unsigned opc, const Type *SrcTy, const Type *DstTy) {
584   Out << '(';
585   printType(Out, DstTy);
586   Out << ')';
587   switch (opc) {
588     case Instruction::UIToFP:
589     case Instruction::ZExt:
590       if (SrcTy->isSigned()) {
591         Out << '(';
592         printType(Out, SrcTy->getUnsignedVersion());
593         Out << ')';
594       }
595       break;
596     case Instruction::SIToFP:
597     case Instruction::SExt:
598       if (SrcTy->isUnsigned()) {
599         Out << '(';
600         printType(Out, SrcTy->getSignedVersion());
601         Out << ')';
602       }
603       break;
604     case Instruction::IntToPtr:
605     case Instruction::PtrToInt:
606         // Avoid "cast to pointer from integer of different size" warnings
607         Out << "(unsigned long)";
608         break;
609     case Instruction::Trunc:
610     case Instruction::BitCast:
611     case Instruction::FPExt:
612     case Instruction::FPTrunc:
613     case Instruction::FPToSI:
614     case Instruction::FPToUI:
615     default:
616       break;
617   }
618 }
619
620 // printConstant - The LLVM Constant to C Constant converter.
621 void CWriter::printConstant(Constant *CPV) {
622   if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(CPV)) {
623     switch (CE->getOpcode()) {
624     case Instruction::Trunc:
625     case Instruction::ZExt:
626     case Instruction::SExt:
627     case Instruction::FPTrunc:
628     case Instruction::FPExt:
629     case Instruction::UIToFP:
630     case Instruction::SIToFP:
631     case Instruction::FPToUI:
632     case Instruction::FPToSI:
633     case Instruction::PtrToInt:
634     case Instruction::IntToPtr:
635     case Instruction::BitCast:
636       Out << "(";
637       printCast(CE->getOpcode(), CE->getOperand(0)->getType(), CE->getType());
638       if (CE->getOpcode() == Instruction::SExt &&
639           CE->getOperand(0)->getType() == Type::BoolTy) {
640         // Make sure we really sext from bool here by subtracting from 0
641         Out << "0-";
642       }
643       printConstant(CE->getOperand(0));
644       if (CE->getType() == Type::BoolTy &&
645           (CE->getOpcode() == Instruction::Trunc ||
646            CE->getOpcode() == Instruction::FPToUI ||
647            CE->getOpcode() == Instruction::FPToSI ||
648            CE->getOpcode() == Instruction::PtrToInt)) {
649         // Make sure we really truncate to bool here by anding with 1
650         Out << "&1u";
651       }
652       Out << ')';
653       return;
654
655     case Instruction::GetElementPtr:
656       Out << "(&(";
657       printIndexingExpression(CE->getOperand(0), gep_type_begin(CPV),
658                               gep_type_end(CPV));
659       Out << "))";
660       return;
661     case Instruction::Select:
662       Out << '(';
663       printConstant(CE->getOperand(0));
664       Out << '?';
665       printConstant(CE->getOperand(1));
666       Out << ':';
667       printConstant(CE->getOperand(2));
668       Out << ')';
669       return;
670     case Instruction::Add:
671     case Instruction::Sub:
672     case Instruction::Mul:
673     case Instruction::SDiv:
674     case Instruction::UDiv:
675     case Instruction::FDiv:
676     case Instruction::URem:
677     case Instruction::SRem:
678     case Instruction::FRem:
679     case Instruction::And:
680     case Instruction::Or:
681     case Instruction::Xor:
682     case Instruction::SetEQ:
683     case Instruction::SetNE:
684     case Instruction::SetLT:
685     case Instruction::SetLE:
686     case Instruction::SetGT:
687     case Instruction::SetGE:
688     case Instruction::Shl:
689     case Instruction::LShr:
690     case Instruction::AShr:
691     {
692       Out << '(';
693       bool NeedsClosingParens = printConstExprCast(CE); 
694       printConstantWithCast(CE->getOperand(0), CE->getOpcode());
695       switch (CE->getOpcode()) {
696       case Instruction::Add: Out << " + "; break;
697       case Instruction::Sub: Out << " - "; break;
698       case Instruction::Mul: Out << " * "; break;
699       case Instruction::URem:
700       case Instruction::SRem: 
701       case Instruction::FRem: Out << " % "; break;
702       case Instruction::UDiv: 
703       case Instruction::SDiv: 
704       case Instruction::FDiv: Out << " / "; break;
705       case Instruction::And: Out << " & "; break;
706       case Instruction::Or:  Out << " | "; break;
707       case Instruction::Xor: Out << " ^ "; break;
708       case Instruction::SetEQ: Out << " == "; break;
709       case Instruction::SetNE: Out << " != "; break;
710       case Instruction::SetLT: Out << " < "; break;
711       case Instruction::SetLE: Out << " <= "; break;
712       case Instruction::SetGT: Out << " > "; break;
713       case Instruction::SetGE: Out << " >= "; break;
714       case Instruction::Shl: Out << " << "; break;
715       case Instruction::LShr:
716       case Instruction::AShr: Out << " >> "; break;
717       default: assert(0 && "Illegal opcode here!");
718       }
719       printConstantWithCast(CE->getOperand(1), CE->getOpcode());
720       if (NeedsClosingParens)
721         Out << "))";
722       Out << ')';
723       return;
724     }
725
726     default:
727       cerr << "CWriter Error: Unhandled constant expression: "
728            << *CE << "\n";
729       abort();
730     }
731   } else if (isa<UndefValue>(CPV) && CPV->getType()->isFirstClassType()) {
732     Out << "((";
733     printType(Out, CPV->getType());
734     Out << ")/*UNDEF*/0)";
735     return;
736   }
737
738   switch (CPV->getType()->getTypeID()) {
739   case Type::BoolTyID:
740     Out << (cast<ConstantBool>(CPV)->getValue() ? '1' : '0');
741     break;
742   case Type::SByteTyID:
743   case Type::ShortTyID:
744     Out << cast<ConstantInt>(CPV)->getSExtValue();
745     break;
746   case Type::IntTyID:
747     if ((int)cast<ConstantInt>(CPV)->getSExtValue() == (int)0x80000000)
748       Out << "((int)0x80000000U)";   // Handle MININT specially to avoid warning
749     else
750       Out << cast<ConstantInt>(CPV)->getSExtValue();
751     break;
752
753   case Type::LongTyID:
754     if (cast<ConstantInt>(CPV)->isMinValue(true))
755       Out << "(/*INT64_MIN*/(-9223372036854775807LL)-1)";
756     else
757       Out << cast<ConstantInt>(CPV)->getSExtValue() << "ll";
758     break;
759
760   case Type::UByteTyID:
761   case Type::UShortTyID:
762     Out << cast<ConstantInt>(CPV)->getZExtValue();
763     break;
764   case Type::UIntTyID:
765     Out << cast<ConstantInt>(CPV)->getZExtValue() << 'u';
766     break;
767   case Type::ULongTyID:
768     Out << cast<ConstantInt>(CPV)->getZExtValue() << "ull";
769     break;
770
771   case Type::FloatTyID:
772   case Type::DoubleTyID: {
773     ConstantFP *FPC = cast<ConstantFP>(CPV);
774     std::map<const ConstantFP*, unsigned>::iterator I = FPConstantMap.find(FPC);
775     if (I != FPConstantMap.end()) {
776       // Because of FP precision problems we must load from a stack allocated
777       // value that holds the value in hex.
778       Out << "(*(" << (FPC->getType() == Type::FloatTy ? "float" : "double")
779           << "*)&FPConstant" << I->second << ')';
780     } else {
781       if (IsNAN(FPC->getValue())) {
782         // The value is NaN
783
784         // The prefix for a quiet NaN is 0x7FF8. For a signalling NaN,
785         // it's 0x7ff4.
786         const unsigned long QuietNaN = 0x7ff8UL;
787         //const unsigned long SignalNaN = 0x7ff4UL;
788
789         // We need to grab the first part of the FP #
790         char Buffer[100];
791
792         uint64_t ll = DoubleToBits(FPC->getValue());
793         sprintf(Buffer, "0x%llx", static_cast<long long>(ll));
794
795         std::string Num(&Buffer[0], &Buffer[6]);
796         unsigned long Val = strtoul(Num.c_str(), 0, 16);
797
798         if (FPC->getType() == Type::FloatTy)
799           Out << "LLVM_NAN" << (Val == QuietNaN ? "" : "S") << "F(\""
800               << Buffer << "\") /*nan*/ ";
801         else
802           Out << "LLVM_NAN" << (Val == QuietNaN ? "" : "S") << "(\""
803               << Buffer << "\") /*nan*/ ";
804       } else if (IsInf(FPC->getValue())) {
805         // The value is Inf
806         if (FPC->getValue() < 0) Out << '-';
807         Out << "LLVM_INF" << (FPC->getType() == Type::FloatTy ? "F" : "")
808             << " /*inf*/ ";
809       } else {
810         std::string Num;
811 #if HAVE_PRINTF_A && ENABLE_CBE_PRINTF_A
812         // Print out the constant as a floating point number.
813         char Buffer[100];
814         sprintf(Buffer, "%a", FPC->getValue());
815         Num = Buffer;
816 #else
817         Num = ftostr(FPC->getValue());
818 #endif
819         Out << Num;
820       }
821     }
822     break;
823   }
824
825   case Type::ArrayTyID:
826     if (isa<ConstantAggregateZero>(CPV) || isa<UndefValue>(CPV)) {
827       const ArrayType *AT = cast<ArrayType>(CPV->getType());
828       Out << '{';
829       if (AT->getNumElements()) {
830         Out << ' ';
831         Constant *CZ = Constant::getNullValue(AT->getElementType());
832         printConstant(CZ);
833         for (unsigned i = 1, e = AT->getNumElements(); i != e; ++i) {
834           Out << ", ";
835           printConstant(CZ);
836         }
837       }
838       Out << " }";
839     } else {
840       printConstantArray(cast<ConstantArray>(CPV));
841     }
842     break;
843
844   case Type::PackedTyID:
845     if (isa<ConstantAggregateZero>(CPV) || isa<UndefValue>(CPV)) {
846       const PackedType *AT = cast<PackedType>(CPV->getType());
847       Out << '{';
848       if (AT->getNumElements()) {
849         Out << ' ';
850         Constant *CZ = Constant::getNullValue(AT->getElementType());
851         printConstant(CZ);
852         for (unsigned i = 1, e = AT->getNumElements(); i != e; ++i) {
853           Out << ", ";
854           printConstant(CZ);
855         }
856       }
857       Out << " }";
858     } else {
859       printConstantPacked(cast<ConstantPacked>(CPV));
860     }
861     break;
862
863   case Type::StructTyID:
864     if (isa<ConstantAggregateZero>(CPV) || isa<UndefValue>(CPV)) {
865       const StructType *ST = cast<StructType>(CPV->getType());
866       Out << '{';
867       if (ST->getNumElements()) {
868         Out << ' ';
869         printConstant(Constant::getNullValue(ST->getElementType(0)));
870         for (unsigned i = 1, e = ST->getNumElements(); i != e; ++i) {
871           Out << ", ";
872           printConstant(Constant::getNullValue(ST->getElementType(i)));
873         }
874       }
875       Out << " }";
876     } else {
877       Out << '{';
878       if (CPV->getNumOperands()) {
879         Out << ' ';
880         printConstant(cast<Constant>(CPV->getOperand(0)));
881         for (unsigned i = 1, e = CPV->getNumOperands(); i != e; ++i) {
882           Out << ", ";
883           printConstant(cast<Constant>(CPV->getOperand(i)));
884         }
885       }
886       Out << " }";
887     }
888     break;
889
890   case Type::PointerTyID:
891     if (isa<ConstantPointerNull>(CPV)) {
892       Out << "((";
893       printType(Out, CPV->getType());
894       Out << ")/*NULL*/0)";
895       break;
896     } else if (GlobalValue *GV = dyn_cast<GlobalValue>(CPV)) {
897       writeOperand(GV);
898       break;
899     }
900     // FALL THROUGH
901   default:
902     cerr << "Unknown constant type: " << *CPV << "\n";
903     abort();
904   }
905 }
906
907 // Some constant expressions need to be casted back to the original types
908 // because their operands were casted to the expected type. This function takes
909 // care of detecting that case and printing the cast for the ConstantExpr.
910 bool CWriter::printConstExprCast(const ConstantExpr* CE) {
911   bool NeedsExplicitCast = false;
912   const Type *Ty = CE->getOperand(0)->getType();
913   switch (CE->getOpcode()) {
914   case Instruction::LShr:
915   case Instruction::URem: 
916   case Instruction::UDiv: 
917     NeedsExplicitCast = Ty->isSigned(); break;
918   case Instruction::AShr:
919   case Instruction::SRem: 
920   case Instruction::SDiv: 
921     NeedsExplicitCast = Ty->isUnsigned(); break;
922   case Instruction::ZExt:
923   case Instruction::SExt:
924   case Instruction::Trunc:
925   case Instruction::FPTrunc:
926   case Instruction::FPExt:
927   case Instruction::UIToFP:
928   case Instruction::SIToFP:
929   case Instruction::FPToUI:
930   case Instruction::FPToSI:
931   case Instruction::PtrToInt:
932   case Instruction::IntToPtr:
933   case Instruction::BitCast:
934     Ty = CE->getType();
935     NeedsExplicitCast = true;
936     break;
937   default: break;
938   }
939   if (NeedsExplicitCast) {
940     Out << "((";
941     printType(Out, Ty);
942     Out << ")(";
943   }
944   return NeedsExplicitCast;
945 }
946
947 //  Print a constant assuming that it is the operand for a given Opcode. The
948 //  opcodes that care about sign need to cast their operands to the expected
949 //  type before the operation proceeds. This function does the casting.
950 void CWriter::printConstantWithCast(Constant* CPV, unsigned Opcode) {
951
952   // Extract the operand's type, we'll need it.
953   const Type* OpTy = CPV->getType();
954
955   // Indicate whether to do the cast or not.
956   bool shouldCast = false;
957
958   // Based on the Opcode for which this Constant is being written, determine
959   // the new type to which the operand should be casted by setting the value
960   // of OpTy. If we change OpTy, also set shouldCast to true so it gets
961   // casted below.
962   switch (Opcode) {
963     default:
964       // for most instructions, it doesn't matter
965       break; 
966     case Instruction::LShr:
967     case Instruction::UDiv:
968     case Instruction::URem:
969       // For UDiv/URem get correct type
970       if (OpTy->isSigned()) {
971         OpTy = OpTy->getUnsignedVersion();
972         shouldCast = true;
973       }
974       break;
975     case Instruction::AShr:
976     case Instruction::SDiv:
977     case Instruction::SRem:
978       // For SDiv/SRem get correct type
979       if (OpTy->isUnsigned()) {
980         OpTy = OpTy->getSignedVersion();
981         shouldCast = true;
982       }
983       break;
984   }
985
986   // Write out the casted constant if we should, otherwise just write the
987   // operand.
988   if (shouldCast) {
989     Out << "((";
990     printType(Out, OpTy);
991     Out << ")";
992     printConstant(CPV);
993     Out << ")";
994   } else 
995     writeOperand(CPV);
996
997 }
998
999 void CWriter::writeOperandInternal(Value *Operand) {
1000   if (Instruction *I = dyn_cast<Instruction>(Operand))
1001     if (isInlinableInst(*I) && !isDirectAlloca(I)) {
1002       // Should we inline this instruction to build a tree?
1003       Out << '(';
1004       visit(*I);
1005       Out << ')';
1006       return;
1007     }
1008
1009   Constant* CPV = dyn_cast<Constant>(Operand);
1010   if (CPV && !isa<GlobalValue>(CPV)) {
1011     printConstant(CPV);
1012   } else {
1013     Out << Mang->getValueName(Operand);
1014   }
1015 }
1016
1017 void CWriter::writeOperandRaw(Value *Operand) {
1018   Constant* CPV = dyn_cast<Constant>(Operand);
1019   if (CPV && !isa<GlobalValue>(CPV)) {
1020     printConstant(CPV);
1021   } else {
1022     Out << Mang->getValueName(Operand);
1023   }
1024 }
1025
1026 void CWriter::writeOperand(Value *Operand) {
1027   if (isa<GlobalVariable>(Operand) || isDirectAlloca(Operand))
1028     Out << "(&";  // Global variables are referenced as their addresses by llvm
1029
1030   writeOperandInternal(Operand);
1031
1032   if (isa<GlobalVariable>(Operand) || isDirectAlloca(Operand))
1033     Out << ')';
1034 }
1035
1036 // Some instructions need to have their result value casted back to the 
1037 // original types because their operands were casted to the expected type. 
1038 // This function takes care of detecting that case and printing the cast 
1039 // for the Instruction.
1040 bool CWriter::writeInstructionCast(const Instruction &I) {
1041   bool NeedsExplicitCast = false;
1042   const Type *Ty = I.getOperand(0)->getType();
1043   switch (I.getOpcode()) {
1044   case Instruction::LShr:
1045   case Instruction::URem: 
1046   case Instruction::UDiv: 
1047     NeedsExplicitCast = Ty->isSigned(); break;
1048   case Instruction::AShr:
1049   case Instruction::SRem: 
1050   case Instruction::SDiv: 
1051     NeedsExplicitCast = Ty->isUnsigned(); break;
1052   case Instruction::ZExt:
1053   case Instruction::SExt:
1054   case Instruction::Trunc:
1055   case Instruction::FPTrunc:
1056   case Instruction::FPExt:
1057   case Instruction::UIToFP:
1058   case Instruction::SIToFP:
1059   case Instruction::FPToUI:
1060   case Instruction::FPToSI:
1061   case Instruction::PtrToInt:
1062   case Instruction::IntToPtr:
1063   case Instruction::BitCast:
1064     Ty = I.getType();
1065     NeedsExplicitCast = true;
1066     break;
1067   default: break;
1068   }
1069   if (NeedsExplicitCast) {
1070     Out << "((";
1071     printType(Out, Ty);
1072     Out << ")(";
1073   }
1074   return NeedsExplicitCast;
1075 }
1076
1077 // Write the operand with a cast to another type based on the Opcode being used.
1078 // This will be used in cases where an instruction has specific type
1079 // requirements (usually signedness) for its operands. 
1080 void CWriter::writeOperandWithCast(Value* Operand, unsigned Opcode) {
1081
1082   // Extract the operand's type, we'll need it.
1083   const Type* OpTy = Operand->getType();
1084
1085   // Indicate whether to do the cast or not.
1086   bool shouldCast = false;
1087
1088   // Based on the Opcode for which this Operand is being written, determine
1089   // the new type to which the operand should be casted by setting the value
1090   // of OpTy. If we change OpTy, also set shouldCast to true.
1091   switch (Opcode) {
1092     default:
1093       // for most instructions, it doesn't matter
1094       break; 
1095     case Instruction::LShr:
1096     case Instruction::UDiv:
1097     case Instruction::URem:
1098       // For UDiv to have unsigned operands
1099       if (OpTy->isSigned()) {
1100         OpTy = OpTy->getUnsignedVersion();
1101         shouldCast = true;
1102       }
1103       break;
1104     case Instruction::AShr:
1105     case Instruction::SDiv:
1106     case Instruction::SRem:
1107       if (OpTy->isUnsigned()) {
1108         OpTy = OpTy->getSignedVersion();
1109         shouldCast = true;
1110       }
1111       break;
1112   }
1113
1114   // Write out the casted operand if we should, otherwise just write the
1115   // operand.
1116   if (shouldCast) {
1117     Out << "((";
1118     printType(Out, OpTy);
1119     Out << ")";
1120     writeOperand(Operand);
1121     Out << ")";
1122   } else 
1123     writeOperand(Operand);
1124
1125 }
1126
1127 // generateCompilerSpecificCode - This is where we add conditional compilation
1128 // directives to cater to specific compilers as need be.
1129 //
1130 static void generateCompilerSpecificCode(std::ostream& Out) {
1131   // Alloca is hard to get, and we don't want to include stdlib.h here.
1132   Out << "/* get a declaration for alloca */\n"
1133       << "#if defined(__CYGWIN__) || defined(__MINGW32__)\n"
1134       << "extern void *_alloca(unsigned long);\n"
1135       << "#define alloca(x) _alloca(x)\n"
1136       << "#elif defined(__APPLE__)\n"
1137       << "extern void *__builtin_alloca(unsigned long);\n"
1138       << "#define alloca(x) __builtin_alloca(x)\n"
1139       << "#elif defined(__sun__)\n"
1140       << "#if defined(__sparcv9)\n"
1141       << "extern void *__builtin_alloca(unsigned long);\n"
1142       << "#else\n"
1143       << "extern void *__builtin_alloca(unsigned int);\n"
1144       << "#endif\n"
1145       << "#define alloca(x) __builtin_alloca(x)\n"
1146       << "#elif defined(__FreeBSD__) || defined(__OpenBSD__)\n"
1147       << "#define alloca(x) __builtin_alloca(x)\n"
1148       << "#elif !defined(_MSC_VER)\n"
1149       << "#include <alloca.h>\n"
1150       << "#endif\n\n";
1151
1152   // We output GCC specific attributes to preserve 'linkonce'ness on globals.
1153   // If we aren't being compiled with GCC, just drop these attributes.
1154   Out << "#ifndef __GNUC__  /* Can only support \"linkonce\" vars with GCC */\n"
1155       << "#define __attribute__(X)\n"
1156       << "#endif\n\n";
1157
1158   // On Mac OS X, "external weak" is spelled "__attribute__((weak_import))".
1159   Out << "#if defined(__GNUC__) && defined(__APPLE_CC__)\n"
1160       << "#define __EXTERNAL_WEAK__ __attribute__((weak_import))\n"
1161       << "#elif defined(__GNUC__)\n"
1162       << "#define __EXTERNAL_WEAK__ __attribute__((weak))\n"
1163       << "#else\n"
1164       << "#define __EXTERNAL_WEAK__\n"
1165       << "#endif\n\n";
1166
1167   // For now, turn off the weak linkage attribute on Mac OS X. (See above.)
1168   Out << "#if defined(__GNUC__) && defined(__APPLE_CC__)\n"
1169       << "#define __ATTRIBUTE_WEAK__\n"
1170       << "#elif defined(__GNUC__)\n"
1171       << "#define __ATTRIBUTE_WEAK__ __attribute__((weak))\n"
1172       << "#else\n"
1173       << "#define __ATTRIBUTE_WEAK__\n"
1174       << "#endif\n\n";
1175
1176   // Define NaN and Inf as GCC builtins if using GCC, as 0 otherwise
1177   // From the GCC documentation:
1178   //
1179   //   double __builtin_nan (const char *str)
1180   //
1181   // This is an implementation of the ISO C99 function nan.
1182   //
1183   // Since ISO C99 defines this function in terms of strtod, which we do
1184   // not implement, a description of the parsing is in order. The string is
1185   // parsed as by strtol; that is, the base is recognized by leading 0 or
1186   // 0x prefixes. The number parsed is placed in the significand such that
1187   // the least significant bit of the number is at the least significant
1188   // bit of the significand. The number is truncated to fit the significand
1189   // field provided. The significand is forced to be a quiet NaN.
1190   //
1191   // This function, if given a string literal, is evaluated early enough
1192   // that it is considered a compile-time constant.
1193   //
1194   //   float __builtin_nanf (const char *str)
1195   //
1196   // Similar to __builtin_nan, except the return type is float.
1197   //
1198   //   double __builtin_inf (void)
1199   //
1200   // Similar to __builtin_huge_val, except a warning is generated if the
1201   // target floating-point format does not support infinities. This
1202   // function is suitable for implementing the ISO C99 macro INFINITY.
1203   //
1204   //   float __builtin_inff (void)
1205   //
1206   // Similar to __builtin_inf, except the return type is float.
1207   Out << "#ifdef __GNUC__\n"
1208       << "#define LLVM_NAN(NanStr)   __builtin_nan(NanStr)   /* Double */\n"
1209       << "#define LLVM_NANF(NanStr)  __builtin_nanf(NanStr)  /* Float */\n"
1210       << "#define LLVM_NANS(NanStr)  __builtin_nans(NanStr)  /* Double */\n"
1211       << "#define LLVM_NANSF(NanStr) __builtin_nansf(NanStr) /* Float */\n"
1212       << "#define LLVM_INF           __builtin_inf()         /* Double */\n"
1213       << "#define LLVM_INFF          __builtin_inff()        /* Float */\n"
1214       << "#define LLVM_PREFETCH(addr,rw,locality) "
1215                               "__builtin_prefetch(addr,rw,locality)\n"
1216       << "#define __ATTRIBUTE_CTOR__ __attribute__((constructor))\n"
1217       << "#define __ATTRIBUTE_DTOR__ __attribute__((destructor))\n"
1218       << "#define LLVM_ASM           __asm__\n"
1219       << "#else\n"
1220       << "#define LLVM_NAN(NanStr)   ((double)0.0)           /* Double */\n"
1221       << "#define LLVM_NANF(NanStr)  0.0F                    /* Float */\n"
1222       << "#define LLVM_NANS(NanStr)  ((double)0.0)           /* Double */\n"
1223       << "#define LLVM_NANSF(NanStr) 0.0F                    /* Float */\n"
1224       << "#define LLVM_INF           ((double)0.0)           /* Double */\n"
1225       << "#define LLVM_INFF          0.0F                    /* Float */\n"
1226       << "#define LLVM_PREFETCH(addr,rw,locality)            /* PREFETCH */\n"
1227       << "#define __ATTRIBUTE_CTOR__\n"
1228       << "#define __ATTRIBUTE_DTOR__\n"
1229       << "#define LLVM_ASM(X)\n"
1230       << "#endif\n\n";
1231
1232   // Output target-specific code that should be inserted into main.
1233   Out << "#define CODE_FOR_MAIN() /* Any target-specific code for main()*/\n";
1234   // On X86, set the FP control word to 64-bits of precision instead of 80 bits.
1235   Out << "#if defined(__GNUC__) && !defined(__llvm__)\n"
1236       << "#if defined(i386) || defined(__i386__) || defined(__i386) || "
1237       << "defined(__x86_64__)\n"
1238       << "#undef CODE_FOR_MAIN\n"
1239       << "#define CODE_FOR_MAIN() \\\n"
1240       << "  {short F;__asm__ (\"fnstcw %0\" : \"=m\" (*&F)); \\\n"
1241       << "  F=(F&~0x300)|0x200;__asm__(\"fldcw %0\"::\"m\"(*&F));}\n"
1242       << "#endif\n#endif\n";
1243
1244 }
1245
1246 /// FindStaticTors - Given a static ctor/dtor list, unpack its contents into
1247 /// the StaticTors set.
1248 static void FindStaticTors(GlobalVariable *GV, std::set<Function*> &StaticTors){
1249   ConstantArray *InitList = dyn_cast<ConstantArray>(GV->getInitializer());
1250   if (!InitList) return;
1251   
1252   for (unsigned i = 0, e = InitList->getNumOperands(); i != e; ++i)
1253     if (ConstantStruct *CS = dyn_cast<ConstantStruct>(InitList->getOperand(i))){
1254       if (CS->getNumOperands() != 2) return;  // Not array of 2-element structs.
1255       
1256       if (CS->getOperand(1)->isNullValue())
1257         return;  // Found a null terminator, exit printing.
1258       Constant *FP = CS->getOperand(1);
1259       if (ConstantExpr *CE = dyn_cast<ConstantExpr>(FP))
1260         if (CE->isCast())
1261           FP = CE->getOperand(0);
1262       if (Function *F = dyn_cast<Function>(FP))
1263         StaticTors.insert(F);
1264     }
1265 }
1266
1267 enum SpecialGlobalClass {
1268   NotSpecial = 0,
1269   GlobalCtors, GlobalDtors,
1270   NotPrinted
1271 };
1272
1273 /// getGlobalVariableClass - If this is a global that is specially recognized
1274 /// by LLVM, return a code that indicates how we should handle it.
1275 static SpecialGlobalClass getGlobalVariableClass(const GlobalVariable *GV) {
1276   // If this is a global ctors/dtors list, handle it now.
1277   if (GV->hasAppendingLinkage() && GV->use_empty()) {
1278     if (GV->getName() == "llvm.global_ctors")
1279       return GlobalCtors;
1280     else if (GV->getName() == "llvm.global_dtors")
1281       return GlobalDtors;
1282   }
1283   
1284   // Otherwise, it it is other metadata, don't print it.  This catches things
1285   // like debug information.
1286   if (GV->getSection() == "llvm.metadata")
1287     return NotPrinted;
1288   
1289   return NotSpecial;
1290 }
1291
1292
1293 bool CWriter::doInitialization(Module &M) {
1294   // Initialize
1295   TheModule = &M;
1296
1297   IL.AddPrototypes(M);
1298
1299   // Ensure that all structure types have names...
1300   Mang = new Mangler(M);
1301   Mang->markCharUnacceptable('.');
1302
1303   // Keep track of which functions are static ctors/dtors so they can have
1304   // an attribute added to their prototypes.
1305   std::set<Function*> StaticCtors, StaticDtors;
1306   for (Module::global_iterator I = M.global_begin(), E = M.global_end();
1307        I != E; ++I) {
1308     switch (getGlobalVariableClass(I)) {
1309     default: break;
1310     case GlobalCtors:
1311       FindStaticTors(I, StaticCtors);
1312       break;
1313     case GlobalDtors:
1314       FindStaticTors(I, StaticDtors);
1315       break;
1316     }
1317   }
1318   
1319   // get declaration for alloca
1320   Out << "/* Provide Declarations */\n";
1321   Out << "#include <stdarg.h>\n";      // Varargs support
1322   Out << "#include <setjmp.h>\n";      // Unwind support
1323   generateCompilerSpecificCode(Out);
1324
1325   // Provide a definition for `bool' if not compiling with a C++ compiler.
1326   Out << "\n"
1327       << "#ifndef __cplusplus\ntypedef unsigned char bool;\n#endif\n"
1328
1329       << "\n\n/* Support for floating point constants */\n"
1330       << "typedef unsigned long long ConstantDoubleTy;\n"
1331       << "typedef unsigned int        ConstantFloatTy;\n"
1332
1333       << "\n\n/* Global Declarations */\n";
1334
1335   // First output all the declarations for the program, because C requires
1336   // Functions & globals to be declared before they are used.
1337   //
1338
1339   // Loop over the symbol table, emitting all named constants...
1340   printModuleTypes(M.getSymbolTable());
1341
1342   // Global variable declarations...
1343   if (!M.global_empty()) {
1344     Out << "\n/* External Global Variable Declarations */\n";
1345     for (Module::global_iterator I = M.global_begin(), E = M.global_end();
1346          I != E; ++I) {
1347       if (I->hasExternalLinkage()) {
1348         Out << "extern ";
1349         printType(Out, I->getType()->getElementType(), Mang->getValueName(I));
1350         Out << ";\n";
1351       } else if (I->hasDLLImportLinkage()) {
1352         Out << "__declspec(dllimport) ";
1353         printType(Out, I->getType()->getElementType(), Mang->getValueName(I));
1354         Out << ";\n";        
1355       } else if (I->hasExternalWeakLinkage()) {
1356         Out << "extern ";
1357         printType(Out, I->getType()->getElementType(), Mang->getValueName(I));
1358         Out << " __EXTERNAL_WEAK__ ;\n";
1359       }
1360     }
1361   }
1362
1363   // Function declarations
1364   Out << "\n/* Function Declarations */\n";
1365   Out << "double fmod(double, double);\n";   // Support for FP rem
1366   Out << "float fmodf(float, float);\n";
1367   
1368   for (Module::iterator I = M.begin(), E = M.end(); I != E; ++I) {
1369     // Don't print declarations for intrinsic functions.
1370     if (!I->getIntrinsicID() && I->getName() != "setjmp" && 
1371         I->getName() != "longjmp" && I->getName() != "_setjmp") {
1372       if (I->hasExternalWeakLinkage())
1373         Out << "extern ";
1374       printFunctionSignature(I, true);
1375       if (I->hasWeakLinkage() || I->hasLinkOnceLinkage()) 
1376         Out << " __ATTRIBUTE_WEAK__";
1377       if (I->hasExternalWeakLinkage())
1378         Out << " __EXTERNAL_WEAK__";
1379       if (StaticCtors.count(I))
1380         Out << " __ATTRIBUTE_CTOR__";
1381       if (StaticDtors.count(I))
1382         Out << " __ATTRIBUTE_DTOR__";
1383       
1384       if (I->hasName() && I->getName()[0] == 1)
1385         Out << " LLVM_ASM(\"" << I->getName().c_str()+1 << "\")";
1386           
1387       Out << ";\n";
1388     }
1389   }
1390
1391   // Output the global variable declarations
1392   if (!M.global_empty()) {
1393     Out << "\n\n/* Global Variable Declarations */\n";
1394     for (Module::global_iterator I = M.global_begin(), E = M.global_end();
1395          I != E; ++I)
1396       if (!I->isExternal()) {
1397         // Ignore special globals, such as debug info.
1398         if (getGlobalVariableClass(I))
1399           continue;
1400         
1401         if (I->hasInternalLinkage())
1402           Out << "static ";
1403         else
1404           Out << "extern ";
1405         printType(Out, I->getType()->getElementType(), Mang->getValueName(I));
1406
1407         if (I->hasLinkOnceLinkage())
1408           Out << " __attribute__((common))";
1409         else if (I->hasWeakLinkage())
1410           Out << " __ATTRIBUTE_WEAK__";
1411         else if (I->hasExternalWeakLinkage())
1412           Out << " __EXTERNAL_WEAK__";
1413         Out << ";\n";
1414       }
1415   }
1416
1417   // Output the global variable definitions and contents...
1418   if (!M.global_empty()) {
1419     Out << "\n\n/* Global Variable Definitions and Initialization */\n";
1420     for (Module::global_iterator I = M.global_begin(), E = M.global_end(); 
1421          I != E; ++I)
1422       if (!I->isExternal()) {
1423         // Ignore special globals, such as debug info.
1424         if (getGlobalVariableClass(I))
1425           continue;
1426         
1427         if (I->hasInternalLinkage())
1428           Out << "static ";
1429         else if (I->hasDLLImportLinkage())
1430           Out << "__declspec(dllimport) ";
1431         else if (I->hasDLLExportLinkage())
1432           Out << "__declspec(dllexport) ";
1433             
1434         printType(Out, I->getType()->getElementType(), Mang->getValueName(I));
1435         if (I->hasLinkOnceLinkage())
1436           Out << " __attribute__((common))";
1437         else if (I->hasWeakLinkage())
1438           Out << " __ATTRIBUTE_WEAK__";
1439
1440         // If the initializer is not null, emit the initializer.  If it is null,
1441         // we try to avoid emitting large amounts of zeros.  The problem with
1442         // this, however, occurs when the variable has weak linkage.  In this
1443         // case, the assembler will complain about the variable being both weak
1444         // and common, so we disable this optimization.
1445         if (!I->getInitializer()->isNullValue()) {
1446           Out << " = " ;
1447           writeOperand(I->getInitializer());
1448         } else if (I->hasWeakLinkage()) {
1449           // We have to specify an initializer, but it doesn't have to be
1450           // complete.  If the value is an aggregate, print out { 0 }, and let
1451           // the compiler figure out the rest of the zeros.
1452           Out << " = " ;
1453           if (isa<StructType>(I->getInitializer()->getType()) ||
1454               isa<ArrayType>(I->getInitializer()->getType()) ||
1455               isa<PackedType>(I->getInitializer()->getType())) {
1456             Out << "{ 0 }";
1457           } else {
1458             // Just print it out normally.
1459             writeOperand(I->getInitializer());
1460           }
1461         }
1462         Out << ";\n";
1463       }
1464   }
1465
1466   if (!M.empty())
1467     Out << "\n\n/* Function Bodies */\n";
1468   return false;
1469 }
1470
1471
1472 /// Output all floating point constants that cannot be printed accurately...
1473 void CWriter::printFloatingPointConstants(Function &F) {
1474   // Scan the module for floating point constants.  If any FP constant is used
1475   // in the function, we want to redirect it here so that we do not depend on
1476   // the precision of the printed form, unless the printed form preserves
1477   // precision.
1478   //
1479   static unsigned FPCounter = 0;
1480   for (constant_iterator I = constant_begin(&F), E = constant_end(&F);
1481        I != E; ++I)
1482     if (const ConstantFP *FPC = dyn_cast<ConstantFP>(*I))
1483       if (!isFPCSafeToPrint(FPC) && // Do not put in FPConstantMap if safe.
1484           !FPConstantMap.count(FPC)) {
1485         double Val = FPC->getValue();
1486
1487         FPConstantMap[FPC] = FPCounter;  // Number the FP constants
1488
1489         if (FPC->getType() == Type::DoubleTy) {
1490           Out << "static const ConstantDoubleTy FPConstant" << FPCounter++
1491               << " = 0x" << std::hex << DoubleToBits(Val) << std::dec
1492               << "ULL;    /* " << Val << " */\n";
1493         } else if (FPC->getType() == Type::FloatTy) {
1494           Out << "static const ConstantFloatTy FPConstant" << FPCounter++
1495               << " = 0x" << std::hex << FloatToBits(Val) << std::dec
1496               << "U;    /* " << Val << " */\n";
1497         } else
1498           assert(0 && "Unknown float type!");
1499       }
1500
1501   Out << '\n';
1502 }
1503
1504
1505 /// printSymbolTable - Run through symbol table looking for type names.  If a
1506 /// type name is found, emit its declaration...
1507 ///
1508 void CWriter::printModuleTypes(const SymbolTable &ST) {
1509   // We are only interested in the type plane of the symbol table.
1510   SymbolTable::type_const_iterator I   = ST.type_begin();
1511   SymbolTable::type_const_iterator End = ST.type_end();
1512
1513   // If there are no type names, exit early.
1514   if (I == End) return;
1515
1516   // Print out forward declarations for structure types before anything else!
1517   Out << "/* Structure forward decls */\n";
1518   for (; I != End; ++I)
1519     if (const Type *STy = dyn_cast<StructType>(I->second)) {
1520       std::string Name = "struct l_" + Mang->makeNameProper(I->first);
1521       Out << Name << ";\n";
1522       TypeNames.insert(std::make_pair(STy, Name));
1523     }
1524
1525   Out << '\n';
1526
1527   // Now we can print out typedefs...
1528   Out << "/* Typedefs */\n";
1529   for (I = ST.type_begin(); I != End; ++I) {
1530     const Type *Ty = cast<Type>(I->second);
1531     std::string Name = "l_" + Mang->makeNameProper(I->first);
1532     Out << "typedef ";
1533     printType(Out, Ty, Name);
1534     Out << ";\n";
1535   }
1536
1537   Out << '\n';
1538
1539   // Keep track of which structures have been printed so far...
1540   std::set<const StructType *> StructPrinted;
1541
1542   // Loop over all structures then push them into the stack so they are
1543   // printed in the correct order.
1544   //
1545   Out << "/* Structure contents */\n";
1546   for (I = ST.type_begin(); I != End; ++I)
1547     if (const StructType *STy = dyn_cast<StructType>(I->second))
1548       // Only print out used types!
1549       printContainedStructs(STy, StructPrinted);
1550 }
1551
1552 // Push the struct onto the stack and recursively push all structs
1553 // this one depends on.
1554 //
1555 // TODO:  Make this work properly with packed types
1556 //
1557 void CWriter::printContainedStructs(const Type *Ty,
1558                                     std::set<const StructType*> &StructPrinted){
1559   // Don't walk through pointers.
1560   if (isa<PointerType>(Ty) || Ty->isPrimitiveType()) return;
1561   
1562   // Print all contained types first.
1563   for (Type::subtype_iterator I = Ty->subtype_begin(),
1564        E = Ty->subtype_end(); I != E; ++I)
1565     printContainedStructs(*I, StructPrinted);
1566   
1567   if (const StructType *STy = dyn_cast<StructType>(Ty)) {
1568     // Check to see if we have already printed this struct.
1569     if (StructPrinted.insert(STy).second) {
1570       // Print structure type out.
1571       std::string Name = TypeNames[STy];
1572       printType(Out, STy, Name, true);
1573       Out << ";\n\n";
1574     }
1575   }
1576 }
1577
1578 void CWriter::printFunctionSignature(const Function *F, bool Prototype) {
1579   /// isCStructReturn - Should this function actually return a struct by-value?
1580   bool isCStructReturn = F->getCallingConv() == CallingConv::CSRet;
1581   
1582   if (F->hasInternalLinkage()) Out << "static ";
1583   if (F->hasDLLImportLinkage()) Out << "__declspec(dllimport) ";
1584   if (F->hasDLLExportLinkage()) Out << "__declspec(dllexport) ";  
1585   switch (F->getCallingConv()) {
1586    case CallingConv::X86_StdCall:
1587     Out << "__stdcall ";
1588     break;
1589    case CallingConv::X86_FastCall:
1590     Out << "__fastcall ";
1591     break;
1592   }
1593   
1594   // Loop over the arguments, printing them...
1595   const FunctionType *FT = cast<FunctionType>(F->getFunctionType());
1596
1597   std::stringstream FunctionInnards;
1598
1599   // Print out the name...
1600   FunctionInnards << Mang->getValueName(F) << '(';
1601
1602   bool PrintedArg = false;
1603   if (!F->isExternal()) {
1604     if (!F->arg_empty()) {
1605       Function::const_arg_iterator I = F->arg_begin(), E = F->arg_end();
1606       
1607       // If this is a struct-return function, don't print the hidden
1608       // struct-return argument.
1609       if (isCStructReturn) {
1610         assert(I != E && "Invalid struct return function!");
1611         ++I;
1612       }
1613       
1614       std::string ArgName;
1615       for (; I != E; ++I) {
1616         if (PrintedArg) FunctionInnards << ", ";
1617         if (I->hasName() || !Prototype)
1618           ArgName = Mang->getValueName(I);
1619         else
1620           ArgName = "";
1621         printType(FunctionInnards, I->getType(), ArgName);
1622         PrintedArg = true;
1623       }
1624     }
1625   } else {
1626     // Loop over the arguments, printing them.
1627     FunctionType::param_iterator I = FT->param_begin(), E = FT->param_end();
1628     
1629     // If this is a struct-return function, don't print the hidden
1630     // struct-return argument.
1631     if (isCStructReturn) {
1632       assert(I != E && "Invalid struct return function!");
1633       ++I;
1634     }
1635     
1636     for (; I != E; ++I) {
1637       if (PrintedArg) FunctionInnards << ", ";
1638       printType(FunctionInnards, *I);
1639       PrintedArg = true;
1640     }
1641   }
1642
1643   // Finish printing arguments... if this is a vararg function, print the ...,
1644   // unless there are no known types, in which case, we just emit ().
1645   //
1646   if (FT->isVarArg() && PrintedArg) {
1647     if (PrintedArg) FunctionInnards << ", ";
1648     FunctionInnards << "...";  // Output varargs portion of signature!
1649   } else if (!FT->isVarArg() && !PrintedArg) {
1650     FunctionInnards << "void"; // ret() -> ret(void) in C.
1651   }
1652   FunctionInnards << ')';
1653   
1654   // Get the return tpe for the function.
1655   const Type *RetTy;
1656   if (!isCStructReturn)
1657     RetTy = F->getReturnType();
1658   else {
1659     // If this is a struct-return function, print the struct-return type.
1660     RetTy = cast<PointerType>(FT->getParamType(0))->getElementType();
1661   }
1662     
1663   // Print out the return type and the signature built above.
1664   printType(Out, RetTy, FunctionInnards.str());
1665 }
1666
1667 void CWriter::printFunction(Function &F) {
1668   printFunctionSignature(&F, false);
1669   Out << " {\n";
1670   
1671   // If this is a struct return function, handle the result with magic.
1672   if (F.getCallingConv() == CallingConv::CSRet) {
1673     const Type *StructTy =
1674       cast<PointerType>(F.arg_begin()->getType())->getElementType();
1675     Out << "  ";
1676     printType(Out, StructTy, "StructReturn");
1677     Out << ";  /* Struct return temporary */\n";
1678
1679     Out << "  ";
1680     printType(Out, F.arg_begin()->getType(), Mang->getValueName(F.arg_begin()));
1681     Out << " = &StructReturn;\n";
1682   }
1683
1684   bool PrintedVar = false;
1685   
1686   // print local variable information for the function
1687   for (inst_iterator I = inst_begin(&F), E = inst_end(&F); I != E; ++I)
1688     if (const AllocaInst *AI = isDirectAlloca(&*I)) {
1689       Out << "  ";
1690       printType(Out, AI->getAllocatedType(), Mang->getValueName(AI));
1691       Out << ";    /* Address-exposed local */\n";
1692       PrintedVar = true;
1693     } else if (I->getType() != Type::VoidTy && !isInlinableInst(*I)) {
1694       Out << "  ";
1695       printType(Out, I->getType(), Mang->getValueName(&*I));
1696       Out << ";\n";
1697
1698       if (isa<PHINode>(*I)) {  // Print out PHI node temporaries as well...
1699         Out << "  ";
1700         printType(Out, I->getType(),
1701                   Mang->getValueName(&*I)+"__PHI_TEMPORARY");
1702         Out << ";\n";
1703       }
1704       PrintedVar = true;
1705     }
1706
1707   if (PrintedVar)
1708     Out << '\n';
1709
1710   if (F.hasExternalLinkage() && F.getName() == "main")
1711     Out << "  CODE_FOR_MAIN();\n";
1712
1713   // print the basic blocks
1714   for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB) {
1715     if (Loop *L = LI->getLoopFor(BB)) {
1716       if (L->getHeader() == BB && L->getParentLoop() == 0)
1717         printLoop(L);
1718     } else {
1719       printBasicBlock(BB);
1720     }
1721   }
1722
1723   Out << "}\n\n";
1724 }
1725
1726 void CWriter::printLoop(Loop *L) {
1727   Out << "  do {     /* Syntactic loop '" << L->getHeader()->getName()
1728       << "' to make GCC happy */\n";
1729   for (unsigned i = 0, e = L->getBlocks().size(); i != e; ++i) {
1730     BasicBlock *BB = L->getBlocks()[i];
1731     Loop *BBLoop = LI->getLoopFor(BB);
1732     if (BBLoop == L)
1733       printBasicBlock(BB);
1734     else if (BB == BBLoop->getHeader() && BBLoop->getParentLoop() == L)
1735       printLoop(BBLoop);
1736   }
1737   Out << "  } while (1); /* end of syntactic loop '"
1738       << L->getHeader()->getName() << "' */\n";
1739 }
1740
1741 void CWriter::printBasicBlock(BasicBlock *BB) {
1742
1743   // Don't print the label for the basic block if there are no uses, or if
1744   // the only terminator use is the predecessor basic block's terminator.
1745   // We have to scan the use list because PHI nodes use basic blocks too but
1746   // do not require a label to be generated.
1747   //
1748   bool NeedsLabel = false;
1749   for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI)
1750     if (isGotoCodeNecessary(*PI, BB)) {
1751       NeedsLabel = true;
1752       break;
1753     }
1754
1755   if (NeedsLabel) Out << Mang->getValueName(BB) << ":\n";
1756
1757   // Output all of the instructions in the basic block...
1758   for (BasicBlock::iterator II = BB->begin(), E = --BB->end(); II != E;
1759        ++II) {
1760     if (!isInlinableInst(*II) && !isDirectAlloca(II)) {
1761       if (II->getType() != Type::VoidTy && !isInlineAsm(*II))
1762         outputLValue(II);
1763       else
1764         Out << "  ";
1765       visit(*II);
1766       Out << ";\n";
1767     }
1768   }
1769
1770   // Don't emit prefix or suffix for the terminator...
1771   visit(*BB->getTerminator());
1772 }
1773
1774
1775 // Specific Instruction type classes... note that all of the casts are
1776 // necessary because we use the instruction classes as opaque types...
1777 //
1778 void CWriter::visitReturnInst(ReturnInst &I) {
1779   // If this is a struct return function, return the temporary struct.
1780   if (I.getParent()->getParent()->getCallingConv() == CallingConv::CSRet) {
1781     Out << "  return StructReturn;\n";
1782     return;
1783   }
1784   
1785   // Don't output a void return if this is the last basic block in the function
1786   if (I.getNumOperands() == 0 &&
1787       &*--I.getParent()->getParent()->end() == I.getParent() &&
1788       !I.getParent()->size() == 1) {
1789     return;
1790   }
1791
1792   Out << "  return";
1793   if (I.getNumOperands()) {
1794     Out << ' ';
1795     writeOperand(I.getOperand(0));
1796   }
1797   Out << ";\n";
1798 }
1799
1800 void CWriter::visitSwitchInst(SwitchInst &SI) {
1801
1802   Out << "  switch (";
1803   writeOperand(SI.getOperand(0));
1804   Out << ") {\n  default:\n";
1805   printPHICopiesForSuccessor (SI.getParent(), SI.getDefaultDest(), 2);
1806   printBranchToBlock(SI.getParent(), SI.getDefaultDest(), 2);
1807   Out << ";\n";
1808   for (unsigned i = 2, e = SI.getNumOperands(); i != e; i += 2) {
1809     Out << "  case ";
1810     writeOperand(SI.getOperand(i));
1811     Out << ":\n";
1812     BasicBlock *Succ = cast<BasicBlock>(SI.getOperand(i+1));
1813     printPHICopiesForSuccessor (SI.getParent(), Succ, 2);
1814     printBranchToBlock(SI.getParent(), Succ, 2);
1815     if (Function::iterator(Succ) == next(Function::iterator(SI.getParent())))
1816       Out << "    break;\n";
1817   }
1818   Out << "  }\n";
1819 }
1820
1821 void CWriter::visitUnreachableInst(UnreachableInst &I) {
1822   Out << "  /*UNREACHABLE*/;\n";
1823 }
1824
1825 bool CWriter::isGotoCodeNecessary(BasicBlock *From, BasicBlock *To) {
1826   /// FIXME: This should be reenabled, but loop reordering safe!!
1827   return true;
1828
1829   if (next(Function::iterator(From)) != Function::iterator(To))
1830     return true;  // Not the direct successor, we need a goto.
1831
1832   //isa<SwitchInst>(From->getTerminator())
1833
1834   if (LI->getLoopFor(From) != LI->getLoopFor(To))
1835     return true;
1836   return false;
1837 }
1838
1839 void CWriter::printPHICopiesForSuccessor (BasicBlock *CurBlock,
1840                                           BasicBlock *Successor,
1841                                           unsigned Indent) {
1842   for (BasicBlock::iterator I = Successor->begin(); isa<PHINode>(I); ++I) {
1843     PHINode *PN = cast<PHINode>(I);
1844     // Now we have to do the printing.
1845     Value *IV = PN->getIncomingValueForBlock(CurBlock);
1846     if (!isa<UndefValue>(IV)) {
1847       Out << std::string(Indent, ' ');
1848       Out << "  " << Mang->getValueName(I) << "__PHI_TEMPORARY = ";
1849       writeOperand(IV);
1850       Out << ";   /* for PHI node */\n";
1851     }
1852   }
1853 }
1854
1855 void CWriter::printBranchToBlock(BasicBlock *CurBB, BasicBlock *Succ,
1856                                  unsigned Indent) {
1857   if (isGotoCodeNecessary(CurBB, Succ)) {
1858     Out << std::string(Indent, ' ') << "  goto ";
1859     writeOperand(Succ);
1860     Out << ";\n";
1861   }
1862 }
1863
1864 // Branch instruction printing - Avoid printing out a branch to a basic block
1865 // that immediately succeeds the current one.
1866 //
1867 void CWriter::visitBranchInst(BranchInst &I) {
1868
1869   if (I.isConditional()) {
1870     if (isGotoCodeNecessary(I.getParent(), I.getSuccessor(0))) {
1871       Out << "  if (";
1872       writeOperand(I.getCondition());
1873       Out << ") {\n";
1874
1875       printPHICopiesForSuccessor (I.getParent(), I.getSuccessor(0), 2);
1876       printBranchToBlock(I.getParent(), I.getSuccessor(0), 2);
1877
1878       if (isGotoCodeNecessary(I.getParent(), I.getSuccessor(1))) {
1879         Out << "  } else {\n";
1880         printPHICopiesForSuccessor (I.getParent(), I.getSuccessor(1), 2);
1881         printBranchToBlock(I.getParent(), I.getSuccessor(1), 2);
1882       }
1883     } else {
1884       // First goto not necessary, assume second one is...
1885       Out << "  if (!";
1886       writeOperand(I.getCondition());
1887       Out << ") {\n";
1888
1889       printPHICopiesForSuccessor (I.getParent(), I.getSuccessor(1), 2);
1890       printBranchToBlock(I.getParent(), I.getSuccessor(1), 2);
1891     }
1892
1893     Out << "  }\n";
1894   } else {
1895     printPHICopiesForSuccessor (I.getParent(), I.getSuccessor(0), 0);
1896     printBranchToBlock(I.getParent(), I.getSuccessor(0), 0);
1897   }
1898   Out << "\n";
1899 }
1900
1901 // PHI nodes get copied into temporary values at the end of predecessor basic
1902 // blocks.  We now need to copy these temporary values into the REAL value for
1903 // the PHI.
1904 void CWriter::visitPHINode(PHINode &I) {
1905   writeOperand(&I);
1906   Out << "__PHI_TEMPORARY";
1907 }
1908
1909
1910 void CWriter::visitBinaryOperator(Instruction &I) {
1911   // binary instructions, shift instructions, setCond instructions.
1912   assert(!isa<PointerType>(I.getType()));
1913
1914   // We must cast the results of binary operations which might be promoted.
1915   bool needsCast = false;
1916   if ((I.getType() == Type::UByteTy) || (I.getType() == Type::SByteTy)
1917       || (I.getType() == Type::UShortTy) || (I.getType() == Type::ShortTy)
1918       || (I.getType() == Type::FloatTy)) {
1919     needsCast = true;
1920     Out << "((";
1921     printType(Out, I.getType());
1922     Out << ")(";
1923   }
1924
1925   // If this is a negation operation, print it out as such.  For FP, we don't
1926   // want to print "-0.0 - X".
1927   if (BinaryOperator::isNeg(&I)) {
1928     Out << "-(";
1929     writeOperand(BinaryOperator::getNegArgument(cast<BinaryOperator>(&I)));
1930     Out << ")";
1931   } else if (I.getOpcode() == Instruction::FRem) {
1932     // Output a call to fmod/fmodf instead of emitting a%b
1933     if (I.getType() == Type::FloatTy)
1934       Out << "fmodf(";
1935     else
1936       Out << "fmod(";
1937     writeOperand(I.getOperand(0));
1938     Out << ", ";
1939     writeOperand(I.getOperand(1));
1940     Out << ")";
1941   } else {
1942
1943     // Write out the cast of the instruction's value back to the proper type
1944     // if necessary.
1945     bool NeedsClosingParens = writeInstructionCast(I);
1946
1947     // Certain instructions require the operand to be forced to a specific type
1948     // so we use writeOperandWithCast here instead of writeOperand. Similarly
1949     // below for operand 1
1950     writeOperandWithCast(I.getOperand(0), I.getOpcode());
1951
1952     switch (I.getOpcode()) {
1953     case Instruction::Add: Out << " + "; break;
1954     case Instruction::Sub: Out << " - "; break;
1955     case Instruction::Mul: Out << '*'; break;
1956     case Instruction::URem:
1957     case Instruction::SRem:
1958     case Instruction::FRem: Out << '%'; break;
1959     case Instruction::UDiv:
1960     case Instruction::SDiv: 
1961     case Instruction::FDiv: Out << '/'; break;
1962     case Instruction::And: Out << " & "; break;
1963     case Instruction::Or: Out << " | "; break;
1964     case Instruction::Xor: Out << " ^ "; break;
1965     case Instruction::SetEQ: Out << " == "; break;
1966     case Instruction::SetNE: Out << " != "; break;
1967     case Instruction::SetLE: Out << " <= "; break;
1968     case Instruction::SetGE: Out << " >= "; break;
1969     case Instruction::SetLT: Out << " < "; break;
1970     case Instruction::SetGT: Out << " > "; break;
1971     case Instruction::Shl : Out << " << "; break;
1972     case Instruction::LShr:
1973     case Instruction::AShr: Out << " >> "; break;
1974     default: cerr << "Invalid operator type!" << I; abort();
1975     }
1976
1977     writeOperandWithCast(I.getOperand(1), I.getOpcode());
1978     if (NeedsClosingParens)
1979       Out << "))";
1980   }
1981
1982   if (needsCast) {
1983     Out << "))";
1984   }
1985 }
1986
1987 void CWriter::visitCastInst(CastInst &I) {
1988   const Type *DstTy = I.getType();
1989   const Type *SrcTy = I.getOperand(0)->getType();
1990   Out << '(';
1991   printCast(I.getOpcode(), SrcTy, DstTy);
1992   if (I.getOpcode() == Instruction::SExt && SrcTy == Type::BoolTy) {
1993     // Make sure we really get a sext from bool by subtracing the bool from 0
1994     Out << "0-";
1995   }
1996   writeOperand(I.getOperand(0));
1997   if (DstTy == Type::BoolTy && 
1998       (I.getOpcode() == Instruction::Trunc ||
1999        I.getOpcode() == Instruction::FPToUI ||
2000        I.getOpcode() == Instruction::FPToSI ||
2001        I.getOpcode() == Instruction::PtrToInt)) {
2002     // Make sure we really get a trunc to bool by anding the operand with 1 
2003     Out << "&1u";
2004   }
2005   Out << ')';
2006 }
2007
2008 void CWriter::visitSelectInst(SelectInst &I) {
2009   Out << "((";
2010   writeOperand(I.getCondition());
2011   Out << ") ? (";
2012   writeOperand(I.getTrueValue());
2013   Out << ") : (";
2014   writeOperand(I.getFalseValue());
2015   Out << "))";
2016 }
2017
2018
2019 void CWriter::lowerIntrinsics(Function &F) {
2020   for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
2021     for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; )
2022       if (CallInst *CI = dyn_cast<CallInst>(I++))
2023         if (Function *F = CI->getCalledFunction())
2024           switch (F->getIntrinsicID()) {
2025           case Intrinsic::not_intrinsic:
2026           case Intrinsic::vastart:
2027           case Intrinsic::vacopy:
2028           case Intrinsic::vaend:
2029           case Intrinsic::returnaddress:
2030           case Intrinsic::frameaddress:
2031           case Intrinsic::setjmp:
2032           case Intrinsic::longjmp:
2033           case Intrinsic::prefetch:
2034           case Intrinsic::dbg_stoppoint:
2035           case Intrinsic::powi_f32:
2036           case Intrinsic::powi_f64:
2037             // We directly implement these intrinsics
2038             break;
2039           default:
2040             // If this is an intrinsic that directly corresponds to a GCC
2041             // builtin, we handle it.
2042             const char *BuiltinName = "";
2043 #define GET_GCC_BUILTIN_NAME
2044 #include "llvm/Intrinsics.gen"
2045 #undef GET_GCC_BUILTIN_NAME
2046             // If we handle it, don't lower it.
2047             if (BuiltinName[0]) break;
2048             
2049             // All other intrinsic calls we must lower.
2050             Instruction *Before = 0;
2051             if (CI != &BB->front())
2052               Before = prior(BasicBlock::iterator(CI));
2053
2054             IL.LowerIntrinsicCall(CI);
2055             if (Before) {        // Move iterator to instruction after call
2056               I = Before; ++I;
2057             } else {
2058               I = BB->begin();
2059             }
2060             break;
2061           }
2062 }
2063
2064
2065
2066 void CWriter::visitCallInst(CallInst &I) {
2067   //check if we have inline asm
2068   if (isInlineAsm(I)) {
2069     visitInlineAsm(I);
2070     return;
2071   }
2072
2073   bool WroteCallee = false;
2074
2075   // Handle intrinsic function calls first...
2076   if (Function *F = I.getCalledFunction())
2077     if (Intrinsic::ID ID = (Intrinsic::ID)F->getIntrinsicID()) {
2078       switch (ID) {
2079       default: {
2080         // If this is an intrinsic that directly corresponds to a GCC
2081         // builtin, we emit it here.
2082         const char *BuiltinName = "";
2083 #define GET_GCC_BUILTIN_NAME
2084 #include "llvm/Intrinsics.gen"
2085 #undef GET_GCC_BUILTIN_NAME
2086         assert(BuiltinName[0] && "Unknown LLVM intrinsic!");
2087
2088         Out << BuiltinName;
2089         WroteCallee = true;
2090         break;
2091       }
2092       case Intrinsic::vastart:
2093         Out << "0; ";
2094
2095         Out << "va_start(*(va_list*)";
2096         writeOperand(I.getOperand(1));
2097         Out << ", ";
2098         // Output the last argument to the enclosing function...
2099         if (I.getParent()->getParent()->arg_empty()) {
2100           cerr << "The C backend does not currently support zero "
2101                << "argument varargs functions, such as '"
2102                << I.getParent()->getParent()->getName() << "'!\n";
2103           abort();
2104         }
2105         writeOperand(--I.getParent()->getParent()->arg_end());
2106         Out << ')';
2107         return;
2108       case Intrinsic::vaend:
2109         if (!isa<ConstantPointerNull>(I.getOperand(1))) {
2110           Out << "0; va_end(*(va_list*)";
2111           writeOperand(I.getOperand(1));
2112           Out << ')';
2113         } else {
2114           Out << "va_end(*(va_list*)0)";
2115         }
2116         return;
2117       case Intrinsic::vacopy:
2118         Out << "0; ";
2119         Out << "va_copy(*(va_list*)";
2120         writeOperand(I.getOperand(1));
2121         Out << ", *(va_list*)";
2122         writeOperand(I.getOperand(2));
2123         Out << ')';
2124         return;
2125       case Intrinsic::returnaddress:
2126         Out << "__builtin_return_address(";
2127         writeOperand(I.getOperand(1));
2128         Out << ')';
2129         return;
2130       case Intrinsic::frameaddress:
2131         Out << "__builtin_frame_address(";
2132         writeOperand(I.getOperand(1));
2133         Out << ')';
2134         return;
2135       case Intrinsic::powi_f32:
2136       case Intrinsic::powi_f64:
2137         Out << "__builtin_powi(";
2138         writeOperand(I.getOperand(1));
2139         Out << ", ";
2140         writeOperand(I.getOperand(2));
2141         Out << ')';
2142         return;
2143       case Intrinsic::setjmp:
2144 #if defined(HAVE__SETJMP) && defined(HAVE__LONGJMP)
2145         Out << "_";  // Use _setjmp on systems that support it!
2146 #endif
2147         Out << "setjmp(*(jmp_buf*)";
2148         writeOperand(I.getOperand(1));
2149         Out << ')';
2150         return;
2151       case Intrinsic::longjmp:
2152 #if defined(HAVE__SETJMP) && defined(HAVE__LONGJMP)
2153         Out << "_";  // Use _longjmp on systems that support it!
2154 #endif
2155         Out << "longjmp(*(jmp_buf*)";
2156         writeOperand(I.getOperand(1));
2157         Out << ", ";
2158         writeOperand(I.getOperand(2));
2159         Out << ')';
2160         return;
2161       case Intrinsic::prefetch:
2162         Out << "LLVM_PREFETCH((const void *)";
2163         writeOperand(I.getOperand(1));
2164         Out << ", ";
2165         writeOperand(I.getOperand(2));
2166         Out << ", ";
2167         writeOperand(I.getOperand(3));
2168         Out << ")";
2169         return;
2170       case Intrinsic::dbg_stoppoint: {
2171         // If we use writeOperand directly we get a "u" suffix which is rejected
2172         // by gcc.
2173         DbgStopPointInst &SPI = cast<DbgStopPointInst>(I);
2174
2175         Out << "\n#line "
2176             << SPI.getLine()
2177             << " \"" << SPI.getDirectory()
2178             << SPI.getFileName() << "\"\n";
2179         return;
2180       }
2181       }
2182     }
2183
2184   Value *Callee = I.getCalledValue();
2185
2186   // If this is a call to a struct-return function, assign to the first
2187   // parameter instead of passing it to the call.
2188   bool isStructRet = I.getCallingConv() == CallingConv::CSRet;
2189   if (isStructRet) {
2190     Out << "*(";
2191     writeOperand(I.getOperand(1));
2192     Out << ") = ";
2193   }
2194   
2195   if (I.isTailCall()) Out << " /*tail*/ ";
2196
2197   const PointerType  *PTy   = cast<PointerType>(Callee->getType());
2198   const FunctionType *FTy   = cast<FunctionType>(PTy->getElementType());
2199   
2200   if (!WroteCallee) {
2201     // If this is an indirect call to a struct return function, we need to cast
2202     // the pointer.
2203     bool NeedsCast = isStructRet && !isa<Function>(Callee);
2204
2205     // GCC is a real PITA.  It does not permit codegening casts of functions to
2206     // function pointers if they are in a call (it generates a trap instruction
2207     // instead!).  We work around this by inserting a cast to void* in between
2208     // the function and the function pointer cast.  Unfortunately, we can't just
2209     // form the constant expression here, because the folder will immediately
2210     // nuke it.
2211     //
2212     // Note finally, that this is completely unsafe.  ANSI C does not guarantee
2213     // that void* and function pointers have the same size. :( To deal with this
2214     // in the common case, we handle casts where the number of arguments passed
2215     // match exactly.
2216     //
2217     if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Callee))
2218       if (CE->isCast())
2219         if (Function *RF = dyn_cast<Function>(CE->getOperand(0))) {
2220           NeedsCast = true;
2221           Callee = RF;
2222         }
2223   
2224     if (NeedsCast) {
2225       // Ok, just cast the pointer type.
2226       Out << "((";
2227       if (!isStructRet)
2228         printType(Out, I.getCalledValue()->getType());
2229       else
2230         printStructReturnPointerFunctionType(Out, 
2231                              cast<PointerType>(I.getCalledValue()->getType()));
2232       Out << ")(void*)";
2233     }
2234     writeOperand(Callee);
2235     if (NeedsCast) Out << ')';
2236   }
2237
2238   Out << '(';
2239
2240   unsigned NumDeclaredParams = FTy->getNumParams();
2241
2242   CallSite::arg_iterator AI = I.op_begin()+1, AE = I.op_end();
2243   unsigned ArgNo = 0;
2244   if (isStructRet) {   // Skip struct return argument.
2245     ++AI;
2246     ++ArgNo;
2247   }
2248       
2249   bool PrintedArg = false;
2250   for (; AI != AE; ++AI, ++ArgNo) {
2251     if (PrintedArg) Out << ", ";
2252     if (ArgNo < NumDeclaredParams &&
2253         (*AI)->getType() != FTy->getParamType(ArgNo)) {
2254       Out << '(';
2255       printType(Out, FTy->getParamType(ArgNo));
2256       Out << ')';
2257     }
2258     writeOperand(*AI);
2259     PrintedArg = true;
2260   }
2261   Out << ')';
2262 }
2263
2264
2265 //This converts the llvm constraint string to something gcc is expecting.
2266 //TODO: work out platform independent constraints and factor those out
2267 //      of the per target tables
2268 //      handle multiple constraint codes
2269 std::string CWriter::InterpretASMConstraint(InlineAsm::ConstraintInfo& c) {
2270
2271   assert(c.Codes.size() == 1 && "Too many asm constraint codes to handle");
2272
2273   const char** table = 0;
2274   
2275   //Grab the translation table from TargetAsmInfo if it exists
2276   if (!TAsm) {
2277     std::string E;
2278     const TargetMachineRegistry::Entry* Match = 
2279       TargetMachineRegistry::getClosestStaticTargetForModule(*TheModule, E);
2280     if (Match) {
2281       //Per platform Target Machines don't exist, so create it
2282       // this must be done only once
2283       const TargetMachine* TM = Match->CtorFn(*TheModule, "");
2284       TAsm = TM->getTargetAsmInfo();
2285     }
2286   }
2287   if (TAsm)
2288     table = TAsm->getAsmCBE();
2289
2290   //Search the translation table if it exists
2291   for (int i = 0; table && table[i]; i += 2)
2292     if (c.Codes[0] == table[i])
2293       return table[i+1];
2294
2295   //default is identity
2296   return c.Codes[0];
2297 }
2298
2299 //TODO: import logic from AsmPrinter.cpp
2300 static std::string gccifyAsm(std::string asmstr) {
2301   for (std::string::size_type i = 0; i != asmstr.size(); ++i)
2302     if (asmstr[i] == '\n')
2303       asmstr.replace(i, 1, "\\n");
2304     else if (asmstr[i] == '\t')
2305       asmstr.replace(i, 1, "\\t");
2306     else if (asmstr[i] == '$') {
2307       if (asmstr[i + 1] == '{') {
2308         std::string::size_type a = asmstr.find_first_of(':', i + 1);
2309         std::string::size_type b = asmstr.find_first_of('}', i + 1);
2310         std::string n = "%" + 
2311           asmstr.substr(a + 1, b - a - 1) +
2312           asmstr.substr(i + 2, a - i - 2);
2313         asmstr.replace(i, b - i + 1, n);
2314         i += n.size() - 1;
2315       } else
2316         asmstr.replace(i, 1, "%");
2317     }
2318     else if (asmstr[i] == '%')//grr
2319       { asmstr.replace(i, 1, "%%"); ++i;}
2320   
2321   return asmstr;
2322 }
2323
2324 //TODO: assumptions about what consume arguments from the call are likely wrong
2325 //      handle communitivity
2326 void CWriter::visitInlineAsm(CallInst &CI) {
2327   InlineAsm* as = cast<InlineAsm>(CI.getOperand(0));
2328   std::vector<InlineAsm::ConstraintInfo> Constraints = as->ParseConstraints();
2329   std::vector<std::pair<std::string, Value*> > Input;
2330   std::vector<std::pair<std::string, Value*> > Output;
2331   std::string Clobber;
2332   int count = CI.getType() == Type::VoidTy ? 1 : 0;
2333   for (std::vector<InlineAsm::ConstraintInfo>::iterator I = Constraints.begin(),
2334          E = Constraints.end(); I != E; ++I) {
2335     assert(I->Codes.size() == 1 && "Too many asm constraint codes to handle");
2336     std::string c = 
2337       InterpretASMConstraint(*I);
2338     switch(I->Type) {
2339     default:
2340       assert(0 && "Unknown asm constraint");
2341       break;
2342     case InlineAsm::isInput: {
2343       if (c.size()) {
2344         Input.push_back(std::make_pair(c, count ? CI.getOperand(count) : &CI));
2345         ++count; //consume arg
2346       }
2347       break;
2348     }
2349     case InlineAsm::isOutput: {
2350       if (c.size()) {
2351         Output.push_back(std::make_pair("="+((I->isEarlyClobber ? "&" : "")+c),
2352                                         count ? CI.getOperand(count) : &CI));
2353         ++count; //consume arg
2354       }
2355       break;
2356     }
2357     case InlineAsm::isClobber: {
2358       if (c.size()) 
2359         Clobber += ",\"" + c + "\"";
2360       break;
2361     }
2362     }
2363   }
2364   
2365   //fix up the asm string for gcc
2366   std::string asmstr = gccifyAsm(as->getAsmString());
2367   
2368   Out << "__asm__ volatile (\"" << asmstr << "\"\n";
2369   Out << "        :";
2370   for (std::vector<std::pair<std::string, Value*> >::iterator I = Output.begin(),
2371          E = Output.end(); I != E; ++I) {
2372     Out << "\"" << I->first << "\"(";
2373     writeOperandRaw(I->second);
2374     Out << ")";
2375     if (I + 1 != E)
2376       Out << ",";
2377   }
2378   Out << "\n        :";
2379   for (std::vector<std::pair<std::string, Value*> >::iterator I = Input.begin(),
2380          E = Input.end(); I != E; ++I) {
2381     Out << "\"" << I->first << "\"(";
2382     writeOperandRaw(I->second);
2383     Out << ")";
2384     if (I + 1 != E)
2385       Out << ",";
2386   }
2387   if (Clobber.size())
2388     Out << "\n        :" << Clobber.substr(1);
2389   Out << ")";
2390 }
2391
2392 void CWriter::visitMallocInst(MallocInst &I) {
2393   assert(0 && "lowerallocations pass didn't work!");
2394 }
2395
2396 void CWriter::visitAllocaInst(AllocaInst &I) {
2397   Out << '(';
2398   printType(Out, I.getType());
2399   Out << ") alloca(sizeof(";
2400   printType(Out, I.getType()->getElementType());
2401   Out << ')';
2402   if (I.isArrayAllocation()) {
2403     Out << " * " ;
2404     writeOperand(I.getOperand(0));
2405   }
2406   Out << ')';
2407 }
2408
2409 void CWriter::visitFreeInst(FreeInst &I) {
2410   assert(0 && "lowerallocations pass didn't work!");
2411 }
2412
2413 void CWriter::printIndexingExpression(Value *Ptr, gep_type_iterator I,
2414                                       gep_type_iterator E) {
2415   bool HasImplicitAddress = false;
2416   // If accessing a global value with no indexing, avoid *(&GV) syndrome
2417   if (isa<GlobalValue>(Ptr)) {
2418     HasImplicitAddress = true;
2419   } else if (isDirectAlloca(Ptr)) {
2420     HasImplicitAddress = true;
2421   }
2422
2423   if (I == E) {
2424     if (!HasImplicitAddress)
2425       Out << '*';  // Implicit zero first argument: '*x' is equivalent to 'x[0]'
2426
2427     writeOperandInternal(Ptr);
2428     return;
2429   }
2430
2431   const Constant *CI = dyn_cast<Constant>(I.getOperand());
2432   if (HasImplicitAddress && (!CI || !CI->isNullValue()))
2433     Out << "(&";
2434
2435   writeOperandInternal(Ptr);
2436
2437   if (HasImplicitAddress && (!CI || !CI->isNullValue())) {
2438     Out << ')';
2439     HasImplicitAddress = false;  // HIA is only true if we haven't addressed yet
2440   }
2441
2442   assert(!HasImplicitAddress || (CI && CI->isNullValue()) &&
2443          "Can only have implicit address with direct accessing");
2444
2445   if (HasImplicitAddress) {
2446     ++I;
2447   } else if (CI && CI->isNullValue()) {
2448     gep_type_iterator TmpI = I; ++TmpI;
2449
2450     // Print out the -> operator if possible...
2451     if (TmpI != E && isa<StructType>(*TmpI)) {
2452       Out << (HasImplicitAddress ? "." : "->");
2453       Out << "field" << cast<ConstantInt>(TmpI.getOperand())->getZExtValue();
2454       I = ++TmpI;
2455     }
2456   }
2457
2458   for (; I != E; ++I)
2459     if (isa<StructType>(*I)) {
2460       Out << ".field" << cast<ConstantInt>(I.getOperand())->getZExtValue();
2461     } else {
2462       Out << '[';
2463       writeOperand(I.getOperand());
2464       Out << ']';
2465     }
2466 }
2467
2468 void CWriter::visitLoadInst(LoadInst &I) {
2469   Out << '*';
2470   if (I.isVolatile()) {
2471     Out << "((";
2472     printType(Out, I.getType(), "volatile*");
2473     Out << ")";
2474   }
2475
2476   writeOperand(I.getOperand(0));
2477
2478   if (I.isVolatile())
2479     Out << ')';
2480 }
2481
2482 void CWriter::visitStoreInst(StoreInst &I) {
2483   Out << '*';
2484   if (I.isVolatile()) {
2485     Out << "((";
2486     printType(Out, I.getOperand(0)->getType(), " volatile*");
2487     Out << ")";
2488   }
2489   writeOperand(I.getPointerOperand());
2490   if (I.isVolatile()) Out << ')';
2491   Out << " = ";
2492   writeOperand(I.getOperand(0));
2493 }
2494
2495 void CWriter::visitGetElementPtrInst(GetElementPtrInst &I) {
2496   Out << '&';
2497   printIndexingExpression(I.getPointerOperand(), gep_type_begin(I),
2498                           gep_type_end(I));
2499 }
2500
2501 void CWriter::visitVAArgInst(VAArgInst &I) {
2502   Out << "va_arg(*(va_list*)";
2503   writeOperand(I.getOperand(0));
2504   Out << ", ";
2505   printType(Out, I.getType());
2506   Out << ");\n ";
2507 }
2508
2509 //===----------------------------------------------------------------------===//
2510 //                       External Interface declaration
2511 //===----------------------------------------------------------------------===//
2512
2513 bool CTargetMachine::addPassesToEmitWholeFile(PassManager &PM,
2514                                               std::ostream &o,
2515                                               CodeGenFileType FileType,
2516                                               bool Fast) {
2517   if (FileType != TargetMachine::AssemblyFile) return true;
2518
2519   PM.add(createLowerGCPass());
2520   PM.add(createLowerAllocationsPass(true));
2521   PM.add(createLowerInvokePass());
2522   PM.add(createCFGSimplificationPass());   // clean up after lower invoke.
2523   PM.add(new CBackendNameAllUsedStructsAndMergeFunctions());
2524   PM.add(new CWriter(o));
2525   return false;
2526 }