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