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