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