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