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