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