LLVM API Documentation

CBackend.cpp

Go to the documentation of this file.
00001 //===-- CBackend.cpp - Library for converting LLVM code to C --------------===//
00002 //
00003 //                     The LLVM Compiler Infrastructure
00004 //
00005 // This file is distributed under the University of Illinois Open Source
00006 // License. See LICENSE.TXT for details.
00007 //
00008 //===----------------------------------------------------------------------===//
00009 //
00010 // This library converts LLVM code to C code, compilable by GCC and other C
00011 // compilers.
00012 //
00013 //===----------------------------------------------------------------------===//
00014 
00015 #include "CTargetMachine.h"
00016 #include "llvm/CallingConv.h"
00017 #include "llvm/Constants.h"
00018 #include "llvm/DerivedTypes.h"
00019 #include "llvm/Module.h"
00020 #include "llvm/Instructions.h"
00021 #include "llvm/Pass.h"
00022 #include "llvm/PassManager.h"
00023 #include "llvm/TypeSymbolTable.h"
00024 #include "llvm/Intrinsics.h"
00025 #include "llvm/IntrinsicInst.h"
00026 #include "llvm/InlineAsm.h"
00027 #include "llvm/ADT/StringExtras.h"
00028 #include "llvm/ADT/STLExtras.h"
00029 #include "llvm/Analysis/ConstantsScanner.h"
00030 #include "llvm/Analysis/FindUsedTypes.h"
00031 #include "llvm/Analysis/LoopInfo.h"
00032 #include "llvm/Analysis/ValueTracking.h"
00033 #include "llvm/CodeGen/Passes.h"
00034 #include "llvm/CodeGen/IntrinsicLowering.h"
00035 #include "llvm/Transforms/Scalar.h"
00036 #include "llvm/Target/TargetAsmInfo.h"
00037 #include "llvm/Target/TargetData.h"
00038 #include "llvm/Target/TargetRegistry.h"
00039 #include "llvm/Support/CallSite.h"
00040 #include "llvm/Support/CFG.h"
00041 #include "llvm/Support/ErrorHandling.h"
00042 #include "llvm/Support/FormattedStream.h"
00043 #include "llvm/Support/GetElementPtrTypeIterator.h"
00044 #include "llvm/Support/InstVisitor.h"
00045 #include "llvm/Support/Mangler.h"
00046 #include "llvm/Support/MathExtras.h"
00047 #include "llvm/System/Host.h"
00048 #include "llvm/Config/config.h"
00049 #include <algorithm>
00050 #include <sstream>
00051 using namespace llvm;
00052 
00053 extern "C" void LLVMInitializeCBackendTarget() { 
00054   // Register the target.
00055   RegisterTargetMachine<CTargetMachine> X(TheCBackendTarget);
00056 }
00057 
00058 namespace {
00059   /// CBackendNameAllUsedStructsAndMergeFunctions - This pass inserts names for
00060   /// any unnamed structure types that are used by the program, and merges
00061   /// external functions with the same name.
00062   ///
00063   class CBackendNameAllUsedStructsAndMergeFunctions : public ModulePass {
00064   public:
00065     static char ID;
00066     CBackendNameAllUsedStructsAndMergeFunctions() 
00067       : ModulePass(&ID) {}
00068     void getAnalysisUsage(AnalysisUsage &AU) const {
00069       AU.addRequired<FindUsedTypes>();
00070     }
00071 
00072     virtual const char *getPassName() const {
00073       return "C backend type canonicalizer";
00074     }
00075 
00076     virtual bool runOnModule(Module &M);
00077   };
00078 
00079   char CBackendNameAllUsedStructsAndMergeFunctions::ID = 0;
00080 
00081   /// CWriter - This class is the main chunk of code that converts an LLVM
00082   /// module to a C translation unit.
00083   class CWriter : public FunctionPass, public InstVisitor<CWriter> {
00084     formatted_raw_ostream &Out;
00085     IntrinsicLowering *IL;
00086     Mangler *Mang;
00087     LoopInfo *LI;
00088     const Module *TheModule;
00089     const TargetAsmInfo* TAsm;
00090     const TargetData* TD;
00091     std::map<const Type *, std::string> TypeNames;
00092     std::map<const ConstantFP *, unsigned> FPConstantMap;
00093     std::set<Function*> intrinsicPrototypesAlreadyGenerated;
00094     std::set<const Argument*> ByValParams;
00095     unsigned FPCounter;
00096     unsigned OpaqueCounter;
00097     DenseMap<const Value*, unsigned> AnonValueNumbers;
00098     unsigned NextAnonValueNumber;
00099 
00100   public:
00101     static char ID;
00102     explicit CWriter(formatted_raw_ostream &o)
00103       : FunctionPass(&ID), Out(o), IL(0), Mang(0), LI(0), 
00104         TheModule(0), TAsm(0), TD(0), OpaqueCounter(0), NextAnonValueNumber(0) {
00105       FPCounter = 0;
00106     }
00107 
00108     virtual const char *getPassName() const { return "C backend"; }
00109 
00110     void getAnalysisUsage(AnalysisUsage &AU) const {
00111       AU.addRequired<LoopInfo>();
00112       AU.setPreservesAll();
00113     }
00114 
00115     virtual bool doInitialization(Module &M);
00116 
00117     bool runOnFunction(Function &F) {
00118      // Do not codegen any 'available_externally' functions at all, they have
00119      // definitions outside the translation unit.
00120      if (F.hasAvailableExternallyLinkage())
00121        return false;
00122 
00123       LI = &getAnalysis<LoopInfo>();
00124 
00125       // Get rid of intrinsics we can't handle.
00126       lowerIntrinsics(F);
00127 
00128       // Output all floating point constants that cannot be printed accurately.
00129       printFloatingPointConstants(F);
00130 
00131       printFunction(F);
00132       return false;
00133     }
00134 
00135     virtual bool doFinalization(Module &M) {
00136       // Free memory...
00137       delete IL;
00138       delete TD;
00139       delete Mang;
00140       FPConstantMap.clear();
00141       TypeNames.clear();
00142       ByValParams.clear();
00143       intrinsicPrototypesAlreadyGenerated.clear();
00144       return false;
00145     }
00146 
00147     raw_ostream &printType(formatted_raw_ostream &Out,
00148                            const Type *Ty, 
00149                            bool isSigned = false,
00150                            const std::string &VariableName = "",
00151                            bool IgnoreName = false,
00152                            const AttrListPtr &PAL = AttrListPtr());
00153     std::ostream &printType(std::ostream &Out, const Type *Ty, 
00154                            bool isSigned = false,
00155                            const std::string &VariableName = "",
00156                            bool IgnoreName = false,
00157                            const AttrListPtr &PAL = AttrListPtr());
00158     raw_ostream &printSimpleType(formatted_raw_ostream &Out,
00159                                  const Type *Ty, 
00160                                  bool isSigned, 
00161                                  const std::string &NameSoFar = "");
00162     std::ostream &printSimpleType(std::ostream &Out, const Type *Ty, 
00163                                  bool isSigned, 
00164                                  const std::string &NameSoFar = "");
00165 
00166     void printStructReturnPointerFunctionType(formatted_raw_ostream &Out,
00167                                               const AttrListPtr &PAL,
00168                                               const PointerType *Ty);
00169 
00170     /// writeOperandDeref - Print the result of dereferencing the specified
00171     /// operand with '*'.  This is equivalent to printing '*' then using
00172     /// writeOperand, but avoids excess syntax in some cases.
00173     void writeOperandDeref(Value *Operand) {
00174       if (isAddressExposed(Operand)) {
00175         // Already something with an address exposed.
00176         writeOperandInternal(Operand);
00177       } else {
00178         Out << "*(";
00179         writeOperand(Operand);
00180         Out << ")";
00181       }
00182     }
00183     
00184     void writeOperand(Value *Operand, bool Static = false);
00185     void writeInstComputationInline(Instruction &I);
00186     void writeOperandInternal(Value *Operand, bool Static = false);
00187     void writeOperandWithCast(Value* Operand, unsigned Opcode);
00188     void writeOperandWithCast(Value* Operand, const ICmpInst &I);
00189     bool writeInstructionCast(const Instruction &I);
00190 
00191     void writeMemoryAccess(Value *Operand, const Type *OperandType,
00192                            bool IsVolatile, unsigned Alignment);
00193 
00194   private :
00195     std::string InterpretASMConstraint(InlineAsm::ConstraintInfo& c);
00196 
00197     void lowerIntrinsics(Function &F);
00198 
00199     void printModule(Module *M);
00200     void printModuleTypes(const TypeSymbolTable &ST);
00201     void printContainedStructs(const Type *Ty, std::set<const Type *> &);
00202     void printFloatingPointConstants(Function &F);
00203     void printFloatingPointConstants(const Constant *C);
00204     void printFunctionSignature(const Function *F, bool Prototype);
00205 
00206     void printFunction(Function &);
00207     void printBasicBlock(BasicBlock *BB);
00208     void printLoop(Loop *L);
00209 
00210     void printCast(unsigned opcode, const Type *SrcTy, const Type *DstTy);
00211     void printConstant(Constant *CPV, bool Static);
00212     void printConstantWithCast(Constant *CPV, unsigned Opcode);
00213     bool printConstExprCast(const ConstantExpr *CE, bool Static);
00214     void printConstantArray(ConstantArray *CPA, bool Static);
00215     void printConstantVector(ConstantVector *CV, bool Static);
00216 
00217     /// isAddressExposed - Return true if the specified value's name needs to
00218     /// have its address taken in order to get a C value of the correct type.
00219     /// This happens for global variables, byval parameters, and direct allocas.
00220     bool isAddressExposed(const Value *V) const {
00221       if (const Argument *A = dyn_cast<Argument>(V))
00222         return ByValParams.count(A);
00223       return isa<GlobalVariable>(V) || isDirectAlloca(V);
00224     }
00225     
00226     // isInlinableInst - Attempt to inline instructions into their uses to build
00227     // trees as much as possible.  To do this, we have to consistently decide
00228     // what is acceptable to inline, so that variable declarations don't get
00229     // printed and an extra copy of the expr is not emitted.
00230     //
00231     static bool isInlinableInst(const Instruction &I) {
00232       // Always inline cmp instructions, even if they are shared by multiple
00233       // expressions.  GCC generates horrible code if we don't.
00234       if (isa<CmpInst>(I)) 
00235         return true;
00236 
00237       // Must be an expression, must be used exactly once.  If it is dead, we
00238       // emit it inline where it would go.
00239       if (I.getType() == Type::getVoidTy(I.getContext()) || !I.hasOneUse() ||
00240           isa<TerminatorInst>(I) || isa<CallInst>(I) || isa<PHINode>(I) ||
00241           isa<LoadInst>(I) || isa<VAArgInst>(I) || isa<InsertElementInst>(I) ||
00242           isa<InsertValueInst>(I))
00243         // Don't inline a load across a store or other bad things!
00244         return false;
00245 
00246       // Must not be used in inline asm, extractelement, or shufflevector.
00247       if (I.hasOneUse()) {
00248         const Instruction &User = cast<Instruction>(*I.use_back());
00249         if (isInlineAsm(User) || isa<ExtractElementInst>(User) ||
00250             isa<ShuffleVectorInst>(User))
00251           return false;
00252       }
00253 
00254       // Only inline instruction it if it's use is in the same BB as the inst.
00255       return I.getParent() == cast<Instruction>(I.use_back())->getParent();
00256     }
00257 
00258     // isDirectAlloca - Define fixed sized allocas in the entry block as direct
00259     // variables which are accessed with the & operator.  This causes GCC to
00260     // generate significantly better code than to emit alloca calls directly.
00261     //
00262     static const AllocaInst *isDirectAlloca(const Value *V) {
00263       const AllocaInst *AI = dyn_cast<AllocaInst>(V);
00264       if (!AI) return false;
00265       if (AI->isArrayAllocation())
00266         return 0;   // FIXME: we can also inline fixed size array allocas!
00267       if (AI->getParent() != &AI->getParent()->getParent()->getEntryBlock())
00268         return 0;
00269       return AI;
00270     }
00271     
00272     // isInlineAsm - Check if the instruction is a call to an inline asm chunk
00273     static bool isInlineAsm(const Instruction& I) {
00274       if (isa<CallInst>(&I) && isa<InlineAsm>(I.getOperand(0)))
00275         return true;
00276       return false;
00277     }
00278     
00279     // Instruction visitation functions
00280     friend class InstVisitor<CWriter>;
00281 
00282     void visitReturnInst(ReturnInst &I);
00283     void visitBranchInst(BranchInst &I);
00284     void visitSwitchInst(SwitchInst &I);
00285     void visitInvokeInst(InvokeInst &I) {
00286       llvm_unreachable("Lowerinvoke pass didn't work!");
00287     }
00288 
00289     void visitUnwindInst(UnwindInst &I) {
00290       llvm_unreachable("Lowerinvoke pass didn't work!");
00291     }
00292     void visitUnreachableInst(UnreachableInst &I);
00293 
00294     void visitPHINode(PHINode &I);
00295     void visitBinaryOperator(Instruction &I);
00296     void visitICmpInst(ICmpInst &I);
00297     void visitFCmpInst(FCmpInst &I);
00298 
00299     void visitCastInst (CastInst &I);
00300     void visitSelectInst(SelectInst &I);
00301     void visitCallInst (CallInst &I);
00302     void visitInlineAsm(CallInst &I);
00303     bool visitBuiltinCall(CallInst &I, Intrinsic::ID ID, bool &WroteCallee);
00304 
00305     void visitMallocInst(MallocInst &I);
00306     void visitAllocaInst(AllocaInst &I);
00307     void visitFreeInst  (FreeInst   &I);
00308     void visitLoadInst  (LoadInst   &I);
00309     void visitStoreInst (StoreInst  &I);
00310     void visitGetElementPtrInst(GetElementPtrInst &I);
00311     void visitVAArgInst (VAArgInst &I);
00312     
00313     void visitInsertElementInst(InsertElementInst &I);
00314     void visitExtractElementInst(ExtractElementInst &I);
00315     void visitShuffleVectorInst(ShuffleVectorInst &SVI);
00316 
00317     void visitInsertValueInst(InsertValueInst &I);
00318     void visitExtractValueInst(ExtractValueInst &I);
00319 
00320     void visitInstruction(Instruction &I) {
00321 #ifndef NDEBUG
00322       cerr << "C Writer does not know about " << I;
00323 #endif
00324       llvm_unreachable(0);
00325     }
00326 
00327     void outputLValue(Instruction *I) {
00328       Out << "  " << GetValueName(I) << " = ";
00329     }
00330 
00331     bool isGotoCodeNecessary(BasicBlock *From, BasicBlock *To);
00332     void printPHICopiesForSuccessor(BasicBlock *CurBlock,
00333                                     BasicBlock *Successor, unsigned Indent);
00334     void printBranchToBlock(BasicBlock *CurBlock, BasicBlock *SuccBlock,
00335                             unsigned Indent);
00336     void printGEPExpression(Value *Ptr, gep_type_iterator I,
00337                             gep_type_iterator E, bool Static);
00338 
00339     std::string GetValueName(const Value *Operand);
00340   };
00341 }
00342 
00343 char CWriter::ID = 0;
00344 
00345 /// This method inserts names for any unnamed structure types that are used by
00346 /// the program, and removes names from structure types that are not used by the
00347 /// program.
00348 ///
00349 bool CBackendNameAllUsedStructsAndMergeFunctions::runOnModule(Module &M) {
00350   // Get a set of types that are used by the program...
00351   std::set<const Type *> UT = getAnalysis<FindUsedTypes>().getTypes();
00352 
00353   // Loop over the module symbol table, removing types from UT that are
00354   // already named, and removing names for types that are not used.
00355   //
00356   TypeSymbolTable &TST = M.getTypeSymbolTable();
00357   for (TypeSymbolTable::iterator TI = TST.begin(), TE = TST.end();
00358        TI != TE; ) {
00359     TypeSymbolTable::iterator I = TI++;
00360     
00361     // If this isn't a struct or array type, remove it from our set of types
00362     // to name. This simplifies emission later.
00363     if (!isa<StructType>(I->second) && !isa<OpaqueType>(I->second) &&
00364         !isa<ArrayType>(I->second)) {
00365       TST.remove(I);
00366     } else {
00367       // If this is not used, remove it from the symbol table.
00368       std::set<const Type *>::iterator UTI = UT.find(I->second);
00369       if (UTI == UT.end())
00370         TST.remove(I);
00371       else
00372         UT.erase(UTI);    // Only keep one name for this type.
00373     }
00374   }
00375 
00376   // UT now contains types that are not named.  Loop over it, naming
00377   // structure types.
00378   //
00379   bool Changed = false;
00380   unsigned RenameCounter = 0;
00381   for (std::set<const Type *>::const_iterator I = UT.begin(), E = UT.end();
00382        I != E; ++I)
00383     if (isa<StructType>(*I) || isa<ArrayType>(*I)) {
00384       while (M.addTypeName("unnamed"+utostr(RenameCounter), *I))
00385         ++RenameCounter;
00386       Changed = true;
00387     }
00388       
00389       
00390   // Loop over all external functions and globals.  If we have two with
00391   // identical names, merge them.
00392   // FIXME: This code should disappear when we don't allow values with the same
00393   // names when they have different types!
00394   std::map<std::string, GlobalValue*> ExtSymbols;
00395   for (Module::iterator I = M.begin(), E = M.end(); I != E;) {
00396     Function *GV = I++;
00397     if (GV->isDeclaration() && GV->hasName()) {
00398       std::pair<std::map<std::string, GlobalValue*>::iterator, bool> X
00399         = ExtSymbols.insert(std::make_pair(GV->getName(), GV));
00400       if (!X.second) {
00401         // Found a conflict, replace this global with the previous one.
00402         GlobalValue *OldGV = X.first->second;
00403         GV->replaceAllUsesWith(ConstantExpr::getBitCast(OldGV, GV->getType()));
00404         GV->eraseFromParent();
00405         Changed = true;
00406       }
00407     }
00408   }
00409   // Do the same for globals.
00410   for (Module::global_iterator I = M.global_begin(), E = M.global_end();
00411        I != E;) {
00412     GlobalVariable *GV = I++;
00413     if (GV->isDeclaration() && GV->hasName()) {
00414       std::pair<std::map<std::string, GlobalValue*>::iterator, bool> X
00415         = ExtSymbols.insert(std::make_pair(GV->getName(), GV));
00416       if (!X.second) {
00417         // Found a conflict, replace this global with the previous one.
00418         GlobalValue *OldGV = X.first->second;
00419         GV->replaceAllUsesWith(ConstantExpr::getBitCast(OldGV, GV->getType()));
00420         GV->eraseFromParent();
00421         Changed = true;
00422       }
00423     }
00424   }
00425   
00426   return Changed;
00427 }
00428 
00429 /// printStructReturnPointerFunctionType - This is like printType for a struct
00430 /// return type, except, instead of printing the type as void (*)(Struct*, ...)
00431 /// print it as "Struct (*)(...)", for struct return functions.
00432 void CWriter::printStructReturnPointerFunctionType(formatted_raw_ostream &Out,
00433                                                    const AttrListPtr &PAL,
00434                                                    const PointerType *TheTy) {
00435   const FunctionType *FTy = cast<FunctionType>(TheTy->getElementType());
00436   std::stringstream FunctionInnards;
00437   FunctionInnards << " (*) (";
00438   bool PrintedType = false;
00439 
00440   FunctionType::param_iterator I = FTy->param_begin(), E = FTy->param_end();
00441   const Type *RetTy = cast<PointerType>(I->get())->getElementType();
00442   unsigned Idx = 1;
00443   for (++I, ++Idx; I != E; ++I, ++Idx) {
00444     if (PrintedType)
00445       FunctionInnards << ", ";
00446     const Type *ArgTy = *I;
00447     if (PAL.paramHasAttr(Idx, Attribute::ByVal)) {
00448       assert(isa<PointerType>(ArgTy));
00449       ArgTy = cast<PointerType>(ArgTy)->getElementType();
00450     }
00451     printType(FunctionInnards, ArgTy,
00452         /*isSigned=*/PAL.paramHasAttr(Idx, Attribute::SExt), "");
00453     PrintedType = true;
00454   }
00455   if (FTy->isVarArg()) {
00456     if (PrintedType)
00457       FunctionInnards << ", ...";
00458   } else if (!PrintedType) {
00459     FunctionInnards << "void";
00460   }
00461   FunctionInnards << ')';
00462   std::string tstr = FunctionInnards.str();
00463   printType(Out, RetTy, 
00464       /*isSigned=*/PAL.paramHasAttr(0, Attribute::SExt), tstr);
00465 }
00466 
00467 raw_ostream &
00468 CWriter::printSimpleType(formatted_raw_ostream &Out, const Type *Ty,
00469                          bool isSigned,
00470                          const std::string &NameSoFar) {
00471   assert((Ty->isPrimitiveType() || Ty->isInteger() || isa<VectorType>(Ty)) && 
00472          "Invalid type for printSimpleType");
00473   switch (Ty->getTypeID()) {
00474   case Type::VoidTyID:   return Out << "void " << NameSoFar;
00475   case Type::IntegerTyID: {
00476     unsigned NumBits = cast<IntegerType>(Ty)->getBitWidth();
00477     if (NumBits == 1) 
00478       return Out << "bool " << NameSoFar;
00479     else if (NumBits <= 8)
00480       return Out << (isSigned?"signed":"unsigned") << " char " << NameSoFar;
00481     else if (NumBits <= 16)
00482       return Out << (isSigned?"signed":"unsigned") << " short " << NameSoFar;
00483     else if (NumBits <= 32)
00484       return Out << (isSigned?"signed":"unsigned") << " int " << NameSoFar;
00485     else if (NumBits <= 64)
00486       return Out << (isSigned?"signed":"unsigned") << " long long "<< NameSoFar;
00487     else { 
00488       assert(NumBits <= 128 && "Bit widths > 128 not implemented yet");
00489       return Out << (isSigned?"llvmInt128":"llvmUInt128") << " " << NameSoFar;
00490     }
00491   }
00492   case Type::FloatTyID:  return Out << "float "   << NameSoFar;
00493   case Type::DoubleTyID: return Out << "double "  << NameSoFar;
00494   // Lacking emulation of FP80 on PPC, etc., we assume whichever of these is
00495   // present matches host 'long double'.
00496   case Type::X86_FP80TyID:
00497   case Type::PPC_FP128TyID:
00498   case Type::FP128TyID:  return Out << "long double " << NameSoFar;
00499       
00500   case Type::VectorTyID: {
00501     const VectorType *VTy = cast<VectorType>(Ty);
00502     return printSimpleType(Out, VTy->getElementType(), isSigned,
00503                      " __attribute__((vector_size(" +
00504                      utostr(TD->getTypeAllocSize(VTy)) + " ))) " + NameSoFar);
00505   }
00506     
00507   default:
00508 #ifndef NDEBUG
00509     cerr << "Unknown primitive type: " << *Ty << "\n";
00510 #endif
00511     llvm_unreachable(0);
00512   }
00513 }
00514 
00515 std::ostream &
00516 CWriter::printSimpleType(std::ostream &Out, const Type *Ty, bool isSigned,
00517                          const std::string &NameSoFar) {
00518   assert((Ty->isPrimitiveType() || Ty->isInteger() || isa<VectorType>(Ty)) && 
00519          "Invalid type for printSimpleType");
00520   switch (Ty->getTypeID()) {
00521   case Type::VoidTyID:   return Out << "void " << NameSoFar;
00522   case Type::IntegerTyID: {
00523     unsigned NumBits = cast<IntegerType>(Ty)->getBitWidth();
00524     if (NumBits == 1) 
00525       return Out << "bool " << NameSoFar;
00526     else if (NumBits <= 8)
00527       return Out << (isSigned?"signed":"unsigned") << " char " << NameSoFar;
00528     else if (NumBits <= 16)
00529       return Out << (isSigned?"signed":"unsigned") << " short " << NameSoFar;
00530     else if (NumBits <= 32)
00531       return Out << (isSigned?"signed":"unsigned") << " int " << NameSoFar;
00532     else if (NumBits <= 64)
00533       return Out << (isSigned?"signed":"unsigned") << " long long "<< NameSoFar;
00534     else { 
00535       assert(NumBits <= 128 && "Bit widths > 128 not implemented yet");
00536       return Out << (isSigned?"llvmInt128":"llvmUInt128") << " " << NameSoFar;
00537     }
00538   }
00539   case Type::FloatTyID:  return Out << "float "   << NameSoFar;
00540   case Type::DoubleTyID: return Out << "double "  << NameSoFar;
00541   // Lacking emulation of FP80 on PPC, etc., we assume whichever of these is
00542   // present matches host 'long double'.
00543   case Type::X86_FP80TyID:
00544   case Type::PPC_FP128TyID:
00545   case Type::FP128TyID:  return Out << "long double " << NameSoFar;
00546       
00547   case Type::VectorTyID: {
00548     const VectorType *VTy = cast<VectorType>(Ty);
00549     return printSimpleType(Out, VTy->getElementType(), isSigned,
00550                      " __attribute__((vector_size(" +
00551                      utostr(TD->getTypeAllocSize(VTy)) + " ))) " + NameSoFar);
00552   }
00553     
00554   default:
00555 #ifndef NDEBUG
00556     cerr << "Unknown primitive type: " << *Ty << "\n";
00557 #endif
00558     llvm_unreachable(0);
00559   }
00560 }
00561 
00562 // Pass the Type* and the variable name and this prints out the variable
00563 // declaration.
00564 //
00565 raw_ostream &CWriter::printType(formatted_raw_ostream &Out,
00566                                 const Type *Ty,
00567                                 bool isSigned, const std::string &NameSoFar,
00568                                 bool IgnoreName, const AttrListPtr &PAL) {
00569   if (Ty->isPrimitiveType() || Ty->isInteger() || isa<VectorType>(Ty)) {
00570     printSimpleType(Out, Ty, isSigned, NameSoFar);
00571     return Out;
00572   }
00573 
00574   // Check to see if the type is named.
00575   if (!IgnoreName || isa<OpaqueType>(Ty)) {
00576     std::map<const Type *, std::string>::iterator I = TypeNames.find(Ty);
00577     if (I != TypeNames.end()) return Out << I->second << ' ' << NameSoFar;
00578   }
00579 
00580   switch (Ty->getTypeID()) {
00581   case Type::FunctionTyID: {
00582     const FunctionType *FTy = cast<FunctionType>(Ty);
00583     std::stringstream FunctionInnards;
00584     FunctionInnards << " (" << NameSoFar << ") (";
00585     unsigned Idx = 1;
00586     for (FunctionType::param_iterator I = FTy->param_begin(),
00587            E = FTy->param_end(); I != E; ++I) {
00588       const Type *ArgTy = *I;
00589       if (PAL.paramHasAttr(Idx, Attribute::ByVal)) {
00590         assert(isa<PointerType>(ArgTy));
00591         ArgTy = cast<PointerType>(ArgTy)->getElementType();
00592       }
00593       if (I != FTy->param_begin())
00594         FunctionInnards << ", ";
00595       printType(FunctionInnards, ArgTy,
00596         /*isSigned=*/PAL.paramHasAttr(Idx, Attribute::SExt), "");
00597       ++Idx;
00598     }
00599     if (FTy->isVarArg()) {
00600       if (FTy->getNumParams())
00601         FunctionInnards << ", ...";
00602     } else if (!FTy->getNumParams()) {
00603       FunctionInnards << "void";
00604     }
00605     FunctionInnards << ')';
00606     std::string tstr = FunctionInnards.str();
00607     printType(Out, FTy->getReturnType(), 
00608       /*isSigned=*/PAL.paramHasAttr(0, Attribute::SExt), tstr);
00609     return Out;
00610   }
00611   case Type::StructTyID: {
00612     const StructType *STy = cast<StructType>(Ty);
00613     Out << NameSoFar + " {\n";
00614     unsigned Idx = 0;
00615     for (StructType::element_iterator I = STy->element_begin(),
00616            E = STy->element_end(); I != E; ++I) {
00617       Out << "  ";
00618       printType(Out, *I, false, "field" + utostr(Idx++));
00619       Out << ";\n";
00620     }
00621     Out << '}';
00622     if (STy->isPacked())
00623       Out << " __attribute__ ((packed))";
00624     return Out;
00625   }
00626 
00627   case Type::PointerTyID: {
00628     const PointerType *PTy = cast<PointerType>(Ty);
00629     std::string ptrName = "*" + NameSoFar;
00630 
00631     if (isa<ArrayType>(PTy->getElementType()) ||
00632         isa<VectorType>(PTy->getElementType()))
00633       ptrName = "(" + ptrName + ")";
00634 
00635     if (!PAL.isEmpty())
00636       // Must be a function ptr cast!
00637       return printType(Out, PTy->getElementType(), false, ptrName, true, PAL);
00638     return printType(Out, PTy->getElementType(), false, ptrName);
00639   }
00640 
00641   case Type::ArrayTyID: {
00642     const ArrayType *ATy = cast<ArrayType>(Ty);
00643     unsigned NumElements = ATy->getNumElements();
00644     if (NumElements == 0) NumElements = 1;
00645     // Arrays are wrapped in structs to allow them to have normal
00646     // value semantics (avoiding the array "decay").
00647     Out << NameSoFar << " { ";
00648     printType(Out, ATy->getElementType(), false,
00649               "array[" + utostr(NumElements) + "]");
00650     return Out << "; }";
00651   }
00652 
00653   case Type::OpaqueTyID: {
00654     std::string TyName = "struct opaque_" + itostr(OpaqueCounter++);
00655     assert(TypeNames.find(Ty) == TypeNames.end());
00656     TypeNames[Ty] = TyName;
00657     return Out << TyName << ' ' << NameSoFar;
00658   }
00659   default:
00660     llvm_unreachable("Unhandled case in getTypeProps!");
00661   }
00662 
00663   return Out;
00664 }
00665 
00666 // Pass the Type* and the variable name and this prints out the variable
00667 // declaration.
00668 //
00669 std::ostream &CWriter::printType(std::ostream &Out, const Type *Ty,
00670                                  bool isSigned, const std::string &NameSoFar,
00671                                  bool IgnoreName, const AttrListPtr &PAL) {
00672   if (Ty->isPrimitiveType() || Ty->isInteger() || isa<VectorType>(Ty)) {
00673     printSimpleType(Out, Ty, isSigned, NameSoFar);
00674     return Out;
00675   }
00676 
00677   // Check to see if the type is named.
00678   if (!IgnoreName || isa<OpaqueType>(Ty)) {
00679     std::map<const Type *, std::string>::iterator I = TypeNames.find(Ty);
00680     if (I != TypeNames.end()) return Out << I->second << ' ' << NameSoFar;
00681   }
00682 
00683   switch (Ty->getTypeID()) {
00684   case Type::FunctionTyID: {
00685     const FunctionType *FTy = cast<FunctionType>(Ty);
00686     std::stringstream FunctionInnards;
00687     FunctionInnards << " (" << NameSoFar << ") (";
00688     unsigned Idx = 1;
00689     for (FunctionType::param_iterator I = FTy->param_begin(),
00690            E = FTy->param_end(); I != E; ++I) {
00691       const Type *ArgTy = *I;
00692       if (PAL.paramHasAttr(Idx, Attribute::ByVal)) {
00693         assert(isa<PointerType>(ArgTy));
00694         ArgTy = cast<PointerType>(ArgTy)->getElementType();
00695       }
00696       if (I != FTy->param_begin())
00697         FunctionInnards << ", ";
00698       printType(FunctionInnards, ArgTy,
00699         /*isSigned=*/PAL.paramHasAttr(Idx, Attribute::SExt), "");
00700       ++Idx;
00701     }
00702     if (FTy->isVarArg()) {
00703       if (FTy->getNumParams())
00704         FunctionInnards << ", ...";
00705     } else if (!FTy->getNumParams()) {
00706       FunctionInnards << "void";
00707     }
00708     FunctionInnards << ')';
00709     std::string tstr = FunctionInnards.str();
00710     printType(Out, FTy->getReturnType(), 
00711       /*isSigned=*/PAL.paramHasAttr(0, Attribute::SExt), tstr);
00712     return Out;
00713   }
00714   case Type::StructTyID: {
00715     const StructType *STy = cast<StructType>(Ty);
00716     Out << NameSoFar + " {\n";
00717     unsigned Idx = 0;
00718     for (StructType::element_iterator I = STy->element_begin(),
00719            E = STy->element_end(); I != E; ++I) {
00720       Out << "  ";
00721       printType(Out, *I, false, "field" + utostr(Idx++));
00722       Out << ";\n";
00723     }
00724     Out << '}';
00725     if (STy->isPacked())
00726       Out << " __attribute__ ((packed))";
00727     return Out;
00728   }
00729 
00730   case Type::PointerTyID: {
00731     const PointerType *PTy = cast<PointerType>(Ty);
00732     std::string ptrName = "*" + NameSoFar;
00733 
00734     if (isa<ArrayType>(PTy->getElementType()) ||
00735         isa<VectorType>(PTy->getElementType()))
00736       ptrName = "(" + ptrName + ")";
00737 
00738     if (!PAL.isEmpty())
00739       // Must be a function ptr cast!
00740       return printType(Out, PTy->getElementType(), false, ptrName, true, PAL);
00741     return printType(Out, PTy->getElementType(), false, ptrName);
00742   }
00743 
00744   case Type::ArrayTyID: {
00745     const ArrayType *ATy = cast<ArrayType>(Ty);
00746     unsigned NumElements = ATy->getNumElements();
00747     if (NumElements == 0) NumElements = 1;
00748     // Arrays are wrapped in structs to allow them to have normal
00749     // value semantics (avoiding the array "decay").
00750     Out << NameSoFar << " { ";
00751     printType(Out, ATy->getElementType(), false,
00752               "array[" + utostr(NumElements) + "]");
00753     return Out << "; }";
00754   }
00755 
00756   case Type::OpaqueTyID: {
00757     std::string TyName = "struct opaque_" + itostr(OpaqueCounter++);
00758     assert(TypeNames.find(Ty) == TypeNames.end());
00759     TypeNames[Ty] = TyName;
00760     return Out << TyName << ' ' << NameSoFar;
00761   }
00762   default:
00763     llvm_unreachable("Unhandled case in getTypeProps!");
00764   }
00765 
00766   return Out;
00767 }
00768 
00769 void CWriter::printConstantArray(ConstantArray *CPA, bool Static) {
00770 
00771   // As a special case, print the array as a string if it is an array of
00772   // ubytes or an array of sbytes with positive values.
00773   //
00774   const Type *ETy = CPA->getType()->getElementType();
00775   bool isString = (ETy == Type::getInt8Ty(CPA->getContext()) ||
00776                    ETy == Type::getInt8Ty(CPA->getContext()));
00777 
00778   // Make sure the last character is a null char, as automatically added by C
00779   if (isString && (CPA->getNumOperands() == 0 ||
00780                    !cast<Constant>(*(CPA->op_end()-1))->isNullValue()))
00781     isString = false;
00782 
00783   if (isString) {
00784     Out << '\"';
00785     // Keep track of whether the last number was a hexadecimal escape
00786     bool LastWasHex = false;
00787 
00788     // Do not include the last character, which we know is null
00789     for (unsigned i = 0, e = CPA->getNumOperands()-1; i != e; ++i) {
00790       unsigned char C = cast<ConstantInt>(CPA->getOperand(i))->getZExtValue();
00791 
00792       // Print it out literally if it is a printable character.  The only thing
00793       // to be careful about is when the last letter output was a hex escape
00794       // code, in which case we have to be careful not to print out hex digits
00795       // explicitly (the C compiler thinks it is a continuation of the previous
00796       // character, sheesh...)
00797       //
00798       if (isprint(C) && (!LastWasHex || !isxdigit(C))) {
00799         LastWasHex = false;
00800         if (C == '"' || C == '\\')
00801           Out << "\\" << (char)C;
00802         else
00803           Out << (char)C;
00804       } else {
00805         LastWasHex = false;
00806         switch (C) {
00807         case '\n': Out << "\\n"; break;
00808         case '\t': Out << "\\t"; break;
00809         case '\r': Out << "\\r"; break;
00810         case '\v': Out << "\\v"; break;
00811         case '\a': Out << "\\a"; break;
00812         case '\"': Out << "\\\""; break;
00813         case '\'': Out << "\\\'"; break;
00814         default:
00815           Out << "\\x";
00816           Out << (char)(( C/16  < 10) ? ( C/16 +'0') : ( C/16 -10+'A'));
00817           Out << (char)(((C&15) < 10) ? ((C&15)+'0') : ((C&15)-10+'A'));
00818           LastWasHex = true;
00819           break;
00820         }
00821       }
00822     }
00823     Out << '\"';
00824   } else {
00825     Out << '{';
00826     if (CPA->getNumOperands()) {
00827       Out << ' ';
00828       printConstant(cast<Constant>(CPA->getOperand(0)), Static);
00829       for (unsigned i = 1, e = CPA->getNumOperands(); i != e; ++i) {
00830         Out << ", ";
00831         printConstant(cast<Constant>(CPA->getOperand(i)), Static);
00832       }
00833     }
00834     Out << " }";
00835   }
00836 }
00837 
00838 void CWriter::printConstantVector(ConstantVector *CP, bool Static) {
00839   Out << '{';
00840   if (CP->getNumOperands()) {
00841     Out << ' ';
00842     printConstant(cast<Constant>(CP->getOperand(0)), Static);
00843     for (unsigned i = 1, e = CP->getNumOperands(); i != e; ++i) {
00844       Out << ", ";
00845       printConstant(cast<Constant>(CP->getOperand(i)), Static);
00846     }
00847   }
00848   Out << " }";
00849 }
00850 
00851 // isFPCSafeToPrint - Returns true if we may assume that CFP may be written out
00852 // textually as a double (rather than as a reference to a stack-allocated
00853 // variable). We decide this by converting CFP to a string and back into a
00854 // double, and then checking whether the conversion results in a bit-equal
00855 // double to the original value of CFP. This depends on us and the target C
00856 // compiler agreeing on the conversion process (which is pretty likely since we
00857 // only deal in IEEE FP).
00858 //
00859 static bool isFPCSafeToPrint(const ConstantFP *CFP) {
00860   bool ignored;
00861   // Do long doubles in hex for now.
00862   if (CFP->getType() != Type::getFloatTy(CFP->getContext()) &&
00863       CFP->getType() != Type::getDoubleTy(CFP->getContext()))
00864     return false;
00865   APFloat APF = APFloat(CFP->getValueAPF());  // copy
00866   if (CFP->getType() == Type::getFloatTy(CFP->getContext()))
00867     APF.convert(APFloat::IEEEdouble, APFloat::rmNearestTiesToEven, &ignored);
00868 #if HAVE_PRINTF_A && ENABLE_CBE_PRINTF_A
00869   char Buffer[100];
00870   sprintf(Buffer, "%a", APF.convertToDouble());
00871   if (!strncmp(Buffer, "0x", 2) ||
00872       !strncmp(Buffer, "-0x", 3) ||
00873       !strncmp(Buffer, "+0x", 3))
00874     return APF.bitwiseIsEqual(APFloat(atof(Buffer)));
00875   return false;
00876 #else
00877   std::string StrVal = ftostr(APF);
00878 
00879   while (StrVal[0] == ' ')
00880     StrVal.erase(StrVal.begin());
00881 
00882   // Check to make sure that the stringized number is not some string like "Inf"
00883   // or NaN.  Check that the string matches the "[-+]?[0-9]" regex.
00884   if ((StrVal[0] >= '0' && StrVal[0] <= '9') ||
00885       ((StrVal[0] == '-' || StrVal[0] == '+') &&
00886        (StrVal[1] >= '0' && StrVal[1] <= '9')))
00887     // Reparse stringized version!
00888     return APF.bitwiseIsEqual(APFloat(atof(StrVal.c_str())));
00889   return false;
00890 #endif
00891 }
00892 
00893 /// Print out the casting for a cast operation. This does the double casting
00894 /// necessary for conversion to the destination type, if necessary. 
00895 /// @brief Print a cast
00896 void CWriter::printCast(unsigned opc, const Type *SrcTy, const Type *DstTy) {
00897   // Print the destination type cast
00898   switch (opc) {
00899     case Instruction::UIToFP:
00900     case Instruction::SIToFP:
00901     case Instruction::IntToPtr:
00902     case Instruction::Trunc:
00903     case Instruction::BitCast:
00904     case Instruction::FPExt:
00905     case Instruction::FPTrunc: // For these the DstTy sign doesn't matter
00906       Out << '(';
00907       printType(Out, DstTy);
00908       Out << ')';
00909       break;
00910     case Instruction::ZExt:
00911     case Instruction::PtrToInt:
00912     case Instruction::FPToUI: // For these, make sure we get an unsigned dest
00913       Out << '(';
00914       printSimpleType(Out, DstTy, false);
00915       Out << ')';
00916       break;
00917     case Instruction::SExt: 
00918     case Instruction::FPToSI: // For these, make sure we get a signed dest
00919       Out << '(';
00920       printSimpleType(Out, DstTy, true);
00921       Out << ')';
00922       break;
00923     default:
00924       llvm_unreachable("Invalid cast opcode");
00925   }
00926 
00927   // Print the source type cast
00928   switch (opc) {
00929     case Instruction::UIToFP:
00930     case Instruction::ZExt:
00931       Out << '(';
00932       printSimpleType(Out, SrcTy, false);
00933       Out << ')';
00934       break;
00935     case Instruction::SIToFP:
00936     case Instruction::SExt:
00937       Out << '(';
00938       printSimpleType(Out, SrcTy, true); 
00939       Out << ')';
00940       break;
00941     case Instruction::IntToPtr:
00942     case Instruction::PtrToInt:
00943       // Avoid "cast to pointer from integer of different size" warnings
00944       Out << "(unsigned long)";
00945       break;
00946     case Instruction::Trunc:
00947     case Instruction::BitCast:
00948     case Instruction::FPExt:
00949     case Instruction::FPTrunc:
00950     case Instruction::FPToSI:
00951     case Instruction::FPToUI:
00952       break; // These don't need a source cast.
00953     default:
00954       llvm_unreachable("Invalid cast opcode");
00955       break;
00956   }
00957 }
00958 
00959 // printConstant - The LLVM Constant to C Constant converter.
00960 void CWriter::printConstant(Constant *CPV, bool Static) {
00961   if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(CPV)) {
00962     switch (CE->getOpcode()) {
00963     case Instruction::Trunc:
00964     case Instruction::ZExt:
00965     case Instruction::SExt:
00966     case Instruction::FPTrunc:
00967     case Instruction::FPExt:
00968     case Instruction::UIToFP:
00969     case Instruction::SIToFP:
00970     case Instruction::FPToUI:
00971     case Instruction::FPToSI:
00972     case Instruction::PtrToInt:
00973     case Instruction::IntToPtr:
00974     case Instruction::BitCast:
00975       Out << "(";
00976       printCast(CE->getOpcode(), CE->getOperand(0)->getType(), CE->getType());
00977       if (CE->getOpcode() == Instruction::SExt &&
00978           CE->getOperand(0)->getType() == Type::getInt1Ty(CPV->getContext())) {
00979         // Make sure we really sext from bool here by subtracting from 0
00980         Out << "0-";
00981       }
00982       printConstant(CE->getOperand(0), Static);
00983       if (CE->getType() == Type::getInt1Ty(CPV->getContext()) &&
00984           (CE->getOpcode() == Instruction::Trunc ||
00985            CE->getOpcode() == Instruction::FPToUI ||
00986            CE->getOpcode() == Instruction::FPToSI ||
00987            CE->getOpcode() == Instruction::PtrToInt)) {
00988         // Make sure we really truncate to bool here by anding with 1
00989         Out << "&1u";
00990       }
00991       Out << ')';
00992       return;
00993 
00994     case Instruction::GetElementPtr:
00995       Out << "(";
00996       printGEPExpression(CE->getOperand(0), gep_type_begin(CPV),
00997                          gep_type_end(CPV), Static);
00998       Out << ")";
00999       return;
01000     case Instruction::Select:
01001       Out << '(';
01002       printConstant(CE->getOperand(0), Static);
01003       Out << '?';
01004       printConstant(CE->getOperand(1), Static);
01005       Out << ':';
01006       printConstant(CE->getOperand(2), Static);
01007       Out << ')';
01008       return;
01009     case Instruction::Add:
01010     case Instruction::FAdd:
01011     case Instruction::Sub:
01012     case Instruction::FSub:
01013     case Instruction::Mul:
01014     case Instruction::FMul:
01015     case Instruction::SDiv:
01016     case Instruction::UDiv:
01017     case Instruction::FDiv:
01018     case Instruction::URem:
01019     case Instruction::SRem:
01020     case Instruction::FRem:
01021     case Instruction::And:
01022     case Instruction::Or:
01023     case Instruction::Xor:
01024     case Instruction::ICmp:
01025     case Instruction::Shl:
01026     case Instruction::LShr:
01027     case Instruction::AShr:
01028     {
01029       Out << '(';
01030       bool NeedsClosingParens = printConstExprCast(CE, Static); 
01031       printConstantWithCast(CE->getOperand(0), CE->getOpcode());
01032       switch (CE->getOpcode()) {
01033       case Instruction::Add:
01034       case Instruction::FAdd: Out << " + "; break;
01035       case Instruction::Sub:
01036       case Instruction::FSub: Out << " - "; break;
01037       case Instruction::Mul:
01038       case Instruction::FMul: Out << " * "; break;
01039       case Instruction::URem:
01040       case Instruction::SRem: 
01041       case Instruction::FRem: Out << " % "; break;
01042       case Instruction::UDiv: 
01043       case Instruction::SDiv: 
01044       case Instruction::FDiv: Out << " / "; break;
01045       case Instruction::And: Out << " & "; break;
01046       case Instruction::Or:  Out << " | "; break;
01047       case Instruction::Xor: Out << " ^ "; break;
01048       case Instruction::Shl: Out << " << "; break;
01049       case Instruction::LShr:
01050       case Instruction::AShr: Out << " >> "; break;
01051       case Instruction::ICmp:
01052         switch (CE->getPredicate()) {
01053           case ICmpInst::ICMP_EQ: Out << " == "; break;
01054           case ICmpInst::ICMP_NE: Out << " != "; break;
01055           case ICmpInst::ICMP_SLT: 
01056           case ICmpInst::ICMP_ULT: Out << " < "; break;
01057           case ICmpInst::ICMP_SLE:
01058           case ICmpInst::ICMP_ULE: Out << " <= "; break;
01059           case ICmpInst::ICMP_SGT:
01060           case ICmpInst::ICMP_UGT: Out << " > "; break;
01061           case ICmpInst::ICMP_SGE:
01062           case ICmpInst::ICMP_UGE: Out << " >= "; break;
01063           default: llvm_unreachable("Illegal ICmp predicate");
01064         }
01065         break;
01066       default: llvm_unreachable("Illegal opcode here!");
01067       }
01068       printConstantWithCast(CE->getOperand(1), CE->getOpcode());
01069       if (NeedsClosingParens)
01070         Out << "))";
01071       Out << ')';
01072       return;
01073     }
01074     case Instruction::FCmp: {
01075       Out << '('; 
01076       bool NeedsClosingParens = printConstExprCast(CE, Static); 
01077       if (CE->getPredicate() == FCmpInst::FCMP_FALSE)
01078         Out << "0";
01079       else if (CE->getPredicate() == FCmpInst::FCMP_TRUE)
01080         Out << "1";
01081       else {
01082         const char* op = 0;
01083         switch (CE->getPredicate()) {
01084         default: llvm_unreachable("Illegal FCmp predicate");
01085         case FCmpInst::FCMP_ORD: op = "ord"; break;
01086         case FCmpInst::FCMP_UNO: op = "uno"; break;
01087         case FCmpInst::FCMP_UEQ: op = "ueq"; break;
01088         case FCmpInst::FCMP_UNE: op = "une"; break;
01089         case FCmpInst::FCMP_ULT: op = "ult"; break;
01090         case FCmpInst::FCMP_ULE: op = "ule"; break;
01091         case FCmpInst::FCMP_UGT: op = "ugt"; break;
01092         case FCmpInst::FCMP_UGE: op = "uge"; break;
01093         case FCmpInst::FCMP_OEQ: op = "oeq"; break;
01094         case FCmpInst::FCMP_ONE: op = "one"; break;
01095         case FCmpInst::FCMP_OLT: op = "olt"; break;
01096         case FCmpInst::FCMP_OLE: op = "ole"; break;
01097         case FCmpInst::FCMP_OGT: op = "ogt"; break;
01098         case FCmpInst::FCMP_OGE: op = "oge"; break;
01099         }
01100         Out << "llvm_fcmp_" << op << "(";
01101         printConstantWithCast(CE->getOperand(0), CE->getOpcode());
01102         Out << ", ";
01103         printConstantWithCast(CE->getOperand(1), CE->getOpcode());
01104         Out << ")";
01105       }
01106       if (NeedsClosingParens)
01107         Out << "))";
01108       Out << ')';
01109       return;
01110     }
01111     default:
01112 #ifndef NDEBUG
01113       cerr << "CWriter Error: Unhandled constant expression: "
01114            << *CE << "\n";
01115 #endif
01116       llvm_unreachable(0);
01117     }
01118   } else if (isa<UndefValue>(CPV) && CPV->getType()->isSingleValueType()) {
01119     Out << "((";
01120     printType(Out, CPV->getType()); // sign doesn't matter
01121     Out << ")/*UNDEF*/";
01122     if (!isa<VectorType>(CPV->getType())) {
01123       Out << "0)";
01124     } else {
01125       Out << "{})";
01126     }
01127     return;
01128   }
01129 
01130   if (ConstantInt *CI = dyn_cast<ConstantInt>(CPV)) {
01131     const Type* Ty = CI->getType();
01132     if (Ty == Type::getInt1Ty(CPV->getContext()))
01133       Out << (CI->getZExtValue() ? '1' : '0');
01134     else if (Ty == Type::getInt32Ty(CPV->getContext()))
01135       Out << CI->getZExtValue() << 'u';
01136     else if (Ty->getPrimitiveSizeInBits() > 32)
01137       Out << CI->getZExtValue() << "ull";
01138     else {
01139       Out << "((";
01140       printSimpleType(Out, Ty, false) << ')';
01141       if (CI->isMinValue(true)) 
01142         Out << CI->getZExtValue() << 'u';
01143       else
01144         Out << CI->getSExtValue();
01145       Out << ')';
01146     }
01147     return;
01148   } 
01149 
01150   switch (CPV->getType()->getTypeID()) {
01151   case Type::FloatTyID:
01152   case Type::DoubleTyID: 
01153   case Type::X86_FP80TyID:
01154   case Type::PPC_FP128TyID:
01155   case Type::FP128TyID: {
01156     ConstantFP *FPC = cast<ConstantFP>(CPV);
01157     std::map<const ConstantFP*, unsigned>::iterator I = FPConstantMap.find(FPC);
01158     if (I != FPConstantMap.end()) {
01159       // Because of FP precision problems we must load from a stack allocated
01160       // value that holds the value in hex.
01161       Out << "(*(" << (FPC->getType() == Type::getFloatTy(CPV->getContext()) ?
01162                        "float" : 
01163                        FPC->getType() == Type::getDoubleTy(CPV->getContext()) ? 
01164                        "double" :
01165                        "long double")
01166           << "*)&FPConstant" << I->second << ')';
01167     } else {
01168       double V;
01169       if (FPC->getType() == Type::getFloatTy(CPV->getContext()))
01170         V = FPC->getValueAPF().convertToFloat();
01171       else if (FPC->getType() == Type::getDoubleTy(CPV->getContext()))
01172         V = FPC->getValueAPF().convertToDouble();
01173       else {
01174         // Long double.  Convert the number to double, discarding precision.
01175         // This is not awesome, but it at least makes the CBE output somewhat
01176         // useful.
01177         APFloat Tmp = FPC->getValueAPF();
01178         bool LosesInfo;
01179         Tmp.convert(APFloat::IEEEdouble, APFloat::rmTowardZero, &LosesInfo);
01180         V = Tmp.convertToDouble();
01181       }
01182       
01183       if (IsNAN(V)) {
01184         // The value is NaN
01185 
01186         // FIXME the actual NaN bits should be emitted.
01187         // The prefix for a quiet NaN is 0x7FF8. For a signalling NaN,
01188         // it's 0x7ff4.
01189         const unsigned long QuietNaN = 0x7ff8UL;
01190         //const unsigned long SignalNaN = 0x7ff4UL;
01191 
01192         // We need to grab the first part of the FP #
01193         char Buffer[100];
01194 
01195         uint64_t ll = DoubleToBits(V);
01196         sprintf(Buffer, "0x%llx", static_cast<long long>(ll));
01197 
01198         std::string Num(&Buffer[0], &Buffer[6]);
01199         unsigned long Val = strtoul(Num.c_str(), 0, 16);
01200 
01201         if (FPC->getType() == Type::getFloatTy(FPC->getContext()))
01202           Out << "LLVM_NAN" << (Val == QuietNaN ? "" : "S") << "F(\""
01203               << Buffer << "\") /*nan*/ ";
01204         else
01205           Out << "LLVM_NAN" << (Val == QuietNaN ? "" : "S") << "(\""
01206               << Buffer << "\") /*nan*/ ";
01207       } else if (IsInf(V)) {
01208         // The value is Inf
01209         if (V < 0) Out << '-';
01210         Out << "LLVM_INF" <<
01211             (FPC->getType() == Type::getFloatTy(FPC->getContext()) ? "F" : "")
01212             << " /*inf*/ ";
01213       } else {
01214         std::string Num;
01215 #if HAVE_PRINTF_A && ENABLE_CBE_PRINTF_A
01216         // Print out the constant as a floating point number.
01217         char Buffer[100];
01218         sprintf(Buffer, "%a", V);
01219         Num = Buffer;
01220 #else
01221         Num = ftostr(FPC->getValueAPF());
01222 #endif
01223        Out << Num;
01224       }
01225     }
01226     break;
01227   }
01228 
01229   case Type::ArrayTyID:
01230     // Use C99 compound expression literal initializer syntax.
01231     if (!Static) {
01232       Out << "(";
01233       printType(Out, CPV->getType());
01234       Out << ")";
01235     }
01236     Out << "{ "; // Arrays are wrapped in struct types.
01237     if (ConstantArray *CA = dyn_cast<ConstantArray>(CPV)) {
01238       printConstantArray(CA, Static);
01239     } else {
01240       assert(isa<ConstantAggregateZero>(CPV) || isa<UndefValue>(CPV));
01241       const ArrayType *AT = cast<ArrayType>(CPV->getType());
01242       Out << '{';
01243       if (AT->getNumElements()) {
01244         Out << ' ';
01245         Constant *CZ = Constant::getNullValue(AT->getElementType());
01246         printConstant(CZ, Static);
01247         for (unsigned i = 1, e = AT->getNumElements(); i != e; ++i) {
01248           Out << ", ";
01249           printConstant(CZ, Static);
01250         }
01251       }
01252       Out << " }";
01253     }
01254     Out << " }"; // Arrays are wrapped in struct types.
01255     break;
01256 
01257   case Type::VectorTyID:
01258     // Use C99 compound expression literal initializer syntax.
01259     if (!Static) {
01260       Out << "(";
01261       printType(Out, CPV->getType());
01262       Out << ")";
01263     }
01264     if (ConstantVector *CV = dyn_cast<ConstantVector>(CPV)) {
01265       printConstantVector(CV, Static);
01266     } else {
01267       assert(isa<ConstantAggregateZero>(CPV) || isa<UndefValue>(CPV));
01268       const VectorType *VT = cast<VectorType>(CPV->getType());
01269       Out << "{ ";
01270       Constant *CZ = Constant::getNullValue(VT->getElementType());
01271       printConstant(CZ, Static);
01272       for (unsigned i = 1, e = VT->getNumElements(); i != e; ++i) {
01273         Out << ", ";
01274         printConstant(CZ, Static);
01275       }
01276       Out << " }";
01277     }
01278     break;
01279 
01280   case Type::StructTyID:
01281     // Use C99 compound expression literal initializer syntax.
01282     if (!Static) {
01283       Out << "(";
01284       printType(Out, CPV->getType());
01285       Out << ")";
01286     }
01287     if (isa<ConstantAggregateZero>(CPV) || isa<UndefValue>(CPV)) {
01288       const StructType *ST = cast<StructType>(CPV->getType());
01289       Out << '{';
01290       if (ST->getNumElements()) {
01291         Out << ' ';
01292         printConstant(Constant::getNullValue(ST->getElementType(0)), Static);
01293         for (unsigned i = 1, e = ST->getNumElements(); i != e; ++i) {
01294           Out << ", ";
01295           printConstant(Constant::getNullValue(ST->getElementType(i)), Static);
01296         }
01297       }
01298       Out << " }";
01299     } else {
01300       Out << '{';
01301       if (CPV->getNumOperands()) {
01302         Out << ' ';
01303         printConstant(cast<Constant>(CPV->getOperand(0)), Static);
01304         for (unsigned i = 1, e = CPV->getNumOperands(); i != e; ++i) {
01305           Out << ", ";
01306           printConstant(cast<Constant>(CPV->getOperand(i)), Static);
01307         }
01308       }
01309       Out << " }";
01310     }
01311     break;
01312 
01313   case Type::PointerTyID:
01314     if (isa<ConstantPointerNull>(CPV)) {
01315       Out << "((";
01316       printType(Out, CPV->getType()); // sign doesn't matter
01317       Out << ")/*NULL*/0)";
01318       break;
01319     } else if (GlobalValue *GV = dyn_cast<GlobalValue>(CPV)) {
01320       writeOperand(GV, Static);
01321       break;
01322     }
01323     // FALL THROUGH
01324   default:
01325 #ifndef NDEBUG
01326     cerr << "Unknown constant type: " << *CPV << "\n";
01327 #endif
01328     llvm_unreachable(0);
01329   }
01330 }
01331 
01332 // Some constant expressions need to be casted back to the original types
01333 // because their operands were casted to the expected type. This function takes
01334 // care of detecting that case and printing the cast for the ConstantExpr.
01335 bool CWriter::printConstExprCast(const ConstantExpr* CE, bool Static) {
01336   bool NeedsExplicitCast = false;
01337   const Type *Ty = CE->getOperand(0)->getType();
01338   bool TypeIsSigned = false;
01339   switch (CE->getOpcode()) {
01340   case Instruction::Add:
01341   case Instruction::Sub:
01342   case Instruction::Mul:
01343     // We need to cast integer arithmetic so that it is always performed
01344     // as unsigned, to avoid undefined behavior on overflow.
01345   case Instruction::LShr:
01346   case Instruction::URem: 
01347   case Instruction::UDiv: NeedsExplicitCast = true; break;
01348   case Instruction::AShr:
01349   case Instruction::SRem: 
01350   case Instruction::SDiv: NeedsExplicitCast = true; TypeIsSigned = true; break;
01351   case Instruction::SExt:
01352     Ty = CE->getType();
01353     NeedsExplicitCast = true;
01354     TypeIsSigned = true;
01355     break;
01356   case Instruction::ZExt:
01357   case Instruction::Trunc:
01358   case Instruction::FPTrunc:
01359   case Instruction::FPExt:
01360   case Instruction::UIToFP:
01361   case Instruction::SIToFP:
01362   case Instruction::FPToUI:
01363   case Instruction::FPToSI:
01364   case Instruction::PtrToInt:
01365   case Instruction::IntToPtr:
01366   case Instruction::BitCast:
01367     Ty = CE->getType();
01368     NeedsExplicitCast = true;
01369     break;
01370   default: break;
01371   }
01372   if (NeedsExplicitCast) {
01373     Out << "((";
01374     if (Ty->isInteger() && Ty != Type::getInt1Ty(Ty->getContext()))
01375       printSimpleType(Out, Ty, TypeIsSigned);
01376     else
01377       printType(Out, Ty); // not integer, sign doesn't matter
01378     Out << ")(";
01379   }
01380   return NeedsExplicitCast;
01381 }
01382 
01383 //  Print a constant assuming that it is the operand for a given Opcode. The
01384 //  opcodes that care about sign need to cast their operands to the expected
01385 //  type before the operation proceeds. This function does the casting.
01386 void CWriter::printConstantWithCast(Constant* CPV, unsigned Opcode) {
01387 
01388   // Extract the operand's type, we'll need it.
01389   const Type* OpTy = CPV->getType();
01390 
01391   // Indicate whether to do the cast or not.
01392   bool shouldCast = false;
01393   bool typeIsSigned = false;
01394 
01395   // Based on the Opcode for which this Constant is being written, determine
01396   // the new type to which the operand should be casted by setting the value
01397   // of OpTy. If we change OpTy, also set shouldCast to true so it gets
01398   // casted below.
01399   switch (Opcode) {
01400     default:
01401       // for most instructions, it doesn't matter
01402       break; 
01403     case Instruction::Add:
01404     case Instruction::Sub:
01405     case Instruction::Mul:
01406       // We need to cast integer arithmetic so that it is always performed
01407       // as unsigned, to avoid undefined behavior on overflow.
01408     case Instruction::LShr:
01409     case Instruction::UDiv:
01410     case Instruction::URem:
01411       shouldCast = true;
01412       break;
01413     case Instruction::AShr:
01414     case Instruction::SDiv:
01415     case Instruction::SRem:
01416       shouldCast = true;
01417       typeIsSigned = true;
01418       break;
01419   }
01420 
01421   // Write out the casted constant if we should, otherwise just write the
01422   // operand.
01423   if (shouldCast) {
01424     Out << "((";
01425     printSimpleType(Out, OpTy, typeIsSigned);
01426     Out << ")";
01427     printConstant(CPV, false);
01428     Out << ")";
01429   } else 
01430     printConstant(CPV, false);
01431 }
01432 
01433 std::string CWriter::GetValueName(const Value *Operand) {
01434   // Mangle globals with the standard mangler interface for LLC compatibility.
01435   if (const GlobalValue *GV = dyn_cast<GlobalValue>(Operand))
01436     return Mang->getMangledName(GV);
01437     
01438   std::string Name = Operand->getName();
01439     
01440   if (Name.empty()) { // Assign unique names to local temporaries.
01441     unsigned &No = AnonValueNumbers[Operand];
01442     if (No == 0)
01443       No = ++NextAnonValueNumber;
01444     Name = "tmp__" + utostr(No);
01445   }
01446     
01447   std::string VarName;
01448   VarName.reserve(Name.capacity());
01449 
01450   for (std::string::iterator I = Name.begin(), E = Name.end();
01451        I != E; ++I) {
01452     char ch = *I;
01453 
01454     if (!((ch >= 'a' && ch <= 'z') || (ch >= 'A' && ch <= 'Z') ||
01455           (ch >= '0' && ch <= '9') || ch == '_')) {
01456       char buffer[5];
01457       sprintf(buffer, "_%x_", ch);
01458       VarName += buffer;
01459     } else
01460       VarName += ch;
01461   }
01462 
01463   return "llvm_cbe_" + VarName;
01464 }
01465 
01466 /// writeInstComputationInline - Emit the computation for the specified
01467 /// instruction inline, with no destination provided.
01468 void CWriter::writeInstComputationInline(Instruction &I) {
01469   // We can't currently support integer types other than 1, 8, 16, 32, 64.
01470   // Validate this.
01471   const Type *Ty = I.getType();
01472   if (Ty->isInteger() && (Ty!=Type::getInt1Ty(I.getContext()) &&
01473         Ty!=Type::getInt8Ty(I.getContext()) && 
01474         Ty!=Type::getInt16Ty(I.getContext()) &&
01475         Ty!=Type::getInt32Ty(I.getContext()) &&
01476         Ty!=Type::getInt64Ty(I.getContext()))) {
01477       llvm_report_error("The C backend does not currently support integer "
01478                         "types of widths other than 1, 8, 16, 32, 64.\n"
01479                         "This is being tracked as PR 4158.");
01480   }
01481 
01482   // If this is a non-trivial bool computation, make sure to truncate down to
01483   // a 1 bit value.  This is important because we want "add i1 x, y" to return
01484   // "0" when x and y are true, not "2" for example.
01485   bool NeedBoolTrunc = false;
01486   if (I.getType() == Type::getInt1Ty(I.getContext()) &&
01487       !isa<ICmpInst>(I) && !isa<FCmpInst>(I))
01488     NeedBoolTrunc = true;
01489   
01490   if (NeedBoolTrunc)
01491     Out << "((";
01492   
01493   visit(I);
01494   
01495   if (NeedBoolTrunc)
01496     Out << ")&1)";
01497 }
01498 
01499 
01500 void CWriter::writeOperandInternal(Value *Operand, bool Static) {
01501   if (Instruction *I = dyn_cast<Instruction>(Operand))
01502     // Should we inline this instruction to build a tree?
01503     if (isInlinableInst(*I) && !isDirectAlloca(I)) {
01504       Out << '(';
01505       writeInstComputationInline(*I);
01506       Out << ')';
01507       return;
01508     }
01509 
01510   Constant* CPV = dyn_cast<Constant>(Operand);
01511 
01512   if (CPV && !isa<GlobalValue>(CPV))
01513     printConstant(CPV, Static);
01514   else
01515     Out << GetValueName(Operand);
01516 }
01517 
01518 void CWriter::writeOperand(Value *Operand, bool Static) {
01519   bool isAddressImplicit = isAddressExposed(Operand);
01520   if (isAddressImplicit)
01521     Out << "(&";  // Global variables are referenced as their addresses by llvm
01522 
01523   writeOperandInternal(Operand, Static);
01524 
01525   if (isAddressImplicit)
01526     Out << ')';
01527 }
01528 
01529 // Some instructions need to have their result value casted back to the 
01530 // original types because their operands were casted to the expected type. 
01531 // This function takes care of detecting that case and printing the cast 
01532 // for the Instruction.
01533 bool CWriter::writeInstructionCast(const Instruction &I) {
01534   const Type *Ty = I.getOperand(0)->getType();
01535   switch (I.getOpcode()) {
01536   case Instruction::Add:
01537   case Instruction::Sub:
01538   case Instruction::Mul:
01539     // We need to cast integer arithmetic so that it is always performed
01540     // as unsigned, to avoid undefined behavior on overflow.
01541   case Instruction::LShr:
01542   case Instruction::URem: 
01543   case Instruction::UDiv: 
01544     Out << "((";
01545     printSimpleType(Out, Ty, false);
01546     Out << ")(";
01547     return true;
01548   case Instruction::AShr:
01549   case Instruction::SRem: 
01550   case Instruction::SDiv: 
01551     Out << "((";
01552     printSimpleType(Out, Ty, true);
01553     Out << ")(";
01554     return true;
01555   default: break;
01556   }
01557   return false;
01558 }
01559 
01560 // Write the operand with a cast to another type based on the Opcode being used.
01561 // This will be used in cases where an instruction has specific type
01562 // requirements (usually signedness) for its operands. 
01563 void CWriter::writeOperandWithCast(Value* Operand, unsigned Opcode) {
01564 
01565   // Extract the operand's type, we'll need it.
01566   const Type* OpTy = Operand->getType();
01567 
01568   // Indicate whether to do the cast or not.
01569   bool shouldCast = false;
01570 
01571   // Indicate whether the cast should be to a signed type or not.
01572   bool castIsSigned = false;
01573 
01574   // Based on the Opcode for which this Operand is being written, determine
01575   // the new type to which the operand should be casted by setting the value
01576   // of OpTy. If we change OpTy, also set shouldCast to true.
01577   switch (Opcode) {
01578     default:
01579       // for most instructions, it doesn't matter
01580       break; 
01581     case Instruction::Add:
01582     case Instruction::Sub:
01583     case Instruction::Mul:
01584       // We need to cast integer arithmetic so that it is always performed
01585       // as unsigned, to avoid undefined behavior on overflow.
01586     case Instruction::LShr:
01587     case Instruction::UDiv:
01588     case Instruction::URem: // Cast to unsigned first
01589       shouldCast = true;
01590       castIsSigned = false;
01591       break;
01592     case Instruction::GetElementPtr:
01593     case Instruction::AShr:
01594     case Instruction::SDiv:
01595     case Instruction::SRem: // Cast to signed first
01596       shouldCast = true;
01597       castIsSigned = true;
01598       break;
01599   }
01600 
01601   // Write out the casted operand if we should, otherwise just write the
01602   // operand.
01603   if (shouldCast) {
01604     Out << "((";
01605     printSimpleType(Out, OpTy, castIsSigned);
01606     Out << ")";
01607     writeOperand(Operand);
01608     Out << ")";
01609   } else 
01610     writeOperand(Operand);
01611 }
01612 
01613 // Write the operand with a cast to another type based on the icmp predicate 
01614 // being used. 
01615 void CWriter::writeOperandWithCast(Value* Operand, const ICmpInst &Cmp) {
01616   // This has to do a cast to ensure the operand has the right signedness. 
01617   // Also, if the operand is a pointer, we make sure to cast to an integer when
01618   // doing the comparison both for signedness and so that the C compiler doesn't
01619   // optimize things like "p < NULL" to false (p may contain an integer value
01620   // f.e.).
01621   bool shouldCast = Cmp.isRelational();
01622 
01623   // Write out the casted operand if we should, otherwise just write the
01624   // operand.
01625   if (!shouldCast) {
01626     writeOperand(Operand);
01627     return;
01628   }
01629   
01630   // Should this be a signed comparison?  If so, convert to signed.
01631   bool castIsSigned = Cmp.isSignedPredicate();
01632 
01633   // If the operand was a pointer, convert to a large integer type.
01634   const Type* OpTy = Operand->getType();
01635   if (isa<PointerType>(OpTy))
01636     OpTy = TD->getIntPtrType(Operand->getContext());
01637   
01638   Out << "((";
01639   printSimpleType(Out, OpTy, castIsSigned);
01640   Out << ")";
01641   writeOperand(Operand);
01642   Out << ")";
01643 }
01644 
01645 // generateCompilerSpecificCode - This is where we add conditional compilation
01646 // directives to cater to specific compilers as need be.
01647 //
01648 static void generateCompilerSpecificCode(formatted_raw_ostream& Out,
01649                                          const TargetData *TD) {
01650   // Alloca is hard to get, and we don't want to include stdlib.h here.
01651   Out << "/* get a declaration for alloca */\n"
01652       << "#if defined(__CYGWIN__) || defined(__MINGW32__)\n"
01653       << "#define  alloca(x) __builtin_alloca((x))\n"
01654       << "#define _alloca(x) __builtin_alloca((x))\n"
01655       << "#elif defined(__APPLE__)\n"
01656       << "extern void *__builtin_alloca(unsigned long);\n"
01657       << "#define alloca(x) __builtin_alloca(x)\n"
01658       << "#define longjmp _longjmp\n"
01659       << "#define setjmp _setjmp\n"
01660       << "#elif defined(__sun__)\n"
01661       << "#if defined(__sparcv9)\n"
01662       << "extern void *__builtin_alloca(unsigned long);\n"
01663       << "#else\n"
01664       << "extern void *__builtin_alloca(unsigned int);\n"
01665       << "#endif\n"
01666       << "#define alloca(x) __builtin_alloca(x)\n"
01667       << "#elif defined(__FreeBSD__) || defined(__NetBSD__) || defined(__OpenBSD__) || defined(__DragonFly__) || defined(__arm__)\n"
01668       << "#define alloca(x) __builtin_alloca(x)\n"
01669       << "#elif defined(_MSC_VER)\n"
01670       << "#define inline _inline\n"
01671       << "#define alloca(x) _alloca(x)\n"
01672       << "#else\n"
01673       << "#include <alloca.h>\n"
01674       << "#endif\n\n";
01675 
01676   // We output GCC specific attributes to preserve 'linkonce'ness on globals.
01677   // If we aren't being compiled with GCC, just drop these attributes.
01678   Out << "#ifndef __GNUC__  /* Can only support \"linkonce\" vars with GCC */\n"
01679       << "#define __attribute__(X)\n"
01680       << "#endif\n\n";
01681 
01682   // On Mac OS X, "external weak" is spelled "__attribute__((weak_import))".
01683   Out << "#if defined(__GNUC__) && defined(__APPLE_CC__)\n"
01684       << "#define __EXTERNAL_WEAK__ __attribute__((weak_import))\n"
01685       << "#elif defined(__GNUC__)\n"
01686       << "#define __EXTERNAL_WEAK__ __attribute__((weak))\n"
01687       << "#else\n"
01688       << "#define __EXTERNAL_WEAK__\n"
01689       << "#endif\n\n";
01690 
01691   // For now, turn off the weak linkage attribute on Mac OS X. (See above.)
01692   Out << "#if defined(__GNUC__) && defined(__APPLE_CC__)\n"
01693       << "#define __ATTRIBUTE_WEAK__\n"
01694       << "#elif defined(__GNUC__)\n"
01695       << "#define __ATTRIBUTE_WEAK__ __attribute__((weak))\n"
01696       << "#else\n"
01697       << "#define __ATTRIBUTE_WEAK__\n"
01698       << "#endif\n\n";
01699 
01700   // Add hidden visibility support. FIXME: APPLE_CC?
01701   Out << "#if defined(__GNUC__)\n"
01702       << "#define __HIDDEN__ __attribute__((visibility(\"hidden\")))\n"
01703       << "#endif\n\n";
01704     
01705   // Define NaN and Inf as GCC builtins if using GCC, as 0 otherwise
01706   // From the GCC documentation:
01707   //
01708   //   double __builtin_nan (const char *str)
01709   //
01710   // This is an implementation of the ISO C99 function nan.
01711   //
01712   // Since ISO C99 defines this function in terms of strtod, which we do
01713   // not implement, a description of the parsing is in order. The string is
01714   // parsed as by strtol; that is, the base is recognized by leading 0 or
01715   // 0x prefixes. The number parsed is placed in the significand such that
01716   // the least significant bit of the number is at the least significant
01717   // bit of the significand. The number is truncated to fit the significand
01718   // field provided. The significand is forced to be a quiet NaN.
01719   //
01720   // This function, if given a string literal, is evaluated early enough
01721   // that it is considered a compile-time constant.
01722   //
01723   //   float __builtin_nanf (const char *str)
01724   //
01725   // Similar to __builtin_nan, except the return type is float.
01726   //
01727   //   double __builtin_inf (void)
01728   //
01729   // Similar to __builtin_huge_val, except a warning is generated if the
01730   // target floating-point format does not support infinities. This
01731   // function is suitable for implementing the ISO C99 macro INFINITY.
01732   //
01733   //   float __builtin_inff (void)
01734   //
01735   // Similar to __builtin_inf, except the return type is float.
01736   Out << "#ifdef __GNUC__\n"
01737       << "#define LLVM_NAN(NanStr)   __builtin_nan(NanStr)   /* Double */\n"
01738       << "#define LLVM_NANF(NanStr)  __builtin_nanf(NanStr)  /* Float */\n"
01739       << "#define LLVM_NANS(NanStr)  __builtin_nans(NanStr)  /* Double */\n"
01740       << "#define LLVM_NANSF(NanStr) __builtin_nansf(NanStr) /* Float */\n"
01741       << "#define LLVM_INF           __builtin_inf()         /* Double */\n"
01742       << "#define LLVM_INFF          __builtin_inff()        /* Float */\n"
01743       << "#define LLVM_PREFETCH(addr,rw,locality) "
01744                               "__builtin_prefetch(addr,rw,locality)\n"
01745       << "#define __ATTRIBUTE_CTOR__ __attribute__((constructor))\n"
01746       << "#define __ATTRIBUTE_DTOR__ __attribute__((destructor))\n"
01747       << "#define LLVM_ASM           __asm__\n"
01748       << "#else\n"
01749       << "#define LLVM_NAN(NanStr)   ((double)0.0)           /* Double */\n"
01750       << "#define LLVM_NANF(NanStr)  0.0F                    /* Float */\n"
01751       << "#define LLVM_NANS(NanStr)  ((double)0.0)           /* Double */\n"
01752       << "#define LLVM_NANSF(NanStr) 0.0F                    /* Float */\n"
01753       << "#define LLVM_INF           ((double)0.0)           /* Double */\n"
01754       << "#define LLVM_INFF          0.0F                    /* Float */\n"
01755       << "#define LLVM_PREFETCH(addr,rw,locality)            /* PREFETCH */\n"
01756       << "#define __ATTRIBUTE_CTOR__\n"
01757       << "#define __ATTRIBUTE_DTOR__\n"
01758       << "#define LLVM_ASM(X)\n"
01759       << "#endif\n\n";
01760   
01761   Out << "#if __GNUC__ < 4 /* Old GCC's, or compilers not GCC */ \n"
01762       << "#define __builtin_stack_save() 0   /* not implemented */\n"
01763       << "#define __builtin_stack_restore(X) /* noop */\n"
01764       << "#endif\n\n";
01765 
01766   // Output typedefs for 128-bit integers. If these are needed with a
01767   // 32-bit target or with a C compiler that doesn't support mode(TI),
01768   // more drastic measures will be needed.
01769   Out << "#if __GNUC__ && __LP64__ /* 128-bit integer types */\n"
01770       << "typedef int __attribute__((mode(TI))) llvmInt128;\n"
01771       << "typedef unsigned __attribute__((mode(TI))) llvmUInt128;\n"
01772       << "#endif\n\n";
01773 
01774   // Output target-specific code that should be inserted into main.
01775   Out << "#define CODE_FOR_MAIN() /* Any target-specific code for main()*/\n";
01776 }
01777 
01778 /// FindStaticTors - Given a static ctor/dtor list, unpack its contents into
01779 /// the StaticTors set.
01780 static void FindStaticTors(GlobalVariable *GV, std::set<Function*> &StaticTors){
01781   ConstantArray *InitList = dyn_cast<ConstantArray>(GV->getInitializer());
01782   if (!InitList) return;
01783   
01784   for (unsigned i = 0, e = InitList->getNumOperands(); i != e; ++i)
01785     if (ConstantStruct *CS = dyn_cast<ConstantStruct>(InitList->getOperand(i))){
01786       if (CS->getNumOperands() != 2) return;  // Not array of 2-element structs.
01787       
01788       if (CS->getOperand(1)->isNullValue())
01789         return;  // Found a null terminator, exit printing.
01790       Constant *FP = CS->getOperand(1);
01791       if (ConstantExpr *CE = dyn_cast<ConstantExpr>(FP))
01792         if (CE->isCast())
01793           FP = CE->getOperand(0);
01794       if (Function *F = dyn_cast<Function>(FP))
01795         StaticTors.insert(F);
01796     }
01797 }
01798 
01799 enum SpecialGlobalClass {
01800   NotSpecial = 0,
01801   GlobalCtors, GlobalDtors,
01802   NotPrinted
01803 };
01804 
01805 /// getGlobalVariableClass - If this is a global that is specially recognized
01806 /// by LLVM, return a code that indicates how we should handle it.
01807 static SpecialGlobalClass getGlobalVariableClass(const GlobalVariable *GV) {
01808   // If this is a global ctors/dtors list, handle it now.
01809   if (GV->hasAppendingLinkage() && GV->use_empty()) {
01810     if (GV->getName() == "llvm.global_ctors")
01811       return GlobalCtors;
01812     else if (GV->getName() == "llvm.global_dtors")
01813       return GlobalDtors;
01814   }
01815   
01816   // Otherwise, it it is other metadata, don't print it.  This catches things
01817   // like debug information.
01818   if (GV->getSection() == "llvm.metadata")
01819     return NotPrinted;
01820   
01821   return NotSpecial;
01822 }
01823 
01824 // PrintEscapedString - Print each character of the specified string, escaping
01825 // it if it is not printable or if it is an escape char.
01826 static void PrintEscapedString(const char *Str, unsigned Length,
01827                                raw_ostream &Out) {
01828   for (unsigned i = 0; i != Length; ++i) {
01829     unsigned char C = Str[i];
01830     if (isprint(C) && C != '\\' && C != '"')
01831       Out << C;
01832     else if (C == '\\')
01833       Out << "\\\\";
01834     else if (C == '\"')
01835       Out << "\\\"";
01836     else if (C == '\t')
01837       Out << "\\t";
01838     else
01839       Out << "\\x" << hexdigit(C >> 4) << hexdigit(C & 0x0F);
01840   }
01841 }
01842 
01843 // PrintEscapedString - Print each character of the specified string, escaping
01844 // it if it is not printable or if it is an escape char.
01845 static void PrintEscapedString(const std::string &Str, raw_ostream &Out) {
01846   PrintEscapedString(Str.c_str(), Str.size(), Out);
01847 }
01848 
01849 bool CWriter::doInitialization(Module &M) {
01850   FunctionPass::doInitialization(M);
01851   
01852   // Initialize
01853   TheModule = &M;
01854 
01855   TD = new TargetData(&M);
01856   IL = new IntrinsicLowering(*TD);
01857   IL->AddPrototypes(M);
01858 
01859   // Ensure that all structure types have names...
01860   Mang = new Mangler(M);
01861   Mang->markCharUnacceptable('.');
01862 
01863   // Keep track of which functions are static ctors/dtors so they can have
01864   // an attribute added to their prototypes.
01865   std::set<Function*> StaticCtors, StaticDtors;
01866   for (Module::global_iterator I = M.global_begin(), E = M.global_end();
01867        I != E; ++I) {
01868     switch (getGlobalVariableClass(I)) {
01869     default: break;
01870     case GlobalCtors:
01871       FindStaticTors(I, StaticCtors);
01872       break;
01873     case GlobalDtors:
01874       FindStaticTors(I, StaticDtors);
01875       break;
01876     }
01877   }
01878   
01879   // get declaration for alloca
01880   Out << "/* Provide Declarations */\n";
01881   Out << "#include <stdarg.h>\n";      // Varargs support
01882   Out << "#include <setjmp.h>\n";      // Unwind support
01883   generateCompilerSpecificCode(Out, TD);
01884 
01885   // Provide a definition for `bool' if not compiling with a C++ compiler.
01886   Out << "\n"
01887       << "#ifndef __cplusplus\ntypedef unsigned char bool;\n#endif\n"
01888 
01889       << "\n\n/* Support for floating point constants */\n"
01890       << "typedef unsigned long long ConstantDoubleTy;\n"
01891       << "typedef unsigned int        ConstantFloatTy;\n"
01892       << "typedef struct { unsigned long long f1; unsigned short f2; "
01893          "unsigned short pad[3]; } ConstantFP80Ty;\n"
01894       // This is used for both kinds of 128-bit long double; meaning differs.
01895       << "typedef struct { unsigned long long f1; unsigned long long f2; }"
01896          " ConstantFP128Ty;\n"
01897       << "\n\n/* Global Declarations */\n";
01898 
01899   // First output all the declarations for the program, because C requires
01900   // Functions & globals to be declared before they are used.
01901   //
01902   if (!M.getModuleInlineAsm().empty()) {
01903     Out << "/* Module asm statements */\n"
01904         << "asm(";
01905 
01906     // Split the string into lines, to make it easier to read the .ll file.
01907     std::string Asm = M.getModuleInlineAsm();
01908     size_t CurPos = 0;
01909     size_t NewLine = Asm.find_first_of('\n', CurPos);
01910     while (NewLine != std::string::npos) {
01911       // We found a newline, print the portion of the asm string from the
01912       // last newline up to this newline.
01913       Out << "\"";
01914       PrintEscapedString(std::string(Asm.begin()+CurPos, Asm.begin()+NewLine),
01915                          Out);
01916       Out << "\\n\"\n";
01917       CurPos = NewLine+1;
01918       NewLine = Asm.find_first_of('\n', CurPos);
01919     }
01920     Out << "\"";
01921     PrintEscapedString(std::string(Asm.begin()+CurPos, Asm.end()), Out);
01922     Out << "\");\n"
01923         << "/* End Module asm statements */\n";
01924   }
01925 
01926   // Loop over the symbol table, emitting all named constants...
01927   printModuleTypes(M.getTypeSymbolTable());
01928 
01929   // Global variable declarations...
01930   if (!M.global_empty()) {
01931     Out << "\n/* External Global Variable Declarations */\n";
01932     for (Module::global_iterator I = M.global_begin(), E = M.global_end();
01933          I != E; ++I) {
01934 
01935       if (I->hasExternalLinkage() || I->hasExternalWeakLinkage() || 
01936           I->hasCommonLinkage())
01937         Out << "extern ";
01938       else if (I->hasDLLImportLinkage())
01939         Out << "__declspec(dllimport) ";
01940       else
01941         continue; // Internal Global
01942 
01943       // Thread Local Storage
01944       if (I->isThreadLocal())
01945         Out << "__thread ";
01946 
01947       printType(Out, I->getType()->getElementType(), false, GetValueName(I));
01948 
01949       if (I->hasExternalWeakLinkage())
01950          Out << " __EXTERNAL_WEAK__";
01951       Out << ";\n";
01952     }
01953   }
01954 
01955   // Function declarations
01956   Out << "\n/* Function Declarations */\n";
01957   Out << "double fmod(double, double);\n";   // Support for FP rem
01958   Out << "float fmodf(float, float);\n";
01959   Out << "long double fmodl(long double, long double);\n";
01960   
01961   for (Module::iterator I = M.begin(), E = M.end(); I != E; ++I) {
01962     // Don't print declarations for intrinsic functions.
01963     if (!I->isIntrinsic() && I->getName() != "setjmp" &&
01964         I->getName() != "longjmp" && I->getName() != "_setjmp") {
01965       if (I->hasExternalWeakLinkage())
01966         Out << "extern ";
01967       printFunctionSignature(I, true);
01968       if (I->hasWeakLinkage() || I->hasLinkOnceLinkage()) 
01969         Out << " __ATTRIBUTE_WEAK__";
01970       if (I->hasExternalWeakLinkage())
01971         Out << " __EXTERNAL_WEAK__";
01972       if (StaticCtors.count(I))
01973         Out << " __ATTRIBUTE_CTOR__";
01974       if (StaticDtors.count(I))
01975         Out << " __ATTRIBUTE_DTOR__";
01976       if (I->hasHiddenVisibility())
01977         Out << " __HIDDEN__";
01978       
01979       if (I->hasName() && I->getName()[0] == 1)
01980         Out << " LLVM_ASM(\"" << I->getName().substr(1) << "\")";
01981           
01982       Out << ";\n";
01983     }
01984   }
01985 
01986   // Output the global variable declarations
01987   if (!M.global_empty()) {
01988     Out << "\n\n/* Global Variable Declarations */\n";
01989     for (Module::global_iterator I = M.global_begin(), E = M.global_end();
01990          I != E; ++I)
01991       if (!I->isDeclaration()) {
01992         // Ignore special globals, such as debug info.
01993         if (getGlobalVariableClass(I))
01994           continue;
01995 
01996         if (I->hasLocalLinkage())
01997           Out << "static ";
01998         else
01999           Out << "extern ";
02000 
02001         // Thread Local Storage
02002         if (I->isThreadLocal())
02003           Out << "__thread ";
02004 
02005         printType(Out, I->getType()->getElementType(), false, 
02006                   GetValueName(I));
02007 
02008         if (I->hasLinkOnceLinkage())
02009           Out << " __attribute__((common))";
02010         else if (I->hasCommonLinkage())     // FIXME is this right?
02011           Out << " __ATTRIBUTE_WEAK__";
02012         else if (I->hasWeakLinkage())
02013           Out << " __ATTRIBUTE_WEAK__";
02014         else if (I->hasExternalWeakLinkage())
02015           Out << " __EXTERNAL_WEAK__";
02016         if (I->hasHiddenVisibility())
02017           Out << " __HIDDEN__";
02018         Out << ";\n";
02019       }
02020   }
02021 
02022   // Output the global variable definitions and contents...
02023   if (!M.global_empty()) {
02024     Out << "\n\n/* Global Variable Definitions and Initialization */\n";
02025     for (Module::global_iterator I = M.global_begin(), E = M.global_end(); 
02026          I != E; ++I)
02027       if (!I->isDeclaration()) {
02028         // Ignore special globals, such as debug info.
02029         if (getGlobalVariableClass(I))
02030           continue;
02031 
02032         if (I->hasLocalLinkage())
02033           Out << "static ";
02034         else if (I->hasDLLImportLinkage())
02035           Out << "__declspec(dllimport) ";
02036         else if (I->hasDLLExportLinkage())
02037           Out << "__declspec(dllexport) ";
02038 
02039         // Thread Local Storage
02040         if (I->isThreadLocal())
02041           Out << "__thread ";
02042 
02043         printType(Out, I->getType()->getElementType(), false, 
02044                   GetValueName(I));
02045         if (I->hasLinkOnceLinkage())
02046           Out << " __attribute__((common))";
02047         else if (I->hasWeakLinkage())
02048           Out << " __ATTRIBUTE_WEAK__";
02049         else if (I->hasCommonLinkage())
02050           Out << " __ATTRIBUTE_WEAK__";
02051 
02052         if (I->hasHiddenVisibility())
02053           Out << " __HIDDEN__";
02054         
02055         // If the initializer is not null, emit the initializer.  If it is null,
02056         // we try to avoid emitting large amounts of zeros.  The problem with
02057         // this, however, occurs when the variable has weak linkage.  In this
02058         // case, the assembler will complain about the variable being both weak
02059         // and common, so we disable this optimization.
02060         // FIXME common linkage should avoid this problem.
02061         if (!I->getInitializer()->isNullValue()) {
02062           Out << " = " ;
02063           writeOperand(I->getInitializer(), true);
02064         } else if (I->hasWeakLinkage()) {
02065           // We have to specify an initializer, but it doesn't have to be
02066           // complete.  If the value is an aggregate, print out { 0 }, and let
02067           // the compiler figure out the rest of the zeros.
02068           Out << " = " ;
02069           if (isa<StructType>(I->getInitializer()->getType()) ||
02070               isa<VectorType>(I->getInitializer()->getType())) {
02071             Out << "{ 0 }";
02072           } else if (isa<ArrayType>(I->getInitializer()->getType())) {
02073             // As with structs and vectors, but with an extra set of braces
02074             // because arrays are wrapped in structs.
02075             Out << "{ { 0 } }";
02076           } else {
02077             // Just print it out normally.
02078             writeOperand(I->getInitializer(), true);
02079           }
02080         }
02081         Out << ";\n";
02082       }
02083   }
02084 
02085   if (!M.empty())
02086     Out << "\n\n/* Function Bodies */\n";
02087 
02088   // Emit some helper functions for dealing with FCMP instruction's 
02089   // predicates
02090   Out << "static inline int llvm_fcmp_ord(double X, double Y) { ";
02091   Out << "return X == X && Y == Y; }\n";
02092   Out << "static inline int llvm_fcmp_uno(double X, double Y) { ";
02093   Out << "return X != X || Y != Y; }\n";
02094   Out << "static inline int llvm_fcmp_ueq(double X, double Y) { ";
02095   Out << "return X == Y || llvm_fcmp_uno(X, Y); }\n";
02096   Out << "static inline int llvm_fcmp_une(double X, double Y) { ";
02097   Out << "return X != Y; }\n";
02098   Out << "static inline int llvm_fcmp_ult(double X, double Y) { ";
02099   Out << "return X <  Y || llvm_fcmp_uno(X, Y); }\n";
02100   Out << "static inline int llvm_fcmp_ugt(double X, double Y) { ";
02101   Out << "return X >  Y || llvm_fcmp_uno(X, Y); }\n";
02102   Out << "static inline int llvm_fcmp_ule(double X, double Y) { ";
02103   Out << "return X <= Y || llvm_fcmp_uno(X, Y); }\n";
02104   Out << "static inline int llvm_fcmp_uge(double X, double Y) { ";
02105   Out << "return X >= Y || llvm_fcmp_uno(X, Y); }\n";
02106   Out << "static inline int llvm_fcmp_oeq(double X, double Y) { ";
02107   Out << "return X == Y ; }\n";
02108   Out << "static inline int llvm_fcmp_one(double X, double Y) { ";
02109   Out << "return X != Y && llvm_fcmp_ord(X, Y); }\n";
02110   Out << "static inline int llvm_fcmp_olt(double X, double Y) { ";
02111   Out << "return X <  Y ; }\n";
02112   Out << "static inline int llvm_fcmp_ogt(double X, double Y) { ";
02113   Out << "return X >  Y ; }\n";
02114   Out << "static inline int llvm_fcmp_ole(double X, double Y) { ";
02115   Out << "return X <= Y ; }\n";
02116   Out << "static inline int llvm_fcmp_oge(double X, double Y) { ";
02117   Out << "return X >= Y ; }\n";
02118   return false;
02119 }
02120 
02121 
02122 /// Output all floating point constants that cannot be printed accurately...
02123 void CWriter::printFloatingPointConstants(Function &F) {
02124   // Scan the module for floating point constants.  If any FP constant is used
02125   // in the function, we want to redirect it here so that we do not depend on
02126   // the precision of the printed form, unless the printed form preserves
02127   // precision.
02128   //
02129   for (constant_iterator I = constant_begin(&F), E = constant_end(&F);
02130        I != E; ++I)
02131     printFloatingPointConstants(*I);
02132 
02133   Out << '\n';
02134 }
02135 
02136 void CWriter::printFloatingPointConstants(const Constant *C) {
02137   // If this is a constant expression, recursively check for constant fp values.
02138   if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
02139     for (unsigned i = 0, e = CE->getNumOperands(); i != e; ++i)
02140       printFloatingPointConstants(CE->getOperand(i));
02141     return;
02142   }
02143     
02144   // Otherwise, check for a FP constant that we need to print.
02145   const ConstantFP *FPC = dyn_cast<ConstantFP>(C);
02146   if (FPC == 0 ||
02147       // Do not put in FPConstantMap if safe.
02148       isFPCSafeToPrint(FPC) ||
02149       // Already printed this constant?
02150       FPConstantMap.count(FPC))
02151     return;
02152 
02153   FPConstantMap[FPC] = FPCounter;  // Number the FP constants
02154   
02155   if (FPC->getType() == Type::getDoubleTy(FPC->getContext())) {
02156     double Val = FPC->getValueAPF().convertToDouble();
02157     uint64_t i = FPC->getValueAPF().bitcastToAPInt().getZExtValue();
02158     Out << "static const ConstantDoubleTy FPConstant" << FPCounter++
02159     << " = 0x" << utohexstr(i)
02160     << "ULL;    /* " << Val << " */\n";
02161   } else if (FPC->getType() == Type::getFloatTy(FPC->getContext())) {
02162     float Val = FPC->getValueAPF().convertToFloat();
02163     uint32_t i = (uint32_t)FPC->getValueAPF().bitcastToAPInt().
02164     getZExtValue();
02165     Out << "static const ConstantFloatTy FPConstant" << FPCounter++
02166     << " = 0x" << utohexstr(i)
02167     << "U;    /* " << Val << " */\n";
02168   } else if (FPC->getType() == Type::getX86_FP80Ty(FPC->getContext())) {
02169     // api needed to prevent premature destruction
02170     APInt api = FPC->getValueAPF().bitcastToAPInt();
02171     const uint64_t *p = api.getRawData();
02172     Out << "static const ConstantFP80Ty FPConstant" << FPCounter++
02173     << " = { 0x" << utohexstr(p[0]) 
02174     << "ULL, 0x" << utohexstr((uint16_t)p[1]) << ",{0,0,0}"
02175     << "}; /* Long double constant */\n";
02176   } else if (FPC->getType() == Type::getPPC_FP128Ty(FPC->getContext())) {
02177     APInt api = FPC->getValueAPF().bitcastToAPInt();
02178     const uint64_t *p = api.getRawData();
02179     Out << "static const ConstantFP128Ty FPConstant" << FPCounter++
02180     << " = { 0x"
02181     << utohexstr(p[0]) << ", 0x" << utohexstr(p[1])
02182     << "}; /* Long double constant */\n";
02183     
02184   } else {
02185     llvm_unreachable("Unknown float type!");
02186   }
02187 }
02188 
02189 
02190 
02191 /// printSymbolTable - Run through symbol table looking for type names.  If a
02192 /// type name is found, emit its declaration...
02193 ///
02194 void CWriter::printModuleTypes(const TypeSymbolTable &TST) {
02195   Out << "/* Helper union for bitcasts */\n";
02196   Out << "typedef union {\n";
02197   Out << "  unsigned int Int32;\n";
02198   Out << "  unsigned long long Int64;\n";
02199   Out << "  float Float;\n";
02200   Out << "  double Double;\n";
02201   Out << "} llvmBitCastUnion;\n";
02202 
02203   // We are only interested in the type plane of the symbol table.
02204   TypeSymbolTable::const_iterator I   = TST.begin();
02205   TypeSymbolTable::const_iterator End = TST.end();
02206 
02207   // If there are no type names, exit early.
02208   if (I == End) return;
02209 
02210   // Print out forward declarations for structure types before anything else!
02211   Out << "/* Structure forward decls */\n";
02212   for (; I != End; ++I) {
02213     std::string Name = "struct l_" + Mang->makeNameProper(I->first);
02214     Out << Name << ";\n";
02215     TypeNames.insert(std::make_pair(I->second, Name));
02216   }
02217 
02218   Out << '\n';
02219 
02220   // Now we can print out typedefs.  Above, we guaranteed that this can only be
02221   // for struct or opaque types.
02222   Out << "/* Typedefs */\n";
02223   for (I = TST.begin(); I != End; ++I) {
02224     std::string Name = "l_" + Mang->makeNameProper(I->first);
02225     Out << "typedef ";
02226     printType(Out, I->second, false, Name);
02227     Out << ";\n";
02228   }
02229 
02230   Out << '\n';
02231 
02232   // Keep track of which structures have been printed so far...
02233   std::set<const Type *> StructPrinted;
02234 
02235   // Loop over all structures then push them into the stack so they are
02236   // printed in the correct order.
02237   //
02238   Out << "/* Structure contents */\n";
02239   for (I = TST.begin(); I != End; ++I)
02240     if (isa<StructType>(I->second) || isa<ArrayType>(I->second))
02241       // Only print out used types!
02242       printContainedStructs(I->second, StructPrinted);
02243 }
02244 
02245 // Push the struct onto the stack and recursively push all structs
02246 // this one depends on.
02247 //
02248 // TODO:  Make this work properly with vector types
02249 //
02250 void CWriter::printContainedStructs(const Type *Ty,
02251                                     std::set<const Type*> &StructPrinted) {
02252   // Don't walk through pointers.
02253   if (isa<PointerType>(Ty) || Ty->isPrimitiveType() || Ty->isInteger()) return;
02254   
02255   // Print all contained types first.
02256   for (Type::subtype_iterator I = Ty->subtype_begin(),
02257        E = Ty->subtype_end(); I != E; ++I)
02258     printContainedStructs(*I, StructPrinted);
02259   
02260   if (isa<StructType>(Ty) || isa<ArrayType>(Ty)) {
02261     // Check to see if we have already printed this struct.
02262     if (StructPrinted.insert(Ty).second) {
02263       // Print structure type out.
02264       std::string Name = TypeNames[Ty];
02265       printType(Out, Ty, false, Name, true);
02266       Out << ";\n\n";
02267     }
02268   }
02269 }
02270 
02271 void CWriter::printFunctionSignature(const Function *F, bool Prototype) {
02272   /// isStructReturn - Should this function actually return a struct by-value?
02273   bool isStructReturn = F->hasStructRetAttr();
02274   
02275   if (F->hasLocalLinkage()) Out << "static ";
02276   if (F->hasDLLImportLinkage()) Out << "__declspec(dllimport) ";
02277   if (F->hasDLLExportLinkage()) Out << "__declspec(dllexport) ";  
02278   switch (F->getCallingConv()) {
02279    case CallingConv::X86_StdCall:
02280     Out << "__attribute__((stdcall)) ";
02281     break;
02282    case CallingConv::X86_FastCall:
02283     Out << "__attribute__((fastcall)) ";
02284     break;
02285   }
02286   
02287   // Loop over the arguments, printing them...
02288   const FunctionType *FT = cast<FunctionType>(F->getFunctionType());
02289   const AttrListPtr &PAL = F->getAttributes();
02290 
02291   std::stringstream FunctionInnards;
02292 
02293   // Print out the name...
02294   FunctionInnards << GetValueName(F) << '(';
02295 
02296   bool PrintedArg = false;
02297   if (!F->isDeclaration()) {
02298     if (!F->arg_empty()) {
02299       Function::const_arg_iterator I = F->arg_begin(), E = F->arg_end();
02300       unsigned Idx = 1;
02301       
02302       // If this is a struct-return function, don't print the hidden
02303       // struct-return argument.
02304       if (isStructReturn) {
02305         assert(I != E && "Invalid struct return function!");
02306         ++I;
02307         ++Idx;
02308       }
02309       
02310       std::string ArgName;
02311       for (; I != E; ++I) {
02312         if (PrintedArg) FunctionInnards << ", ";
02313         if (I->hasName() || !Prototype)
02314           ArgName = GetValueName(I);
02315         else
02316           ArgName = "";
02317         const Type *ArgTy = I->getType();
02318         if (PAL.paramHasAttr(Idx, Attribute::ByVal)) {
02319           ArgTy = cast<PointerType>(ArgTy)->getElementType();
02320           ByValParams.insert(I);
02321         }
02322         printType(FunctionInnards, ArgTy,
02323             /*isSigned=*/PAL.paramHasAttr(Idx, Attribute::SExt),
02324             ArgName);
02325         PrintedArg = true;
02326         ++Idx;
02327       }
02328     }
02329   } else {
02330     // Loop over the arguments, printing them.
02331     FunctionType::param_iterator I = FT->param_begin(), E = FT->param_end();
02332     unsigned Idx = 1;
02333     
02334     // If this is a struct-return function, don't print the hidden
02335     // struct-return argument.
02336     if (isStructReturn) {
02337       assert(I != E && "Invalid struct return function!");
02338       ++I;
02339       ++Idx;
02340     }
02341     
02342     for (; I != E; ++I) {
02343       if (PrintedArg) FunctionInnards << ", ";
02344       const Type *ArgTy = *I;
02345       if (PAL.paramHasAttr(Idx, Attribute::ByVal)) {
02346         assert(isa<PointerType>(ArgTy));
02347         ArgTy = cast<PointerType>(ArgTy)->getElementType();
02348       }
02349       printType(FunctionInnards, ArgTy,
02350              /*isSigned=*/PAL.paramHasAttr(Idx, Attribute::SExt));
02351       PrintedArg = true;
02352       ++Idx;
02353     }
02354   }
02355 
02356   // Finish printing arguments... if this is a vararg function, print the ...,
02357   // unless there are no known types, in which case, we just emit ().
02358   //
02359   if (FT->isVarArg() && PrintedArg) {
02360     if (PrintedArg) FunctionInnards << ", ";
02361     FunctionInnards << "...";  // Output varargs portion of signature!
02362   } else if (!FT->isVarArg() && !PrintedArg) {
02363     FunctionInnards << "void"; // ret() -> ret(void) in C.
02364   }
02365   FunctionInnards << ')';
02366   
02367   // Get the return tpe for the function.
02368   const Type *RetTy;
02369   if (!isStructReturn)
02370     RetTy = F->getReturnType();
02371   else {
02372     // If this is a struct-return function, print the struct-return type.
02373     RetTy = cast<PointerType>(FT->getParamType(0))->getElementType();
02374   }
02375     
02376   // Print out the return type and the signature built above.
02377   printType(Out, RetTy, 
02378             /*isSigned=*/PAL.paramHasAttr(0, Attribute::SExt),
02379             FunctionInnards.str());
02380 }
02381 
02382 static inline bool isFPIntBitCast(const Instruction &I) {
02383   if (!isa<BitCastInst>(I))
02384     return false;
02385   const Type *SrcTy = I.getOperand(0)->getType();
02386   const Type *DstTy = I.getType();
02387   return (SrcTy->isFloatingPoint() && DstTy->isInteger()) ||
02388          (DstTy->isFloatingPoint() && SrcTy->isInteger());
02389 }
02390 
02391 void CWriter::printFunction(Function &F) {
02392   /// isStructReturn - Should this function actually return a struct by-value?
02393   bool isStructReturn = F.hasStructRetAttr();
02394 
02395   printFunctionSignature(&F, false);
02396   Out << " {\n";
02397   
02398   // If this is a struct return function, handle the result with magic.
02399   if (isStructReturn) {
02400     const Type *StructTy =
02401       cast<PointerType>(F.arg_begin()->getType())->getElementType();
02402     Out << "  ";
02403     printType(Out, StructTy, false, "StructReturn");
02404     Out << ";  /* Struct return temporary */\n";
02405 
02406     Out << "  ";
02407     printType(Out, F.arg_begin()->getType(), false, 
02408               GetValueName(F.arg_begin()));
02409     Out << " = &StructReturn;\n";
02410   }
02411 
02412   bool PrintedVar = false;
02413   
02414   // print local variable information for the function
02415   for (inst_iterator I = inst_begin(&F), E = inst_end(&F); I != E; ++I) {
02416     if (const AllocaInst *AI = isDirectAlloca(&*I)) {
02417       Out << "  ";
02418       printType(Out, AI->getAllocatedType(), false, GetValueName(AI));
02419       Out << ";    /* Address-exposed local */\n";
02420       PrintedVar = true;
02421     } else if (I->getType() != Type::getVoidTy(F.getContext()) && 
02422                !isInlinableInst(*I)) {
02423       Out << "  ";
02424       printType(Out, I->getType(), false, GetValueName(&*I));
02425       Out << ";\n";
02426 
02427       if (isa<PHINode>(*I)) {  // Print out PHI node temporaries as well...
02428         Out << "  ";
02429         printType(Out, I->getType(), false,
02430                   GetValueName(&*I)+"__PHI_TEMPORARY");
02431         Out << ";\n";
02432       }
02433       PrintedVar = true;
02434     }
02435     // We need a temporary for the BitCast to use so it can pluck a value out
02436     // of a union to do the BitCast. This is separate from the need for a
02437     // variable to hold the result of the BitCast. 
02438     if (isFPIntBitCast(*I)) {
02439       Out << "  llvmBitCastUnion " << GetValueName(&*I)
02440           << "__BITCAST_TEMPORARY;\n";
02441       PrintedVar = true;
02442     }
02443   }
02444 
02445   if (PrintedVar)
02446     Out << '\n';
02447 
02448   if (F.hasExternalLinkage() && F.getName() == "main")
02449     Out << "  CODE_FOR_MAIN();\n";
02450 
02451   // print the basic blocks
02452   for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB) {
02453     if (Loop *L = LI->getLoopFor(BB)) {
02454       if (L->getHeader() == BB && L->getParentLoop() == 0)
02455         printLoop(L);
02456     } else {
02457       printBasicBlock(BB);
02458     }
02459   }
02460 
02461   Out << "}\n\n";
02462 }
02463 
02464 void CWriter::printLoop(Loop *L) {
02465   Out << "  do {     /* Syntactic loop '" << L->getHeader()->getName()
02466       << "' to make GCC happy */\n";
02467   for (unsigned i = 0, e = L->getBlocks().size(); i != e; ++i) {
02468     BasicBlock *BB = L->getBlocks()[i];
02469     Loop *BBLoop = LI->getLoopFor(BB);
02470     if (BBLoop == L)
02471       printBasicBlock(BB);
02472     else if (BB == BBLoop->getHeader() && BBLoop->getParentLoop() == L)
02473       printLoop(BBLoop);
02474   }
02475   Out << "  } while (1); /* end of syntactic loop '"
02476       << L->getHeader()->getName() << "' */\n";
02477 }
02478 
02479 void CWriter::printBasicBlock(BasicBlock *BB) {
02480 
02481   // Don't print the label for the basic block if there are no uses, or if
02482   // the only terminator use is the predecessor basic block's terminator.
02483   // We have to scan the use list because PHI nodes use basic blocks too but
02484   // do not require a label to be generated.
02485   //
02486   bool NeedsLabel = false;
02487   for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI)
02488     if (isGotoCodeNecessary(*PI, BB)) {
02489       NeedsLabel = true;
02490       break;
02491     }
02492 
02493   if (NeedsLabel) Out << GetValueName(BB) << ":\n";
02494 
02495   // Output all of the instructions in the basic block...
02496   for (BasicBlock::iterator II = BB->begin(), E = --BB->end(); II != E;
02497        ++II) {
02498     if (!isInlinableInst(*II) && !isDirectAlloca(II)) {
02499       if (II->getType() != Type::getVoidTy(BB->getContext()) &&
02500           !isInlineAsm(*II))
02501         outputLValue(II);
02502       else
02503         Out << "  ";
02504       writeInstComputationInline(*II);
02505       Out << ";\n";
02506     }
02507   }
02508 
02509   // Don't emit prefix or suffix for the terminator.
02510   visit(*BB->getTerminator());
02511 }
02512 
02513 
02514 // Specific Instruction type classes... note that all of the casts are
02515 // necessary because we use the instruction classes as opaque types...
02516 //
02517 void CWriter::visitReturnInst(ReturnInst &I) {
02518   // If this is a struct return function, return the temporary struct.
02519   bool isStructReturn = I.getParent()->getParent()->hasStructRetAttr();
02520 
02521   if (isStructReturn) {
02522     Out << "  return StructReturn;\n";
02523     return;
02524   }
02525   
02526   // Don't output a void return if this is the last basic block in the function
02527   if (I.getNumOperands() == 0 &&
02528       &*--I.getParent()->getParent()->end() == I.getParent() &&
02529       !I.getParent()->size() == 1) {
02530     return;
02531   }
02532 
02533   if (I.getNumOperands() > 1) {
02534     Out << "  {\n";
02535     Out << "    ";
02536     printType(Out, I.getParent()->getParent()->getReturnType());
02537     Out << "   llvm_cbe_mrv_temp = {\n";
02538     for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i) {
02539       Out << "      ";
02540       writeOperand(I.getOperand(i));
02541       if (i != e - 1)
02542         Out << ",";
02543       Out << "\n";
02544     }
02545     Out << "    };\n";
02546     Out << "    return llvm_cbe_mrv_temp;\n";
02547     Out << "  }\n";
02548     return;
02549   }
02550 
02551   Out << "  return";
02552   if (I.getNumOperands()) {
02553     Out << ' ';
02554     writeOperand(I.getOperand(0));
02555   }
02556   Out << ";\n";
02557 }
02558 
02559 void CWriter::visitSwitchInst(SwitchInst &SI) {
02560 
02561   Out << "  switch (";
02562   writeOperand(SI.getOperand(0));
02563   Out << ") {\n  default:\n";
02564   printPHICopiesForSuccessor (SI.getParent(), SI.getDefaultDest(), 2);
02565   printBranchToBlock(SI.getParent(), SI.getDefaultDest(), 2);
02566   Out << ";\n";
02567   for (unsigned i = 2, e = SI.getNumOperands(); i != e; i += 2) {
02568     Out << "  case ";
02569     writeOperand(SI.getOperand(i));
02570     Out << ":\n";
02571     BasicBlock *Succ = cast<BasicBlock>(SI.getOperand(i+1));
02572     printPHICopiesForSuccessor (SI.getParent(), Succ, 2);
02573     printBranchToBlock(SI.getParent(), Succ, 2);
02574     if (Function::iterator(Succ) == next(Function::iterator(SI.getParent())))
02575       Out << "    break;\n";
02576   }
02577   Out << "  }\n";
02578 }
02579 
02580 void CWriter::visitUnreachableInst(UnreachableInst &I) {
02581   Out << "  /*UNREACHABLE*/;\n";
02582 }
02583 
02584 bool CWriter::isGotoCodeNecessary(BasicBlock *From, BasicBlock *To) {
02585   /// FIXME: This should be reenabled, but loop reordering safe!!
02586   return true;
02587 
02588   if (next(Function::iterator(From)) != Function::iterator(To))
02589     return true;  // Not the direct successor, we need a goto.
02590 
02591   //isa<SwitchInst>(From->getTerminator())
02592 
02593   if (LI->getLoopFor(From) != LI->getLoopFor(To))
02594     return true;
02595   return false;
02596 }
02597 
02598 void CWriter::printPHICopiesForSuccessor (BasicBlock *CurBlock,
02599                                           BasicBlock *Successor,
02600                                           unsigned Indent) {
02601   for (BasicBlock::iterator I = Successor->begin(); isa<PHINode>(I); ++I) {
02602     PHINode *PN = cast<PHINode>(I);
02603     // Now we have to do the printing.
02604     Value *IV = PN->getIncomingValueForBlock(CurBlock);
02605     if (!isa<UndefValue>(IV)) {
02606       Out << std::string(Indent, ' ');
02607       Out << "  " << GetValueName(I) << "__PHI_TEMPORARY = ";
02608       writeOperand(IV);
02609       Out << ";   /* for PHI node */\n";
02610     }
02611   }
02612 }
02613 
02614 void CWriter::printBranchToBlock(BasicBlock *CurBB, BasicBlock *Succ,
02615                                  unsigned Indent) {
02616   if (isGotoCodeNecessary(CurBB, Succ)) {
02617     Out << std::string(Indent, ' ') << "  goto ";
02618     writeOperand(Succ);
02619     Out << ";\n";
02620   }
02621 }
02622 
02623 // Branch instruction printing - Avoid printing out a branch to a basic block
02624 // that immediately succeeds the current one.
02625 //
02626 void CWriter::visitBranchInst(BranchInst &I) {
02627 
02628   if (I.isConditional()) {
02629     if (isGotoCodeNecessary(I.getParent(), I.getSuccessor(0))) {
02630       Out << "  if (";
02631       writeOperand(I.getCondition());
02632       Out << ") {\n";
02633 
02634       printPHICopiesForSuccessor (I.getParent(), I.getSuccessor(0), 2);
02635       printBranchToBlock(I.getParent(), I.getSuccessor(0), 2);
02636 
02637       if (isGotoCodeNecessary(I.getParent(), I.getSuccessor(1))) {
02638         Out << "  } else {\n";
02639         printPHICopiesForSuccessor (I.getParent(), I.getSuccessor(1), 2);
02640         printBranchToBlock(I.getParent(), I.getSuccessor(1), 2);
02641       }
02642     } else {
02643       // First goto not necessary, assume second one is...
02644       Out << "  if (!";
02645       writeOperand(I.getCondition());
02646       Out << ") {\n";
02647 
02648       printPHICopiesForSuccessor (I.getParent(), I.getSuccessor(1), 2);
02649       printBranchToBlock(I.getParent(), I.getSuccessor(1), 2);
02650     }
02651 
02652     Out << "  }\n";
02653   } else {
02654     printPHICopiesForSuccessor (I.getParent(), I.getSuccessor(0), 0);
02655     printBranchToBlock(I.getParent(), I.getSuccessor(0), 0);
02656   }
02657   Out << "\n";
02658 }
02659 
02660 // PHI nodes get copied into temporary values at the end of predecessor basic
02661 // blocks.  We now need to copy these temporary values into the REAL value for
02662 // the PHI.
02663 void CWriter::visitPHINode(PHINode &I) {
02664   writeOperand(&I);
02665   Out << "__PHI_TEMPORARY";
02666 }
02667 
02668 
02669 void CWriter::visitBinaryOperator(Instruction &I) {
02670   // binary instructions, shift instructions, setCond instructions.
02671   assert(!isa<PointerType>(I.getType()));
02672 
02673   // We must cast the results of binary operations which might be promoted.
02674   bool needsCast = false;
02675   if ((I.getType() == Type::getInt8Ty(I.getContext())) ||
02676       (I.getType() == Type::getInt16Ty(I.getContext())) 
02677       || (I.getType() == Type::getFloatTy(I.getContext()))) {
02678     needsCast = true;
02679     Out << "((";
02680     printType(Out, I.getType(), false);
02681     Out << ")(";
02682   }
02683 
02684   // If this is a negation operation, print it out as such.  For FP, we don't
02685   // want to print "-0.0 - X".
02686   if (BinaryOperator::isNeg(&I)) {
02687     Out << "-(";
02688     writeOperand(BinaryOperator::getNegArgument(cast<BinaryOperator>(&I)));
02689     Out << ")";
02690   } else if (BinaryOperator::isFNeg(&I)) {
02691     Out << "-(";
02692     writeOperand(BinaryOperator::getFNegArgument(cast<BinaryOperator>(&I)));
02693     Out << ")";
02694   } else if (I.getOpcode() == Instruction::FRem) {
02695     // Output a call to fmod/fmodf instead of emitting a%b
02696     if (I.getType() == Type::getFloatTy(I.getContext()))
02697       Out << "fmodf(";
02698     else if (I.getType() == Type::getDoubleTy(I.getContext()))
02699       Out << "fmod(";
02700     else  // all 3 flavors of long double
02701       Out << "fmodl(";
02702     writeOperand(I.getOperand(0));
02703     Out << ", ";
02704     writeOperand(I.getOperand(1));
02705     Out << ")";
02706   } else {
02707 
02708     // Write out the cast of the instruction's value back to the proper type
02709     // if necessary.
02710     bool NeedsClosingParens = writeInstructionCast(I);
02711 
02712     // Certain instructions require the operand to be forced to a specific type
02713     // so we use writeOperandWithCast here instead of writeOperand. Similarly
02714     // below for operand 1
02715     writeOperandWithCast(I.getOperand(0), I.getOpcode());
02716 
02717     switch (I.getOpcode()) {
02718     case Instruction::Add:
02719     case Instruction::FAdd: Out << " + "; break;
02720     case Instruction::Sub:
02721     case Instruction::FSub: Out << " - "; break;
02722     case Instruction::Mul:
02723     case Instruction::FMul: Out << " * "; break;
02724     case Instruction::URem:
02725     case Instruction::SRem:
02726     case Instruction::FRem: Out << " % "; break;
02727     case Instruction::UDiv:
02728     case Instruction::SDiv: 
02729     case Instruction::FDiv: Out << " / "; break;
02730     case Instruction::And:  Out << " & "; break;
02731     case Instruction::Or:   Out << " | "; break;
02732     case Instruction::Xor:  Out << " ^ "; break;
02733     case Instruction::Shl : Out << " << "; break;
02734     case Instruction::LShr:
02735     case Instruction::AShr: Out << " >> "; break;
02736     default: 
02737 #ifndef NDEBUG
02738        cerr << "Invalid operator type!" << I;
02739 #endif
02740        llvm_unreachable(0);
02741     }
02742 
02743     writeOperandWithCast(I.getOperand(1), I.getOpcode());
02744     if (NeedsClosingParens)
02745       Out << "))";
02746   }
02747 
02748   if (needsCast) {
02749     Out << "))";
02750   }
02751 }
02752 
02753 void CWriter::visitICmpInst(ICmpInst &I) {
02754   // We must cast the results of icmp which might be promoted.
02755   bool needsCast = false;
02756 
02757   // Write out the cast of the instruction's value back to the proper type
02758   // if necessary.
02759   bool NeedsClosingParens = writeInstructionCast(I);
02760 
02761   // Certain icmp predicate require the operand to be forced to a specific type
02762   // so we use writeOperandWithCast here instead of writeOperand. Similarly
02763   // below for operand 1
02764   writeOperandWithCast(I.getOperand(0), I);
02765 
02766   switch (I.getPredicate()) {
02767   case ICmpInst::ICMP_EQ:  Out << " == "; break;
02768   case ICmpInst::ICMP_NE:  Out << " != "; break;
02769   case ICmpInst::ICMP_ULE:
02770   case ICmpInst::ICMP_SLE: Out << " <= "; break;
02771   case ICmpInst::ICMP_UGE:
02772   case ICmpInst::ICMP_SGE: Out << " >= "; break;
02773   case ICmpInst::ICMP_ULT:
02774   case ICmpInst::ICMP_SLT: Out << " < "; break;
02775   case ICmpInst::ICMP_UGT:
02776   case ICmpInst::ICMP_SGT: Out << " > "; break;
02777   default:
02778 #ifndef NDEBUG
02779     cerr << "Invalid icmp predicate!" << I; 
02780 #endif
02781     llvm_unreachable(0);
02782   }
02783 
02784   writeOperandWithCast(I.getOperand(1), I);
02785   if (NeedsClosingParens)
02786     Out << "))";
02787 
02788   if (needsCast) {
02789     Out << "))";
02790   }
02791 }
02792 
02793 void CWriter::visitFCmpInst(FCmpInst &I) {
02794   if (I.getPredicate() == FCmpInst::FCMP_FALSE) {
02795     Out << "0";
02796     return;
02797   }
02798   if (I.getPredicate() == FCmpInst::FCMP_TRUE) {
02799     Out << "1";
02800     return;
02801   }
02802 
02803   const char* op = 0;
02804   switch (I.getPredicate()) {
02805   default: llvm_unreachable("Illegal FCmp predicate");
02806   case FCmpInst::FCMP_ORD: op = "ord"; break;
02807   case FCmpInst::FCMP_UNO: op = "uno"; break;
02808   case FCmpInst::FCMP_UEQ: op = "ueq"; break;
02809   case FCmpInst::FCMP_UNE: op = "une"; break;
02810   case FCmpInst::FCMP_ULT: op = "ult"; break;
02811   case FCmpInst::FCMP_ULE: op = "ule"; break;
02812   case FCmpInst::FCMP_UGT: op = "ugt"; break;
02813   case FCmpInst::FCMP_UGE: op = "uge"; break;
02814   case FCmpInst::FCMP_OEQ: op = "oeq"; break;
02815   case FCmpInst::FCMP_ONE: op = "one"; break;
02816   case FCmpInst::FCMP_OLT: op = "olt"; break;
02817   case FCmpInst::FCMP_OLE: op = "ole"; break;
02818   case FCmpInst::FCMP_OGT: op = "ogt"; break;
02819   case FCmpInst::FCMP_OGE: op = "oge"; break;
02820   }
02821 
02822   Out << "llvm_fcmp_" << op << "(";
02823   // Write the first operand
02824   writeOperand(I.getOperand(0));
02825   Out << ", ";
02826   // Write the second operand
02827   writeOperand(I.getOperand(1));
02828   Out << ")";
02829 }
02830 
02831 static const char * getFloatBitCastField(const Type *Ty) {
02832   switch (Ty->getTypeID()) {
02833     default: llvm_unreachable("Invalid Type");
02834     case Type::FloatTyID:  return "Float";
02835     case Type::DoubleTyID: return "Double";
02836     case Type::IntegerTyID: {
02837       unsigned NumBits = cast<IntegerType>(Ty)->getBitWidth();
02838       if (NumBits <= 32)
02839         return "Int32";
02840       else
02841         return "Int64";
02842     }
02843   }
02844 }
02845 
02846 void CWriter::visitCastInst(CastInst &I) {
02847   const Type *DstTy = I.getType();
02848   const Type *SrcTy = I.getOperand(0)->getType();
02849   if (isFPIntBitCast(I)) {
02850     Out << '(';
02851     // These int<->float and long<->double casts need to be handled specially
02852     Out << GetValueName(&I) << "__BITCAST_TEMPORARY." 
02853         << getFloatBitCastField(I.getOperand(0)->getType()) << " = ";
02854     writeOperand(I.getOperand(0));
02855     Out << ", " << GetValueName(&I) << "__BITCAST_TEMPORARY."
02856         << getFloatBitCastField(I.getType());
02857     Out << ')';
02858     return;
02859   }
02860   
02861   Out << '(';
02862   printCast(I.getOpcode(), SrcTy, DstTy);
02863 
02864   // Make a sext from i1 work by subtracting the i1 from 0 (an int).
02865   if (SrcTy == Type::getInt1Ty(I.getContext()) &&
02866       I.getOpcode() == Instruction::SExt)
02867     Out << "0-";
02868   
02869   writeOperand(I.getOperand(0));
02870     
02871   if (DstTy == Type::getInt1Ty(I.getContext()) && 
02872       (I.getOpcode() == Instruction::Trunc ||
02873        I.getOpcode() == Instruction::FPToUI ||
02874        I.getOpcode() == Instruction::FPToSI ||
02875        I.getOpcode() == Instruction::PtrToInt)) {
02876     // Make sure we really get a trunc to bool by anding the operand with 1 
02877     Out << "&1u";
02878   }
02879   Out << ')';
02880 }
02881 
02882 void CWriter::visitSelectInst(SelectInst &I) {
02883   Out << "((";
02884   writeOperand(I.getCondition());
02885   Out << ") ? (";
02886   writeOperand(I.getTrueValue());
02887   Out << ") : (";
02888   writeOperand(I.getFalseValue());
02889   Out << "))";
02890 }
02891 
02892 
02893 void CWriter::lowerIntrinsics(Function &F) {
02894   // This is used to keep track of intrinsics that get generated to a lowered
02895   // function. We must generate the prototypes before the function body which
02896   // will only be expanded on first use (by the loop below).
02897   std::vector<Function*> prototypesToGen;
02898 
02899   // Examine all the instructions in this function to find the intrinsics that
02900   // need to be lowered.
02901   for (Function::iterator BB = F.begin(), EE = F.end(); BB != EE; ++BB)
02902     for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; )
02903       if (CallInst *CI = dyn_cast<CallInst>(I++))
02904         if (Function *F = CI->getCalledFunction())
02905           switch (F->getIntrinsicID()) {
02906           case Intrinsic::not_intrinsic:
02907           case Intrinsic::memory_barrier:
02908           case Intrinsic::vastart:
02909           case Intrinsic::vacopy:
02910           case Intrinsic::vaend:
02911           case Intrinsic::returnaddress:
02912           case Intrinsic::frameaddress:
02913           case Intrinsic::setjmp:
02914           case Intrinsic::longjmp:
02915           case Intrinsic::prefetch:
02916           case Intrinsic::dbg_stoppoint:
02917           case Intrinsic::powi:
02918           case Intrinsic::x86_sse_cmp_ss:
02919           case Intrinsic::x86_sse_cmp_ps:
02920           case Intrinsic::x86_sse2_cmp_sd:
02921           case Intrinsic::x86_sse2_cmp_pd:
02922           case Intrinsic::ppc_altivec_lvsl:
02923               // We directly implement these intrinsics
02924             break;
02925           default:
02926             // If this is an intrinsic that directly corresponds to a GCC
02927             // builtin, we handle it.
02928             const char *BuiltinName = "";
02929 #define GET_GCC_BUILTIN_NAME
02930 #include "llvm/Intrinsics.gen"
02931 #undef GET_GCC_BUILTIN_NAME
02932             // If we handle it, don't lower it.
02933             if (BuiltinName[0]) break;
02934             
02935             // All other intrinsic calls we must lower.
02936             Instruction *Before = 0;
02937             if (CI != &BB->front())
02938               Before = prior(BasicBlock::iterator(CI));
02939 
02940             IL->LowerIntrinsicCall(CI);
02941             if (Before) {        // Move iterator to instruction after call
02942               I = Before; ++I;
02943             } else {
02944               I = BB->begin();
02945             }
02946             // If the intrinsic got lowered to another call, and that call has
02947             // a definition then we need to make sure its prototype is emitted
02948             // before any calls to it.
02949             if (CallInst *Call = dyn_cast<CallInst>(I))
02950               if (Function *NewF = Call->getCalledFunction())
02951                 if (!NewF->isDeclaration())
02952                   prototypesToGen.push_back(NewF);
02953 
02954             break;
02955           }
02956 
02957   // We may have collected some prototypes to emit in the loop above. 
02958   // Emit them now, before the function that uses them is emitted. But,
02959   // be careful not to emit them twice.
02960   std::vector<Function*>::iterator I = prototypesToGen.begin();
02961   std::vector<Function*>::iterator E = prototypesToGen.end();
02962   for ( ; I != E; ++I) {
02963     if (intrinsicPrototypesAlreadyGenerated.insert(*I).second) {
02964       Out << '\n';
02965       printFunctionSignature(*I, true);
02966       Out << ";\n";
02967     }
02968   }
02969 }
02970 
02971 void CWriter::visitCallInst(CallInst &I) {
02972   if (isa<InlineAsm>(I.getOperand(0)))
02973     return visitInlineAsm(I);
02974 
02975   bool WroteCallee = false;
02976 
02977   // Handle intrinsic function calls first...
02978   if (Function *F = I.getCalledFunction())
02979     if (Intrinsic::ID ID = (Intrinsic::ID)F->getIntrinsicID())
02980       if (visitBuiltinCall(I, ID, WroteCallee))
02981         return;
02982 
02983   Value *Callee = I.getCalledValue();
02984 
02985   const PointerType  *PTy   = cast<PointerType>(Callee->getType());
02986   const FunctionType *FTy   = cast<FunctionType>(PTy->getElementType());
02987 
02988   // If this is a call to a struct-return function, assign to the first
02989   // parameter instead of passing it to the call.
02990   const AttrListPtr &PAL = I.getAttributes();
02991   bool hasByVal = I.hasByValArgument();
02992   bool isStructRet = I.hasStructRetAttr();
02993   if (isStructRet) {
02994     writeOperandDeref(I.getOperand(1));
02995     Out << " = ";
02996   }
02997   
02998   if (I.isTailCall()) Out << " /*tail*/ ";
02999   
03000   if (!WroteCallee) {
03001     // If this is an indirect call to a struct return function, we need to cast
03002     // the pointer. Ditto for indirect calls with byval arguments.
03003     bool NeedsCast = (hasByVal || isStructRet) && !isa<Function>(Callee);
03004 
03005     // GCC is a real PITA.  It does not permit codegening casts of functions to
03006     // function pointers if they are in a call (it generates a trap instruction
03007     // instead!).  We work around this by inserting a cast to void* in between
03008     // the function and the function pointer cast.  Unfortunately, we can't just
03009     // form the constant expression here, because the folder will immediately
03010     // nuke it.
03011     //
03012     // Note finally, that this is completely unsafe.  ANSI C does not guarantee
03013     // that void* and function pointers have the same size. :( To deal with this
03014     // in the common case, we handle casts where the number of arguments passed
03015     // match exactly.
03016     //
03017     if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Callee))
03018       if (CE->isCast())
03019         if (Function *RF = dyn_cast<Function>(CE->getOperand(0))) {
03020           NeedsCast = true;
03021           Callee = RF;
03022         }
03023   
03024     if (NeedsCast) {
03025       // Ok, just cast the pointer type.
03026       Out << "((";
03027       if (isStructRet)
03028         printStructReturnPointerFunctionType(Out, PAL,
03029                              cast<PointerType>(I.getCalledValue()->getType()));
03030       else if (hasByVal)
03031         printType(Out, I.getCalledValue()->getType(), false, "", true, PAL);
03032       else
03033         printType(Out, I.getCalledValue()->getType());
03034       Out << ")(void*)";
03035     }
03036     writeOperand(Callee);
03037     if (NeedsCast) Out << ')';
03038   }
03039 
03040   Out << '(';
03041 
03042   unsigned NumDeclaredParams = FTy->getNumParams();
03043 
03044   CallSite::arg_iterator AI = I.op_begin()+1, AE = I.op_end();
03045   unsigned ArgNo = 0;
03046   if (isStructRet) {   // Skip struct return argument.
03047     ++AI;
03048     ++ArgNo;
03049   }
03050       
03051   bool PrintedArg = false;
03052   for (; AI != AE; ++AI, ++ArgNo) {
03053     if (PrintedArg) Out << ", ";
03054     if (ArgNo < NumDeclaredParams &&
03055         (*AI)->getType() != FTy->getParamType(ArgNo)) {
03056       Out << '(';
03057       printType(Out, FTy->getParamType(ArgNo), 
03058             /*isSigned=*/PAL.paramHasAttr(ArgNo+1, Attribute::SExt));
03059       Out << ')';
03060     }
03061     // Check if the argument is expected to be passed by value.
03062     if (I.paramHasAttr(ArgNo+1, Attribute::ByVal))
03063       writeOperandDeref(*AI);
03064     else
03065       writeOperand(*AI);
03066     PrintedArg = true;
03067   }
03068   Out << ')';
03069 }
03070 
03071 /// visitBuiltinCall - Handle the call to the specified builtin.  Returns true
03072 /// if the entire call is handled, return false it it wasn't handled, and
03073 /// optionally set 'WroteCallee' if the callee has already been printed out.
03074 bool CWriter::visitBuiltinCall(CallInst &I, Intrinsic::ID ID,
03075                                bool &WroteCallee) {
03076   switch (ID) {
03077   default: {
03078     // If this is an intrinsic that directly corresponds to a GCC
03079     // builtin, we emit it here.
03080     const char *BuiltinName = "";
03081     Function *F = I.getCalledFunction();
03082 #define GET_GCC_BUILTIN_NAME
03083 #include "llvm/Intrinsics.gen"
03084 #undef GET_GCC_BUILTIN_NAME
03085     assert(BuiltinName[0] && "Unknown LLVM intrinsic!");
03086     
03087     Out << BuiltinName;
03088     WroteCallee = true;
03089     return false;
03090   }
03091   case Intrinsic::memory_barrier:
03092     Out << "__sync_synchronize()";
03093     return true;
03094   case Intrinsic::vastart:
03095     Out << "0; ";
03096       
03097     Out << "va_start(*(va_list*)";
03098     writeOperand(I.getOperand(1));
03099     Out << ", ";
03100     // Output the last argument to the enclosing function.
03101     if (I.getParent()->getParent()->arg_empty()) {
03102       std::string msg;
03103       raw_string_ostream Msg(msg);
03104       Msg << "The C backend does not currently support zero "
03105            << "argument varargs functions, such as '"
03106            << I.getParent()->getParent()->getName() << "'!";
03107       llvm_report_error(Msg.str());
03108     }
03109     writeOperand(--I.getParent()->getParent()->arg_end());
03110     Out << ')';
03111     return true;
03112   case Intrinsic::vaend:
03113     if (!isa<ConstantPointerNull>(I.getOperand(1))) {
03114       Out << "0; va_end(*(va_list*)";
03115       writeOperand(I.getOperand(1));
03116       Out << ')';
03117     } else {
03118       Out << "va_end(*(va_list*)0)";
03119     }
03120     return true;
03121   case Intrinsic::vacopy:
03122     Out << "0; ";
03123     Out << "va_copy(*(va_list*)";
03124     writeOperand(I.getOperand(1));
03125     Out << ", *(va_list*)";
03126     writeOperand(I.getOperand(2));
03127     Out << ')';
03128     return true;
03129   case Intrinsic::returnaddress:
03130     Out << "__builtin_return_address(";
03131     writeOperand(I.getOperand(1));
03132     Out << ')';
03133     return true;
03134   case Intrinsic::frameaddress:
03135     Out << "__builtin_frame_address(";
03136     writeOperand(I.getOperand(1));
03137     Out << ')';
03138     return true;
03139   case Intrinsic::powi:
03140     Out << "__builtin_powi(";
03141     writeOperand(I.getOperand(1));
03142     Out << ", ";
03143     writeOperand(I.getOperand(2));
03144     Out << ')';
03145     return true;
03146   case Intrinsic::setjmp:
03147     Out << "setjmp(*(jmp_buf*)";
03148     writeOperand(I.getOperand(1));
03149     Out << ')';
03150     return true;
03151   case Intrinsic::longjmp:
03152     Out << "longjmp(*(jmp_buf*)";
03153     writeOperand(I.getOperand(1));
03154     Out << ", ";
03155     writeOperand(I.getOperand(2));
03156     Out << ')';
03157     return true;
03158   case Intrinsic::prefetch:
03159     Out << "LLVM_PREFETCH((const void *)";
03160     writeOperand(I.getOperand(1));
03161     Out << ", ";
03162     writeOperand(I.getOperand(2));
03163     Out << ", ";
03164     writeOperand(I.getOperand(3));
03165     Out << ")";
03166     return true;
03167   case Intrinsic::stacksave:
03168     // Emit this as: Val = 0; *((void**)&Val) = __builtin_stack_save()
03169     // to work around GCC bugs (see PR1809).
03170     Out << "0; *((void**)&" << GetValueName(&I)
03171         << ") = __builtin_stack_save()";
03172     return true;
03173   case Intrinsic::dbg_stoppoint: {
03174     // If we use writeOperand directly we get a "u" suffix which is rejected
03175     // by gcc.
03176     DbgStopPointInst &SPI = cast<DbgStopPointInst>(I);
03177     std::string dir;
03178     GetConstantStringInfo(SPI.getDirectory(), dir);
03179     std::string file;
03180     GetConstantStringInfo(SPI.getFileName(), file);
03181     Out << "\n#line "
03182         << SPI.getLine()
03183         << " \""
03184         << dir << '/' << file << "\"\n";
03185     return true;
03186   }
03187   case Intrinsic::x86_sse_cmp_ss:
03188   case Intrinsic::x86_sse_cmp_ps:
03189   case Intrinsic::x86_sse2_cmp_sd:
03190   case Intrinsic::x86_sse2_cmp_pd:
03191     Out << '(';
03192     printType(Out, I.getType());
03193     Out << ')';  
03194     // Multiple GCC builtins multiplex onto this intrinsic.
03195     switch (cast<ConstantInt>(I.getOperand(3))->getZExtValue()) {
03196     default: llvm_unreachable("Invalid llvm.x86.sse.cmp!");
03197     case 0: Out << "__builtin_ia32_cmpeq"; break;
03198     case 1: Out << "__builtin_ia32_cmplt"; break;
03199     case 2: Out << "__builtin_ia32_cmple"; break;
03200     case 3: Out << "__builtin_ia32_cmpunord"; break;
03201     case 4: Out << "__builtin_ia32_cmpneq"; break;
03202     case 5: Out << "__builtin_ia32_cmpnlt"; break;
03203     case 6: Out << "__builtin_ia32_cmpnle"; break;
03204     case 7: Out << "__builtin_ia32_cmpord"; break;
03205     }
03206     if (ID == Intrinsic::x86_sse_cmp_ps || ID == Intrinsic::x86_sse2_cmp_pd)
03207       Out << 'p';
03208     else
03209       Out << 's';
03210     if (ID == Intrinsic::x86_sse_cmp_ss || ID == Intrinsic::x86_sse_cmp_ps)
03211       Out << 's';
03212     else
03213       Out << 'd';
03214       
03215     Out << "(";
03216     writeOperand(I.getOperand(1));
03217     Out << ", ";
03218     writeOperand(I.getOperand(2));
03219     Out << ")";
03220     return true;
03221   case Intrinsic::ppc_altivec_lvsl:
03222     Out << '(';
03223     printType(Out, I.getType());
03224     Out << ')';  
03225     Out << "__builtin_altivec_lvsl(0, (void*)";
03226     writeOperand(I.getOperand(1));
03227     Out << ")";
03228     return true;
03229   }
03230 }
03231 
03232 //This converts the llvm constraint string to something gcc is expecting.
03233 //TODO: work out platform independent constraints and factor those out
03234 //      of the per target tables
03235 //      handle multiple constraint codes
03236 std::string CWriter::InterpretASMConstraint(InlineAsm::ConstraintInfo& c) {
03237 
03238   assert(c.Codes.size() == 1 && "Too many asm constraint codes to handle");
03239 
03240   const char *const *table = 0;
03241   
03242   // Grab the translation table from TargetAsmInfo if it exists.
03243   if (!TAsm) {
03244     std::string Triple = TheModule->getTargetTriple();
03245     if (Triple.empty())
03246       Triple = llvm::sys::getHostTriple();
03247 
03248     std::string E;
03249     if (const Target *Match = TargetRegistry::lookupTarget(Triple, E))
03250       TAsm = Match->createAsmInfo(Triple);
03251   }
03252   if (TAsm)
03253     table = TAsm->getAsmCBE();
03254 
03255   // Search the translation table if it exists.
03256   for (int i = 0; table && table[i]; i += 2)
03257     if (c.Codes[0] == table[i])
03258       return table[i+1];
03259 
03260   // Default is identity.
03261   return c.Codes[0];
03262 }
03263 
03264 //TODO: import logic from AsmPrinter.cpp
03265 static std::string gccifyAsm(std::string asmstr) {
03266   for (std::string::size_type i = 0; i != asmstr.size(); ++i)
03267     if (asmstr[i] == '\n')
03268       asmstr.replace(i, 1, "\\n");
03269     else if (asmstr[i] == '\t')
03270       asmstr.replace(i, 1, "\\t");
03271     else if (asmstr[i] == '$') {
03272       if (asmstr[i + 1] == '{') {
03273         std::string::size_type a = asmstr.find_first_of(':', i + 1);
03274         std::string::size_type b = asmstr.find_first_of('}', i + 1);
03275         std::string n = "%" + 
03276           asmstr.substr(a + 1, b - a - 1) +
03277           asmstr.substr(i + 2, a - i - 2);
03278         asmstr.replace(i, b - i + 1, n);
03279         i += n.size() - 1;
03280       } else
03281         asmstr.replace(i, 1, "%");
03282     }
03283     else if (asmstr[i] == '%')//grr
03284       { asmstr.replace(i, 1, "%%"); ++i;}
03285   
03286   return asmstr;
03287 }
03288 
03289 //TODO: assumptions about what consume arguments from the call are likely wrong
03290 //      handle communitivity
03291 void CWriter::visitInlineAsm(CallInst &CI) {
03292   InlineAsm* as = cast<InlineAsm>(CI.getOperand(0));
03293   std::vector<InlineAsm::ConstraintInfo> Constraints = as->ParseConstraints();
03294   
03295   std::vector<std::pair<Value*, int> > ResultVals;
03296   if (CI.getType() == Type::getVoidTy(CI.getContext()))
03297     ;
03298   else if (const StructType *ST = dyn_cast<StructType>(CI.getType())) {
03299     for (unsigned i = 0, e = ST->getNumElements(); i != e; ++i)
03300       ResultVals.push_back(std::make_pair(&CI, (int)i));
03301   } else {
03302     ResultVals.push_back(std::make_pair(&CI, -1));
03303   }
03304   
03305   // Fix up the asm string for gcc and emit it.
03306   Out << "__asm__ volatile (\"" << gccifyAsm(as->getAsmString()) << "\"\n";
03307   Out << "        :";
03308 
03309   unsigned ValueCount = 0;
03310   bool IsFirst = true;
03311   
03312   // Convert over all the output constraints.
03313   for (std::vector<InlineAsm::ConstraintInfo>::iterator I = Constraints.begin(),
03314        E = Constraints.end(); I != E; ++I) {
03315     
03316     if (I->Type != InlineAsm::isOutput) {
03317       ++ValueCount;
03318       continue;  // Ignore non-output constraints.
03319     }
03320     
03321     assert(I->Codes.size() == 1 && "Too many asm constraint codes to handle");
03322     std::string C = InterpretASMConstraint(*I);
03323     if (C.empty()) continue;
03324     
03325     if (!IsFirst) {
03326       Out << ", ";
03327       IsFirst = false;
03328     }
03329 
03330     // Unpack the dest.
03331     Value *DestVal;
03332     int DestValNo = -1;
03333     
03334     if (ValueCount < ResultVals.size()) {
03335       DestVal = ResultVals[ValueCount].first;
03336       DestValNo = ResultVals[ValueCount].second;
03337     } else
03338       DestVal = CI.getOperand(ValueCount-ResultVals.size()+1);
03339 
03340     if (I->isEarlyClobber)
03341       C = "&"+C;
03342       
03343     Out << "\"=" << C << "\"(" << GetValueName(DestVal);
03344     if (DestValNo != -1)
03345       Out << ".field" << DestValNo; // Multiple retvals.
03346     Out << ")";
03347     ++ValueCount;
03348   }
03349   
03350   
03351   // Convert over all the input constraints.
03352   Out << "\n        :";
03353   IsFirst = true;
03354   ValueCount = 0;
03355   for (std::vector<InlineAsm::ConstraintInfo>::iterator I = Constraints.begin(),
03356        E = Constraints.end(); I != E; ++I) {
03357     if (I->Type != InlineAsm::isInput) {
03358       ++ValueCount;
03359       continue;  // Ignore non-input constraints.
03360     }
03361     
03362     assert(I->Codes.size() == 1 && "Too many asm constraint codes to handle");
03363     std::string C = InterpretASMConstraint(*I);
03364     if (C.empty()) continue;
03365     
03366     if (!IsFirst) {
03367       Out << ", ";
03368       IsFirst = false;
03369     }
03370     
03371     assert(ValueCount >= ResultVals.size() && "Input can't refer to result");
03372     Value *SrcVal = CI.getOperand(ValueCount-ResultVals.size()+1);
03373     
03374     Out << "\"" << C << "\"(";
03375     if (!I->isIndirect)
03376       writeOperand(SrcVal);
03377     else
03378       writeOperandDeref(SrcVal);
03379     Out << ")";
03380   }
03381   
03382   // Convert over the clobber constraints.
03383   IsFirst = true;
03384   ValueCount = 0;
03385   for (std::vector<InlineAsm::ConstraintInfo>::iterator I = Constraints.begin(),
03386        E = Constraints.end(); I != E; ++I) {
03387     if (I->Type != InlineAsm::isClobber)
03388       continue;  // Ignore non-input constraints.
03389 
03390     assert(I->Codes.size() == 1 && "Too many asm constraint codes to handle");
03391     std::string C = InterpretASMConstraint(*I);
03392     if (C.empty()) continue;
03393     
03394     if (!IsFirst) {
03395       Out << ", ";
03396       IsFirst = false;
03397     }
03398     
03399     Out << '\"' << C << '"';
03400   }
03401   
03402   Out << ")";
03403 }
03404 
03405 void CWriter::visitMallocInst(MallocInst &I) {
03406   llvm_unreachable("lowerallocations pass didn't work!");
03407 }
03408 
03409 void CWriter::visitAllocaInst(AllocaInst &I) {
03410   Out << '(';
03411   printType(Out, I.getType());
03412   Out << ") alloca(sizeof(";
03413   printType(Out, I.getType()->getElementType());
03414   Out << ')';
03415   if (I.isArrayAllocation()) {
03416     Out << " * " ;
03417     writeOperand(I.getOperand(0));
03418   }
03419   Out << ')';
03420 }
03421 
03422 void CWriter::visitFreeInst(FreeInst &I) {
03423   llvm_unreachable("lowerallocations pass didn't work!");
03424 }
03425 
03426 void CWriter::printGEPExpression(Value *Ptr, gep_type_iterator I,
03427                                  gep_type_iterator E, bool Static) {
03428   
03429   // If there are no indices, just print out the pointer.
03430   if (I == E) {
03431     writeOperand(Ptr);
03432     return;
03433   }
03434     
03435   // Find out if the last index is into a vector.  If so, we have to print this
03436   // specially.  Since vectors can't have elements of indexable type, only the
03437   // last index could possibly be of a vector element.
03438   const VectorType *LastIndexIsVector = 0;
03439   {
03440     for (gep_type_iterator TmpI = I; TmpI != E; ++TmpI)
03441       LastIndexIsVector = dyn_cast<VectorType>(*TmpI);
03442   }
03443   
03444   Out << "(";
03445   
03446   // If the last index is into a vector, we can't print it as &a[i][j] because
03447   // we can't index into a vector with j in GCC.  Instead, emit this as
03448   // (((float*)&a[i])+j)
03449   if (LastIndexIsVector) {
03450     Out << "((";
03451     printType(Out, PointerType::getUnqual(LastIndexIsVector->getElementType()));
03452     Out << ")(";
03453   }
03454   
03455   Out << '&';
03456 
03457   // If the first index is 0 (very typical) we can do a number of
03458   // simplifications to clean up the code.
03459   Value *FirstOp = I.getOperand();
03460   if (!isa<Constant>(FirstOp) || !cast<Constant>(FirstOp)->isNullValue()) {
03461     // First index isn't simple, print it the hard way.
03462     writeOperand(Ptr);
03463   } else {
03464     ++I;  // Skip the zero index.
03465 
03466     // Okay, emit the first operand. If Ptr is something that is already address
03467     // exposed, like a global, avoid emitting (&foo)[0], just emit foo instead.
03468     if (isAddressExposed(Ptr)) {
03469       writeOperandInternal(Ptr, Static);
03470     } else if (I != E && isa<StructType>(*I)) {
03471       // If we didn't already emit the first operand, see if we can print it as
03472       // P->f instead of "P[0].f"
03473       writeOperand(Ptr);
03474       Out << "->field" << cast<ConstantInt>(I.getOperand())->getZExtValue();
03475       ++I;  // eat the struct index as well.
03476     } else {
03477       // Instead of emitting P[0][1], emit (*P)[1], which is more idiomatic.
03478       Out << "(*";
03479       writeOperand(Ptr);
03480       Out << ")";
03481     }
03482   }
03483 
03484   for (; I != E; ++I) {
03485     if (isa<StructType>(*I)) {
03486       Out << ".field" << cast<ConstantInt>(I.getOperand())->getZExtValue();
03487     } else if (isa<ArrayType>(*I)) {
03488       Out << ".array[";
03489       writeOperandWithCast(I.getOperand(), Instruction::GetElementPtr);
03490       Out << ']';
03491     } else if (!isa<VectorType>(*I)) {
03492       Out << '[';
03493       writeOperandWithCast(I.getOperand(), Instruction::GetElementPtr);
03494       Out << ']';
03495     } else {
03496       // If the last index is into a vector, then print it out as "+j)".  This
03497       // works with the 'LastIndexIsVector' code above.
03498       if (isa<Constant>(I.getOperand()) &&
03499           cast<Constant>(I.getOperand())->isNullValue()) {
03500         Out << "))";  // avoid "+0".
03501       } else {
03502         Out << ")+(";
03503         writeOperandWithCast(I.getOperand(), Instruction::GetElementPtr);
03504         Out << "))";
03505       }
03506     }
03507   }
03508   Out << ")";
03509 }
03510 
03511 void CWriter::writeMemoryAccess(Value *Operand, const Type *OperandType,
03512                                 bool IsVolatile, unsigned Alignment) {
03513 
03514   bool IsUnaligned = Alignment &&
03515     Alignment < TD->getABITypeAlignment(OperandType);
03516 
03517   if (!IsUnaligned)
03518     Out << '*';
03519   if (IsVolatile || IsUnaligned) {
03520     Out << "((";
03521     if (IsUnaligned)
03522       Out << "struct __attribute__ ((packed, aligned(" << Alignment << "))) {";
03523     printType(Out, OperandType, false, IsUnaligned ? "data" : "volatile*");
03524     if (IsUnaligned) {
03525       Out << "; } ";
03526       if (IsVolatile) Out << "volatile ";
03527       Out << "*";
03528     }
03529     Out << ")";
03530   }
03531 
03532   writeOperand(Operand);
03533 
03534   if (IsVolatile || IsUnaligned) {
03535     Out << ')';
03536     if (IsUnaligned)
03537       Out << "->data";
03538   }
03539 }
03540 
03541 void CWriter::visitLoadInst(LoadInst &I) {
03542   writeMemoryAccess(I.getOperand(0), I.getType(), I.isVolatile(),
03543                     I.getAlignment());
03544 
03545 }
03546 
03547 void CWriter::visitStoreInst(StoreInst &I) {
03548   writeMemoryAccess(I.getPointerOperand(), I.getOperand(0)->getType(),
03549                     I.isVolatile(), I.getAlignment());
03550   Out << " = ";
03551   Value *Operand = I.getOperand(0);
03552   Constant *BitMask = 0;
03553   if (const IntegerType* ITy = dyn_cast<IntegerType>(Operand->getType()))
03554     if (!ITy->isPowerOf2ByteWidth())
03555       // We have a bit width that doesn't match an even power-of-2 byte
03556       // size. Consequently we must & the value with the type's bit mask
03557       BitMask = ConstantInt::get(ITy, ITy->getBitMask());
03558   if (BitMask)
03559     Out << "((";
03560   writeOperand(Operand);
03561   if (BitMask) {
03562     Out << ") & ";
03563     printConstant(BitMask, false);
03564     Out << ")"; 
03565   }
03566 }
03567 
03568 void CWriter::visitGetElementPtrInst(GetElementPtrInst &I) {
03569   printGEPExpression(I.getPointerOperand(), gep_type_begin(I),
03570                      gep_type_end(I), false);
03571 }
03572 
03573 void CWriter::visitVAArgInst(VAArgInst &I) {
03574   Out << "va_arg(*(va_list*)";
03575   writeOperand(I.getOperand(0));
03576   Out << ", ";
03577   printType(Out, I.getType());
03578   Out << ");\n ";
03579 }
03580 
03581 void CWriter::visitInsertElementInst(InsertElementInst &I) {
03582   const Type *EltTy = I.getType()->getElementType();
03583   writeOperand(I.getOperand(0));
03584   Out << ";\n  ";
03585   Out << "((";
03586   printType(Out, PointerType::getUnqual(EltTy));
03587   Out << ")(&" << GetValueName(&I) << "))[";
03588   writeOperand(I.getOperand(2));
03589   Out << "] = (";
03590   writeOperand(I.getOperand(1));
03591   Out << ")";
03592 }
03593 
03594 void CWriter::visitExtractElementInst(ExtractElementInst &I) {
03595   // We know that our operand is not inlined.
03596   Out << "((";
03597   const Type *EltTy = 
03598     cast<VectorType>(I.getOperand(0)->getType())->getElementType();
03599   printType(Out, PointerType::getUnqual(EltTy));
03600   Out << ")(&" << GetValueName(I.getOperand(0)) << "))[";
03601   writeOperand(I.getOperand(1));
03602   Out << "]";
03603 }
03604 
03605 void CWriter::visitShuffleVectorInst(ShuffleVectorInst &SVI) {
03606   Out << "(";
03607   printType(Out, SVI.getType());
03608   Out << "){ ";
03609   const VectorType *VT = SVI.getType();
03610   unsigned NumElts = VT->getNumElements();
03611   const Type *EltTy = VT->getElementType();
03612 
03613   for (unsigned i = 0; i != NumElts; ++i) {
03614     if (i) Out << ", ";
03615     int SrcVal = SVI.getMaskValue(i);
03616     if ((unsigned)SrcVal >= NumElts*2) {
03617       Out << " 0/*undef*/ ";
03618     } else {
03619       Value *Op = SVI.getOperand((unsigned)SrcVal >= NumElts);
03620       if (isa<Instruction>(Op)) {
03621         // Do an extractelement of this value from the appropriate input.
03622         Out << "((";
03623         printType(Out, PointerType::getUnqual(EltTy));
03624         Out << ")(&" << GetValueName(Op)
03625             << "))[" << (SrcVal & (NumElts-1)) << "]";
03626       } else if (isa<ConstantAggregateZero>(Op) || isa<UndefValue>(Op)) {
03627         Out << "0";
03628       } else {
03629         printConstant(cast<ConstantVector>(Op)->getOperand(SrcVal &
03630                                                            (NumElts-1)),
03631                       false);
03632       }
03633     }
03634   }
03635   Out << "}";
03636 }
03637 
03638 void CWriter::visitInsertValueInst(InsertValueInst &IVI) {
03639   // Start by copying the entire aggregate value into the result variable.
03640   writeOperand(IVI.getOperand(0));
03641   Out << ";\n  ";
03642 
03643   // Then do the insert to update the field.
03644   Out << GetValueName(&IVI);
03645   for (const unsigned *b = IVI.idx_begin(), *i = b, *e = IVI.idx_end();
03646        i != e; ++i) {
03647     const Type *IndexedTy =
03648       ExtractValueInst::getIndexedType(IVI.getOperand(0)->getType(), b, i+1);
03649     if (isa<ArrayType>(IndexedTy))
03650       Out << ".array[" << *i << "]";
03651     else
03652       Out << ".field" << *i;
03653   }
03654   Out << " = ";
03655   writeOperand(IVI.getOperand(1));
03656 }
03657 
03658 void CWriter::visitExtractValueInst(ExtractValueInst &EVI) {
03659   Out << "(";
03660   if (isa<UndefValue>(EVI.getOperand(0))) {
03661     Out << "(";
03662     printType(Out, EVI.getType());
03663     Out << ") 0/*UNDEF*/";
03664   } else {
03665     Out << GetValueName(EVI.getOperand(0));
03666     for (const unsigned *b = EVI.idx_begin(), *i = b, *e = EVI.idx_end();
03667          i != e; ++i) {
03668       const Type *IndexedTy =
03669         ExtractValueInst::getIndexedType(EVI.getOperand(0)->getType(), b, i+1);
03670       if (isa<ArrayType>(IndexedTy))
03671         Out << ".array[" << *i << "]";
03672       else
03673         Out << ".field" << *i;
03674     }
03675   }
03676   Out << ")";
03677 }
03678 
03679 //===----------------------------------------------------------------------===//
03680 //                       External Interface declaration
03681 //===----------------------------------------------------------------------===//
03682 
03683 bool CTargetMachine::addPassesToEmitWholeFile(PassManager &PM,
03684                                               formatted_raw_ostream &o,
03685                                               CodeGenFileType FileType,
03686                                               CodeGenOpt::Level OptLevel) {
03687   if (FileType != TargetMachine::AssemblyFile) return true;
03688 
03689   PM.add(createGCLoweringPass());
03690   PM.add(createLowerAllocationsPass(true));
03691   PM.add(createLowerInvokePass());
03692   PM.add(createCFGSimplificationPass());   // clean up after lower invoke.
03693   PM.add(new CBackendNameAllUsedStructsAndMergeFunctions());
03694   PM.add(new CWriter(o));
03695   PM.add(createGCInfoDeleter());
03696   return false;
03697 }