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