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