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