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