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