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