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