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