Adding dllimport, dllexport and external weak linkage types.
[oota-llvm.git] / lib / Target / CBackend / CBackend.cpp
1 //===-- Writer.cpp - Library for converting LLVM code to C ----------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file was developed by the LLVM research group and is distributed under
6 // the University of Illinois Open Source 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/SymbolTable.h"
24 #include "llvm/Intrinsics.h"
25 #include "llvm/IntrinsicInst.h"
26 #include "llvm/Analysis/ConstantsScanner.h"
27 #include "llvm/Analysis/FindUsedTypes.h"
28 #include "llvm/Analysis/LoopInfo.h"
29 #include "llvm/CodeGen/IntrinsicLowering.h"
30 #include "llvm/Transforms/Scalar.h"
31 #include "llvm/Target/TargetMachineRegistry.h"
32 #include "llvm/Support/CallSite.h"
33 #include "llvm/Support/CFG.h"
34 #include "llvm/Support/GetElementPtrTypeIterator.h"
35 #include "llvm/Support/InstVisitor.h"
36 #include "llvm/Support/Mangler.h"
37 #include "llvm/Support/MathExtras.h"
38 #include "llvm/ADT/StringExtras.h"
39 #include "llvm/ADT/STLExtras.h"
40 #include "llvm/Support/MathExtras.h"
41 #include "llvm/Config/config.h"
42 #include <algorithm>
43 #include <iostream>
44 #include <ios>
45 #include <sstream>
46 using namespace llvm;
47
48 namespace {
49   // Register the target.
50   RegisterTarget<CTargetMachine> X("c", "  C backend");
51
52   /// CBackendNameAllUsedStructsAndMergeFunctions - This pass inserts names for
53   /// any unnamed structure types that are used by the program, and merges
54   /// external functions with the same name.
55   ///
56   class CBackendNameAllUsedStructsAndMergeFunctions : public ModulePass {
57     void getAnalysisUsage(AnalysisUsage &AU) const {
58       AU.addRequired<FindUsedTypes>();
59     }
60
61     virtual const char *getPassName() const {
62       return "C backend type canonicalizer";
63     }
64
65     virtual bool runOnModule(Module &M);
66   };
67
68   /// CWriter - This class is the main chunk of code that converts an LLVM
69   /// module to a C translation unit.
70   class CWriter : public FunctionPass, public InstVisitor<CWriter> {
71     std::ostream &Out;
72     DefaultIntrinsicLowering IL;
73     Mangler *Mang;
74     LoopInfo *LI;
75     const Module *TheModule;
76     std::map<const Type *, std::string> TypeNames;
77
78     std::map<const ConstantFP *, unsigned> FPConstantMap;
79   public:
80     CWriter(std::ostream &o) : Out(o) {}
81
82     virtual const char *getPassName() const { return "C backend"; }
83
84     void getAnalysisUsage(AnalysisUsage &AU) const {
85       AU.addRequired<LoopInfo>();
86       AU.setPreservesAll();
87     }
88
89     virtual bool doInitialization(Module &M);
90
91     bool runOnFunction(Function &F) {
92       LI = &getAnalysis<LoopInfo>();
93
94       // Get rid of intrinsics we can't handle.
95       lowerIntrinsics(F);
96
97       // Output all floating point constants that cannot be printed accurately.
98       printFloatingPointConstants(F);
99
100       // Ensure that no local symbols conflict with global symbols.
101       F.renameLocalSymbols();
102
103       printFunction(F);
104       FPConstantMap.clear();
105       return false;
106     }
107
108     virtual bool doFinalization(Module &M) {
109       // Free memory...
110       delete Mang;
111       TypeNames.clear();
112       return false;
113     }
114
115     std::ostream &printType(std::ostream &Out, const Type *Ty,
116                             const std::string &VariableName = "",
117                             bool IgnoreName = false);
118
119     void printStructReturnPointerFunctionType(std::ostream &Out,
120                                               const PointerType *Ty);
121     
122     void writeOperand(Value *Operand);
123     void writeOperandInternal(Value *Operand);
124
125   private :
126     void lowerIntrinsics(Function &F);
127
128     void printModule(Module *M);
129     void printModuleTypes(const SymbolTable &ST);
130     void printContainedStructs(const Type *Ty, std::set<const StructType *> &);
131     void printFloatingPointConstants(Function &F);
132     void printFunctionSignature(const Function *F, bool Prototype);
133
134     void printFunction(Function &);
135     void printBasicBlock(BasicBlock *BB);
136     void printLoop(Loop *L);
137
138     void printConstant(Constant *CPV);
139     void printConstantArray(ConstantArray *CPA);
140     void printConstantPacked(ConstantPacked *CP);
141
142     // isInlinableInst - Attempt to inline instructions into their uses to build
143     // trees as much as possible.  To do this, we have to consistently decide
144     // what is acceptable to inline, so that variable declarations don't get
145     // printed and an extra copy of the expr is not emitted.
146     //
147     static bool isInlinableInst(const Instruction &I) {
148       // Always inline setcc instructions, even if they are shared by multiple
149       // expressions.  GCC generates horrible code if we don't.
150       if (isa<SetCondInst>(I)) return true;
151
152       // Must be an expression, must be used exactly once.  If it is dead, we
153       // emit it inline where it would go.
154       if (I.getType() == Type::VoidTy || !I.hasOneUse() ||
155           isa<TerminatorInst>(I) || isa<CallInst>(I) || isa<PHINode>(I) ||
156           isa<LoadInst>(I) || isa<VAArgInst>(I))
157         // Don't inline a load across a store or other bad things!
158         return false;
159
160       // Only inline instruction it it's use is in the same BB as the inst.
161       return I.getParent() == cast<Instruction>(I.use_back())->getParent();
162     }
163
164     // isDirectAlloca - Define fixed sized allocas in the entry block as direct
165     // variables which are accessed with the & operator.  This causes GCC to
166     // generate significantly better code than to emit alloca calls directly.
167     //
168     static const AllocaInst *isDirectAlloca(const Value *V) {
169       const AllocaInst *AI = dyn_cast<AllocaInst>(V);
170       if (!AI) return false;
171       if (AI->isArrayAllocation())
172         return 0;   // FIXME: we can also inline fixed size array allocas!
173       if (AI->getParent() != &AI->getParent()->getParent()->getEntryBlock())
174         return 0;
175       return AI;
176     }
177
178     // Instruction visitation functions
179     friend class InstVisitor<CWriter>;
180
181     void visitReturnInst(ReturnInst &I);
182     void visitBranchInst(BranchInst &I);
183     void visitSwitchInst(SwitchInst &I);
184     void visitInvokeInst(InvokeInst &I) {
185       assert(0 && "Lowerinvoke pass didn't work!");
186     }
187
188     void visitUnwindInst(UnwindInst &I) {
189       assert(0 && "Lowerinvoke pass didn't work!");
190     }
191     void visitUnreachableInst(UnreachableInst &I);
192
193     void visitPHINode(PHINode &I);
194     void visitBinaryOperator(Instruction &I);
195
196     void visitCastInst (CastInst &I);
197     void visitSelectInst(SelectInst &I);
198     void visitCallInst (CallInst &I);
199     void visitShiftInst(ShiftInst &I) { visitBinaryOperator(I); }
200
201     void visitMallocInst(MallocInst &I);
202     void visitAllocaInst(AllocaInst &I);
203     void visitFreeInst  (FreeInst   &I);
204     void visitLoadInst  (LoadInst   &I);
205     void visitStoreInst (StoreInst  &I);
206     void visitGetElementPtrInst(GetElementPtrInst &I);
207     void visitVAArgInst (VAArgInst &I);
208
209     void visitInstruction(Instruction &I) {
210       std::cerr << "C Writer does not know about " << I;
211       abort();
212     }
213
214     void outputLValue(Instruction *I) {
215       Out << "  " << Mang->getValueName(I) << " = ";
216     }
217
218     bool isGotoCodeNecessary(BasicBlock *From, BasicBlock *To);
219     void printPHICopiesForSuccessor(BasicBlock *CurBlock,
220                                     BasicBlock *Successor, unsigned Indent);
221     void printBranchToBlock(BasicBlock *CurBlock, BasicBlock *SuccBlock,
222                             unsigned Indent);
223     void printIndexingExpression(Value *Ptr, gep_type_iterator I,
224                                  gep_type_iterator E);
225   };
226 }
227
228 /// This method inserts names for any unnamed structure types that are used by
229 /// the program, and removes names from structure types that are not used by the
230 /// program.
231 ///
232 bool CBackendNameAllUsedStructsAndMergeFunctions::runOnModule(Module &M) {
233   // Get a set of types that are used by the program...
234   std::set<const Type *> UT = getAnalysis<FindUsedTypes>().getTypes();
235
236   // Loop over the module symbol table, removing types from UT that are
237   // already named, and removing names for types that are not used.
238   //
239   SymbolTable &MST = M.getSymbolTable();
240   for (SymbolTable::type_iterator TI = MST.type_begin(), TE = MST.type_end();
241        TI != TE; ) {
242     SymbolTable::type_iterator I = TI++;
243
244     // If this is not used, remove it from the symbol table.
245     std::set<const Type *>::iterator UTI = UT.find(I->second);
246     if (UTI == UT.end())
247       MST.remove(I);
248     else
249       UT.erase(UTI);    // Only keep one name for this type.
250   }
251
252   // UT now contains types that are not named.  Loop over it, naming
253   // structure types.
254   //
255   bool Changed = false;
256   unsigned RenameCounter = 0;
257   for (std::set<const Type *>::const_iterator I = UT.begin(), E = UT.end();
258        I != E; ++I)
259     if (const StructType *ST = dyn_cast<StructType>(*I)) {
260       while (M.addTypeName("unnamed"+utostr(RenameCounter), ST))
261         ++RenameCounter;
262       Changed = true;
263     }
264       
265       
266   // Loop over all external functions and globals.  If we have two with
267   // identical names, merge them.
268   // FIXME: This code should disappear when we don't allow values with the same
269   // names when they have different types!
270   std::map<std::string, GlobalValue*> ExtSymbols;
271   for (Module::iterator I = M.begin(), E = M.end(); I != E;) {
272     Function *GV = I++;
273     if (GV->isExternal() && GV->hasName()) {
274       std::pair<std::map<std::string, GlobalValue*>::iterator, bool> X
275         = ExtSymbols.insert(std::make_pair(GV->getName(), GV));
276       if (!X.second) {
277         // Found a conflict, replace this global with the previous one.
278         GlobalValue *OldGV = X.first->second;
279         GV->replaceAllUsesWith(ConstantExpr::getCast(OldGV, GV->getType()));
280         GV->eraseFromParent();
281         Changed = true;
282       }
283     }
284   }
285   // Do the same for globals.
286   for (Module::global_iterator I = M.global_begin(), E = M.global_end();
287        I != E;) {
288     GlobalVariable *GV = I++;
289     if (GV->isExternal() && GV->hasName()) {
290       std::pair<std::map<std::string, GlobalValue*>::iterator, bool> X
291         = ExtSymbols.insert(std::make_pair(GV->getName(), GV));
292       if (!X.second) {
293         // Found a conflict, replace this global with the previous one.
294         GlobalValue *OldGV = X.first->second;
295         GV->replaceAllUsesWith(ConstantExpr::getCast(OldGV, GV->getType()));
296         GV->eraseFromParent();
297         Changed = true;
298       }
299     }
300   }
301   
302   return Changed;
303 }
304
305 /// printStructReturnPointerFunctionType - This is like printType for a struct
306 /// return type, except, instead of printing the type as void (*)(Struct*, ...)
307 /// print it as "Struct (*)(...)", for struct return functions.
308 void CWriter::printStructReturnPointerFunctionType(std::ostream &Out,
309                                                    const PointerType *TheTy) {
310   const FunctionType *FTy = cast<FunctionType>(TheTy->getElementType());
311   std::stringstream FunctionInnards;
312   FunctionInnards << " (*) (";
313   bool PrintedType = false;
314
315   FunctionType::param_iterator I = FTy->param_begin(), E = FTy->param_end();
316   const Type *RetTy = cast<PointerType>(I->get())->getElementType();
317   for (++I; I != E; ++I) {
318     if (PrintedType)
319       FunctionInnards << ", ";
320     printType(FunctionInnards, *I, "");
321     PrintedType = true;
322   }
323   if (FTy->isVarArg()) {
324     if (PrintedType)
325       FunctionInnards << ", ...";
326   } else if (!PrintedType) {
327     FunctionInnards << "void";
328   }
329   FunctionInnards << ')';
330   std::string tstr = FunctionInnards.str();
331   printType(Out, RetTy, tstr);
332 }
333
334
335 // Pass the Type* and the variable name and this prints out the variable
336 // declaration.
337 //
338 std::ostream &CWriter::printType(std::ostream &Out, const Type *Ty,
339                                  const std::string &NameSoFar,
340                                  bool IgnoreName) {
341   if (Ty->isPrimitiveType())
342     switch (Ty->getTypeID()) {
343     case Type::VoidTyID:   return Out << "void "               << NameSoFar;
344     case Type::BoolTyID:   return Out << "bool "               << NameSoFar;
345     case Type::UByteTyID:  return Out << "unsigned char "      << NameSoFar;
346     case Type::SByteTyID:  return Out << "signed char "        << NameSoFar;
347     case Type::UShortTyID: return Out << "unsigned short "     << NameSoFar;
348     case Type::ShortTyID:  return Out << "short "              << NameSoFar;
349     case Type::UIntTyID:   return Out << "unsigned "           << NameSoFar;
350     case Type::IntTyID:    return Out << "int "                << NameSoFar;
351     case Type::ULongTyID:  return Out << "unsigned long long " << NameSoFar;
352     case Type::LongTyID:   return Out << "signed long long "   << NameSoFar;
353     case Type::FloatTyID:  return Out << "float "              << NameSoFar;
354     case Type::DoubleTyID: return Out << "double "             << NameSoFar;
355     default :
356       std::cerr << "Unknown primitive type: " << *Ty << "\n";
357       abort();
358     }
359
360   // Check to see if the type is named.
361   if (!IgnoreName || isa<OpaqueType>(Ty)) {
362     std::map<const Type *, std::string>::iterator I = TypeNames.find(Ty);
363     if (I != TypeNames.end()) return Out << I->second << ' ' << NameSoFar;
364   }
365
366   switch (Ty->getTypeID()) {
367   case Type::FunctionTyID: {
368     const FunctionType *FTy = cast<FunctionType>(Ty);
369     std::stringstream FunctionInnards;
370     FunctionInnards << " (" << NameSoFar << ") (";
371     for (FunctionType::param_iterator I = FTy->param_begin(),
372            E = FTy->param_end(); I != E; ++I) {
373       if (I != FTy->param_begin())
374         FunctionInnards << ", ";
375       printType(FunctionInnards, *I, "");
376     }
377     if (FTy->isVarArg()) {
378       if (FTy->getNumParams())
379         FunctionInnards << ", ...";
380     } else if (!FTy->getNumParams()) {
381       FunctionInnards << "void";
382     }
383     FunctionInnards << ')';
384     std::string tstr = FunctionInnards.str();
385     printType(Out, FTy->getReturnType(), tstr);
386     return Out;
387   }
388   case Type::StructTyID: {
389     const StructType *STy = cast<StructType>(Ty);
390     Out << NameSoFar + " {\n";
391     unsigned Idx = 0;
392     for (StructType::element_iterator I = STy->element_begin(),
393            E = STy->element_end(); I != E; ++I) {
394       Out << "  ";
395       printType(Out, *I, "field" + utostr(Idx++));
396       Out << ";\n";
397     }
398     return Out << '}';
399   }
400
401   case Type::PointerTyID: {
402     const PointerType *PTy = cast<PointerType>(Ty);
403     std::string ptrName = "*" + NameSoFar;
404
405     if (isa<ArrayType>(PTy->getElementType()) ||
406         isa<PackedType>(PTy->getElementType()))
407       ptrName = "(" + ptrName + ")";
408
409     return printType(Out, PTy->getElementType(), ptrName);
410   }
411
412   case Type::ArrayTyID: {
413     const ArrayType *ATy = cast<ArrayType>(Ty);
414     unsigned NumElements = ATy->getNumElements();
415     if (NumElements == 0) NumElements = 1;
416     return printType(Out, ATy->getElementType(),
417                      NameSoFar + "[" + utostr(NumElements) + "]");
418   }
419
420   case Type::PackedTyID: {
421     const PackedType *PTy = cast<PackedType>(Ty);
422     unsigned NumElements = PTy->getNumElements();
423     if (NumElements == 0) NumElements = 1;
424     return printType(Out, PTy->getElementType(),
425                      NameSoFar + "[" + utostr(NumElements) + "]");
426   }
427
428   case Type::OpaqueTyID: {
429     static int Count = 0;
430     std::string TyName = "struct opaque_" + itostr(Count++);
431     assert(TypeNames.find(Ty) == TypeNames.end());
432     TypeNames[Ty] = TyName;
433     return Out << TyName << ' ' << NameSoFar;
434   }
435   default:
436     assert(0 && "Unhandled case in getTypeProps!");
437     abort();
438   }
439
440   return Out;
441 }
442
443 void CWriter::printConstantArray(ConstantArray *CPA) {
444
445   // As a special case, print the array as a string if it is an array of
446   // ubytes or an array of sbytes with positive values.
447   //
448   const Type *ETy = CPA->getType()->getElementType();
449   bool isString = (ETy == Type::SByteTy || ETy == Type::UByteTy);
450
451   // Make sure the last character is a null char, as automatically added by C
452   if (isString && (CPA->getNumOperands() == 0 ||
453                    !cast<Constant>(*(CPA->op_end()-1))->isNullValue()))
454     isString = false;
455
456   if (isString) {
457     Out << '\"';
458     // Keep track of whether the last number was a hexadecimal escape
459     bool LastWasHex = false;
460
461     // Do not include the last character, which we know is null
462     for (unsigned i = 0, e = CPA->getNumOperands()-1; i != e; ++i) {
463       unsigned char C = cast<ConstantInt>(CPA->getOperand(i))->getRawValue();
464
465       // Print it out literally if it is a printable character.  The only thing
466       // to be careful about is when the last letter output was a hex escape
467       // code, in which case we have to be careful not to print out hex digits
468       // explicitly (the C compiler thinks it is a continuation of the previous
469       // character, sheesh...)
470       //
471       if (isprint(C) && (!LastWasHex || !isxdigit(C))) {
472         LastWasHex = false;
473         if (C == '"' || C == '\\')
474           Out << "\\" << C;
475         else
476           Out << C;
477       } else {
478         LastWasHex = false;
479         switch (C) {
480         case '\n': Out << "\\n"; break;
481         case '\t': Out << "\\t"; break;
482         case '\r': Out << "\\r"; break;
483         case '\v': Out << "\\v"; break;
484         case '\a': Out << "\\a"; break;
485         case '\"': Out << "\\\""; break;
486         case '\'': Out << "\\\'"; break;
487         default:
488           Out << "\\x";
489           Out << (char)(( C/16  < 10) ? ( C/16 +'0') : ( C/16 -10+'A'));
490           Out << (char)(((C&15) < 10) ? ((C&15)+'0') : ((C&15)-10+'A'));
491           LastWasHex = true;
492           break;
493         }
494       }
495     }
496     Out << '\"';
497   } else {
498     Out << '{';
499     if (CPA->getNumOperands()) {
500       Out << ' ';
501       printConstant(cast<Constant>(CPA->getOperand(0)));
502       for (unsigned i = 1, e = CPA->getNumOperands(); i != e; ++i) {
503         Out << ", ";
504         printConstant(cast<Constant>(CPA->getOperand(i)));
505       }
506     }
507     Out << " }";
508   }
509 }
510
511 void CWriter::printConstantPacked(ConstantPacked *CP) {
512   Out << '{';
513   if (CP->getNumOperands()) {
514     Out << ' ';
515     printConstant(cast<Constant>(CP->getOperand(0)));
516     for (unsigned i = 1, e = CP->getNumOperands(); i != e; ++i) {
517       Out << ", ";
518       printConstant(cast<Constant>(CP->getOperand(i)));
519     }
520   }
521   Out << " }";
522 }
523
524 // isFPCSafeToPrint - Returns true if we may assume that CFP may be written out
525 // textually as a double (rather than as a reference to a stack-allocated
526 // variable). We decide this by converting CFP to a string and back into a
527 // double, and then checking whether the conversion results in a bit-equal
528 // double to the original value of CFP. This depends on us and the target C
529 // compiler agreeing on the conversion process (which is pretty likely since we
530 // only deal in IEEE FP).
531 //
532 static bool isFPCSafeToPrint(const ConstantFP *CFP) {
533 #if HAVE_PRINTF_A
534   char Buffer[100];
535   sprintf(Buffer, "%a", CFP->getValue());
536
537   if (!strncmp(Buffer, "0x", 2) ||
538       !strncmp(Buffer, "-0x", 3) ||
539       !strncmp(Buffer, "+0x", 3))
540     return atof(Buffer) == CFP->getValue();
541   return false;
542 #else
543   std::string StrVal = ftostr(CFP->getValue());
544
545   while (StrVal[0] == ' ')
546     StrVal.erase(StrVal.begin());
547
548   // Check to make sure that the stringized number is not some string like "Inf"
549   // or NaN.  Check that the string matches the "[-+]?[0-9]" regex.
550   if ((StrVal[0] >= '0' && StrVal[0] <= '9') ||
551       ((StrVal[0] == '-' || StrVal[0] == '+') &&
552        (StrVal[1] >= '0' && StrVal[1] <= '9')))
553     // Reparse stringized version!
554     return atof(StrVal.c_str()) == CFP->getValue();
555   return false;
556 #endif
557 }
558
559 // printConstant - The LLVM Constant to C Constant converter.
560 void CWriter::printConstant(Constant *CPV) {
561   if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(CPV)) {
562     switch (CE->getOpcode()) {
563     case Instruction::Cast:
564       Out << "((";
565       printType(Out, CPV->getType());
566       Out << ')';
567       printConstant(CE->getOperand(0));
568       Out << ')';
569       return;
570
571     case Instruction::GetElementPtr:
572       Out << "(&(";
573       printIndexingExpression(CE->getOperand(0), gep_type_begin(CPV),
574                               gep_type_end(CPV));
575       Out << "))";
576       return;
577     case Instruction::Select:
578       Out << '(';
579       printConstant(CE->getOperand(0));
580       Out << '?';
581       printConstant(CE->getOperand(1));
582       Out << ':';
583       printConstant(CE->getOperand(2));
584       Out << ')';
585       return;
586     case Instruction::Add:
587     case Instruction::Sub:
588     case Instruction::Mul:
589     case Instruction::Div:
590     case Instruction::Rem:
591     case Instruction::And:
592     case Instruction::Or:
593     case Instruction::Xor:
594     case Instruction::SetEQ:
595     case Instruction::SetNE:
596     case Instruction::SetLT:
597     case Instruction::SetLE:
598     case Instruction::SetGT:
599     case Instruction::SetGE:
600     case Instruction::Shl:
601     case Instruction::Shr:
602       Out << '(';
603       printConstant(CE->getOperand(0));
604       switch (CE->getOpcode()) {
605       case Instruction::Add: Out << " + "; break;
606       case Instruction::Sub: Out << " - "; break;
607       case Instruction::Mul: Out << " * "; break;
608       case Instruction::Div: Out << " / "; break;
609       case Instruction::Rem: Out << " % "; break;
610       case Instruction::And: Out << " & "; break;
611       case Instruction::Or:  Out << " | "; break;
612       case Instruction::Xor: Out << " ^ "; break;
613       case Instruction::SetEQ: Out << " == "; break;
614       case Instruction::SetNE: Out << " != "; break;
615       case Instruction::SetLT: Out << " < "; break;
616       case Instruction::SetLE: Out << " <= "; break;
617       case Instruction::SetGT: Out << " > "; break;
618       case Instruction::SetGE: Out << " >= "; break;
619       case Instruction::Shl: Out << " << "; break;
620       case Instruction::Shr: Out << " >> "; break;
621       default: assert(0 && "Illegal opcode here!");
622       }
623       printConstant(CE->getOperand(1));
624       Out << ')';
625       return;
626
627     default:
628       std::cerr << "CWriter Error: Unhandled constant expression: "
629                 << *CE << "\n";
630       abort();
631     }
632   } else if (isa<UndefValue>(CPV) && CPV->getType()->isFirstClassType()) {
633     Out << "((";
634     printType(Out, CPV->getType());
635     Out << ")/*UNDEF*/0)";
636     return;
637   }
638
639   switch (CPV->getType()->getTypeID()) {
640   case Type::BoolTyID:
641     Out << (CPV == ConstantBool::False ? '0' : '1'); break;
642   case Type::SByteTyID:
643   case Type::ShortTyID:
644     Out << cast<ConstantSInt>(CPV)->getValue(); break;
645   case Type::IntTyID:
646     if ((int)cast<ConstantSInt>(CPV)->getValue() == (int)0x80000000)
647       Out << "((int)0x80000000U)";   // Handle MININT specially to avoid warning
648     else
649       Out << cast<ConstantSInt>(CPV)->getValue();
650     break;
651
652   case Type::LongTyID:
653     if (cast<ConstantSInt>(CPV)->isMinValue())
654       Out << "(/*INT64_MIN*/(-9223372036854775807LL)-1)";
655     else
656       Out << cast<ConstantSInt>(CPV)->getValue() << "ll"; break;
657
658   case Type::UByteTyID:
659   case Type::UShortTyID:
660     Out << cast<ConstantUInt>(CPV)->getValue(); break;
661   case Type::UIntTyID:
662     Out << cast<ConstantUInt>(CPV)->getValue() << 'u'; break;
663   case Type::ULongTyID:
664     Out << cast<ConstantUInt>(CPV)->getValue() << "ull"; break;
665
666   case Type::FloatTyID:
667   case Type::DoubleTyID: {
668     ConstantFP *FPC = cast<ConstantFP>(CPV);
669     std::map<const ConstantFP*, unsigned>::iterator I = FPConstantMap.find(FPC);
670     if (I != FPConstantMap.end()) {
671       // Because of FP precision problems we must load from a stack allocated
672       // value that holds the value in hex.
673       Out << "(*(" << (FPC->getType() == Type::FloatTy ? "float" : "double")
674           << "*)&FPConstant" << I->second << ')';
675     } else {
676       if (IsNAN(FPC->getValue())) {
677         // The value is NaN
678
679         // The prefix for a quiet NaN is 0x7FF8. For a signalling NaN,
680         // it's 0x7ff4.
681         const unsigned long QuietNaN = 0x7ff8UL;
682         const unsigned long SignalNaN = 0x7ff4UL;
683
684         // We need to grab the first part of the FP #
685         char Buffer[100];
686
687         uint64_t ll = DoubleToBits(FPC->getValue());
688         sprintf(Buffer, "0x%llx", static_cast<long long>(ll));
689
690         std::string Num(&Buffer[0], &Buffer[6]);
691         unsigned long Val = strtoul(Num.c_str(), 0, 16);
692
693         if (FPC->getType() == Type::FloatTy)
694           Out << "LLVM_NAN" << (Val == QuietNaN ? "" : "S") << "F(\""
695               << Buffer << "\") /*nan*/ ";
696         else
697           Out << "LLVM_NAN" << (Val == QuietNaN ? "" : "S") << "(\""
698               << Buffer << "\") /*nan*/ ";
699       } else if (IsInf(FPC->getValue())) {
700         // The value is Inf
701         if (FPC->getValue() < 0) Out << '-';
702         Out << "LLVM_INF" << (FPC->getType() == Type::FloatTy ? "F" : "")
703             << " /*inf*/ ";
704       } else {
705         std::string Num;
706 #if HAVE_PRINTF_A
707         // Print out the constant as a floating point number.
708         char Buffer[100];
709         sprintf(Buffer, "%a", FPC->getValue());
710         Num = Buffer;
711 #else
712         Num = ftostr(FPC->getValue());
713 #endif
714         Out << Num;
715       }
716     }
717     break;
718   }
719
720   case Type::ArrayTyID:
721     if (isa<ConstantAggregateZero>(CPV) || isa<UndefValue>(CPV)) {
722       const ArrayType *AT = cast<ArrayType>(CPV->getType());
723       Out << '{';
724       if (AT->getNumElements()) {
725         Out << ' ';
726         Constant *CZ = Constant::getNullValue(AT->getElementType());
727         printConstant(CZ);
728         for (unsigned i = 1, e = AT->getNumElements(); i != e; ++i) {
729           Out << ", ";
730           printConstant(CZ);
731         }
732       }
733       Out << " }";
734     } else {
735       printConstantArray(cast<ConstantArray>(CPV));
736     }
737     break;
738
739   case Type::PackedTyID:
740     if (isa<ConstantAggregateZero>(CPV) || isa<UndefValue>(CPV)) {
741       const PackedType *AT = cast<PackedType>(CPV->getType());
742       Out << '{';
743       if (AT->getNumElements()) {
744         Out << ' ';
745         Constant *CZ = Constant::getNullValue(AT->getElementType());
746         printConstant(CZ);
747         for (unsigned i = 1, e = AT->getNumElements(); i != e; ++i) {
748           Out << ", ";
749           printConstant(CZ);
750         }
751       }
752       Out << " }";
753     } else {
754       printConstantPacked(cast<ConstantPacked>(CPV));
755     }
756     break;
757
758   case Type::StructTyID:
759     if (isa<ConstantAggregateZero>(CPV) || isa<UndefValue>(CPV)) {
760       const StructType *ST = cast<StructType>(CPV->getType());
761       Out << '{';
762       if (ST->getNumElements()) {
763         Out << ' ';
764         printConstant(Constant::getNullValue(ST->getElementType(0)));
765         for (unsigned i = 1, e = ST->getNumElements(); i != e; ++i) {
766           Out << ", ";
767           printConstant(Constant::getNullValue(ST->getElementType(i)));
768         }
769       }
770       Out << " }";
771     } else {
772       Out << '{';
773       if (CPV->getNumOperands()) {
774         Out << ' ';
775         printConstant(cast<Constant>(CPV->getOperand(0)));
776         for (unsigned i = 1, e = CPV->getNumOperands(); i != e; ++i) {
777           Out << ", ";
778           printConstant(cast<Constant>(CPV->getOperand(i)));
779         }
780       }
781       Out << " }";
782     }
783     break;
784
785   case Type::PointerTyID:
786     if (isa<ConstantPointerNull>(CPV)) {
787       Out << "((";
788       printType(Out, CPV->getType());
789       Out << ")/*NULL*/0)";
790       break;
791     } else if (GlobalValue *GV = dyn_cast<GlobalValue>(CPV)) {
792       writeOperand(GV);
793       break;
794     }
795     // FALL THROUGH
796   default:
797     std::cerr << "Unknown constant type: " << *CPV << "\n";
798     abort();
799   }
800 }
801
802 void CWriter::writeOperandInternal(Value *Operand) {
803   if (Instruction *I = dyn_cast<Instruction>(Operand))
804     if (isInlinableInst(*I) && !isDirectAlloca(I)) {
805       // Should we inline this instruction to build a tree?
806       Out << '(';
807       visit(*I);
808       Out << ')';
809       return;
810     }
811
812   Constant* CPV = dyn_cast<Constant>(Operand);
813   if (CPV && !isa<GlobalValue>(CPV)) {
814     printConstant(CPV);
815   } else {
816     Out << Mang->getValueName(Operand);
817   }
818 }
819
820 void CWriter::writeOperand(Value *Operand) {
821   if (isa<GlobalVariable>(Operand) || isDirectAlloca(Operand))
822     Out << "(&";  // Global variables are references as their addresses by llvm
823
824   writeOperandInternal(Operand);
825
826   if (isa<GlobalVariable>(Operand) || isDirectAlloca(Operand))
827     Out << ')';
828 }
829
830 // generateCompilerSpecificCode - This is where we add conditional compilation
831 // directives to cater to specific compilers as need be.
832 //
833 static void generateCompilerSpecificCode(std::ostream& Out) {
834   // Alloca is hard to get, and we don't want to include stdlib.h here.
835   Out << "/* get a declaration for alloca */\n"
836       << "#if defined(__CYGWIN__) || defined(__MINGW32__)\n"
837       << "extern void *_alloca(unsigned long);\n"
838       << "#define alloca(x) _alloca(x)\n"
839       << "#elif defined(__APPLE__)\n"
840       << "extern void *__builtin_alloca(unsigned long);\n"
841       << "#define alloca(x) __builtin_alloca(x)\n"
842       << "#elif defined(__sun__)\n"
843       << "#if defined(__sparcv9)\n"
844       << "extern void *__builtin_alloca(unsigned long);\n"
845       << "#else\n"
846       << "extern void *__builtin_alloca(unsigned int);\n"
847       << "#endif\n"
848       << "#define alloca(x) __builtin_alloca(x)\n"
849       << "#elif defined(__FreeBSD__) || defined(__OpenBSD__)\n"
850       << "#define alloca(x) __builtin_alloca(x)\n"
851       << "#elif !defined(_MSC_VER)\n"
852       << "#include <alloca.h>\n"
853       << "#endif\n\n";
854
855   // We output GCC specific attributes to preserve 'linkonce'ness on globals.
856   // If we aren't being compiled with GCC, just drop these attributes.
857   Out << "#ifndef __GNUC__  /* Can only support \"linkonce\" vars with GCC */\n"
858       << "#define __attribute__(X)\n"
859       << "#endif\n\n";
860
861 #if 0
862   // At some point, we should support "external weak" vs. "weak" linkages.
863   // On Mac OS X, "external weak" is spelled "__attribute__((weak_import))".
864   Out << "#if defined(__GNUC__) && defined(__APPLE_CC__)\n"
865       << "#define __EXTERNAL_WEAK__ __attribute__((weak_import))\n"
866       << "#elif defined(__GNUC__)\n"
867       << "#define __EXTERNAL_WEAK__ __attribute__((weak))\n"
868       << "#else\n"
869       << "#define __EXTERNAL_WEAK__\n"
870       << "#endif\n\n";
871 #endif
872
873   // For now, turn off the weak linkage attribute on Mac OS X. (See above.)
874   Out << "#if defined(__GNUC__) && defined(__APPLE_CC__)\n"
875       << "#define __ATTRIBUTE_WEAK__\n"
876       << "#elif defined(__GNUC__)\n"
877       << "#define __ATTRIBUTE_WEAK__ __attribute__((weak))\n"
878       << "#else\n"
879       << "#define __ATTRIBUTE_WEAK__\n"
880       << "#endif\n\n";
881
882   // Define NaN and Inf as GCC builtins if using GCC, as 0 otherwise
883   // From the GCC documentation:
884   //
885   //   double __builtin_nan (const char *str)
886   //
887   // This is an implementation of the ISO C99 function nan.
888   //
889   // Since ISO C99 defines this function in terms of strtod, which we do
890   // not implement, a description of the parsing is in order. The string is
891   // parsed as by strtol; that is, the base is recognized by leading 0 or
892   // 0x prefixes. The number parsed is placed in the significand such that
893   // the least significant bit of the number is at the least significant
894   // bit of the significand. The number is truncated to fit the significand
895   // field provided. The significand is forced to be a quiet NaN.
896   //
897   // This function, if given a string literal, is evaluated early enough
898   // that it is considered a compile-time constant.
899   //
900   //   float __builtin_nanf (const char *str)
901   //
902   // Similar to __builtin_nan, except the return type is float.
903   //
904   //   double __builtin_inf (void)
905   //
906   // Similar to __builtin_huge_val, except a warning is generated if the
907   // target floating-point format does not support infinities. This
908   // function is suitable for implementing the ISO C99 macro INFINITY.
909   //
910   //   float __builtin_inff (void)
911   //
912   // Similar to __builtin_inf, except the return type is float.
913   Out << "#ifdef __GNUC__\n"
914       << "#define LLVM_NAN(NanStr)   __builtin_nan(NanStr)   /* Double */\n"
915       << "#define LLVM_NANF(NanStr)  __builtin_nanf(NanStr)  /* Float */\n"
916       << "#define LLVM_NANS(NanStr)  __builtin_nans(NanStr)  /* Double */\n"
917       << "#define LLVM_NANSF(NanStr) __builtin_nansf(NanStr) /* Float */\n"
918       << "#define LLVM_INF           __builtin_inf()         /* Double */\n"
919       << "#define LLVM_INFF          __builtin_inff()        /* Float */\n"
920       << "#define LLVM_PREFETCH(addr,rw,locality) "
921                               "__builtin_prefetch(addr,rw,locality)\n"
922       << "#define __ATTRIBUTE_CTOR__ __attribute__((constructor))\n"
923       << "#define __ATTRIBUTE_DTOR__ __attribute__((destructor))\n"
924       << "#define LLVM_ASM           __asm__\n"
925       << "#else\n"
926       << "#define LLVM_NAN(NanStr)   ((double)0.0)           /* Double */\n"
927       << "#define LLVM_NANF(NanStr)  0.0F                    /* Float */\n"
928       << "#define LLVM_NANS(NanStr)  ((double)0.0)           /* Double */\n"
929       << "#define LLVM_NANSF(NanStr) 0.0F                    /* Float */\n"
930       << "#define LLVM_INF           ((double)0.0)           /* Double */\n"
931       << "#define LLVM_INFF          0.0F                    /* Float */\n"
932       << "#define LLVM_PREFETCH(addr,rw,locality)            /* PREFETCH */\n"
933       << "#define __ATTRIBUTE_CTOR__\n"
934       << "#define __ATTRIBUTE_DTOR__\n"
935       << "#define LLVM_ASM(X)\n"
936       << "#endif\n\n";
937
938   // Output target-specific code that should be inserted into main.
939   Out << "#define CODE_FOR_MAIN() /* Any target-specific code for main()*/\n";
940   // On X86, set the FP control word to 64-bits of precision instead of 80 bits.
941   Out << "#if defined(__GNUC__) && !defined(__llvm__)\n"
942       << "#if defined(i386) || defined(__i386__) || defined(__i386) || "
943       << "defined(__x86_64__)\n"
944       << "#undef CODE_FOR_MAIN\n"
945       << "#define CODE_FOR_MAIN() \\\n"
946       << "  {short F;__asm__ (\"fnstcw %0\" : \"=m\" (*&F)); \\\n"
947       << "  F=(F&~0x300)|0x200;__asm__(\"fldcw %0\"::\"m\"(*&F));}\n"
948       << "#endif\n#endif\n";
949
950 }
951
952 /// FindStaticTors - Given a static ctor/dtor list, unpack its contents into
953 /// the StaticTors set.
954 static void FindStaticTors(GlobalVariable *GV, std::set<Function*> &StaticTors){
955   ConstantArray *InitList = dyn_cast<ConstantArray>(GV->getInitializer());
956   if (!InitList) return;
957   
958   for (unsigned i = 0, e = InitList->getNumOperands(); i != e; ++i)
959     if (ConstantStruct *CS = dyn_cast<ConstantStruct>(InitList->getOperand(i))){
960       if (CS->getNumOperands() != 2) return;  // Not array of 2-element structs.
961       
962       if (CS->getOperand(1)->isNullValue())
963         return;  // Found a null terminator, exit printing.
964       Constant *FP = CS->getOperand(1);
965       if (ConstantExpr *CE = dyn_cast<ConstantExpr>(FP))
966         if (CE->getOpcode() == Instruction::Cast)
967           FP = CE->getOperand(0);
968       if (Function *F = dyn_cast<Function>(FP))
969         StaticTors.insert(F);
970     }
971 }
972
973 enum SpecialGlobalClass {
974   NotSpecial = 0,
975   GlobalCtors, GlobalDtors,
976   NotPrinted
977 };
978
979 /// getGlobalVariableClass - If this is a global that is specially recognized
980 /// by LLVM, return a code that indicates how we should handle it.
981 static SpecialGlobalClass getGlobalVariableClass(const GlobalVariable *GV) {
982   // If this is a global ctors/dtors list, handle it now.
983   if (GV->hasAppendingLinkage() && GV->use_empty()) {
984     if (GV->getName() == "llvm.global_ctors")
985       return GlobalCtors;
986     else if (GV->getName() == "llvm.global_dtors")
987       return GlobalDtors;
988   }
989   
990   // Otherwise, it it is other metadata, don't print it.  This catches things
991   // like debug information.
992   if (GV->getSection() == "llvm.metadata")
993     return NotPrinted;
994   
995   return NotSpecial;
996 }
997
998
999 bool CWriter::doInitialization(Module &M) {
1000   // Initialize
1001   TheModule = &M;
1002
1003   IL.AddPrototypes(M);
1004
1005   // Ensure that all structure types have names...
1006   Mang = new Mangler(M);
1007   Mang->markCharUnacceptable('.');
1008
1009   // Keep track of which functions are static ctors/dtors so they can have
1010   // an attribute added to their prototypes.
1011   std::set<Function*> StaticCtors, StaticDtors;
1012   for (Module::global_iterator I = M.global_begin(), E = M.global_end();
1013        I != E; ++I) {
1014     switch (getGlobalVariableClass(I)) {
1015     default: break;
1016     case GlobalCtors:
1017       FindStaticTors(I, StaticCtors);
1018       break;
1019     case GlobalDtors:
1020       FindStaticTors(I, StaticDtors);
1021       break;
1022     }
1023   }
1024   
1025   // get declaration for alloca
1026   Out << "/* Provide Declarations */\n";
1027   Out << "#include <stdarg.h>\n";      // Varargs support
1028   Out << "#include <setjmp.h>\n";      // Unwind support
1029   generateCompilerSpecificCode(Out);
1030
1031   // Provide a definition for `bool' if not compiling with a C++ compiler.
1032   Out << "\n"
1033       << "#ifndef __cplusplus\ntypedef unsigned char bool;\n#endif\n"
1034
1035       << "\n\n/* Support for floating point constants */\n"
1036       << "typedef unsigned long long ConstantDoubleTy;\n"
1037       << "typedef unsigned int        ConstantFloatTy;\n"
1038
1039       << "\n\n/* Global Declarations */\n";
1040
1041   // First output all the declarations for the program, because C requires
1042   // Functions & globals to be declared before they are used.
1043   //
1044
1045   // Loop over the symbol table, emitting all named constants...
1046   printModuleTypes(M.getSymbolTable());
1047
1048   // Global variable declarations...
1049   if (!M.global_empty()) {
1050     Out << "\n/* External Global Variable Declarations */\n";
1051     for (Module::global_iterator I = M.global_begin(), E = M.global_end();
1052          I != E; ++I) {
1053       if (I->hasExternalLinkage()) {
1054         Out << "extern ";
1055         printType(Out, I->getType()->getElementType(), Mang->getValueName(I));
1056         Out << ";\n";
1057       } else if (I->hasDLLImportLinkage()) {
1058         Out << "__declspec(dllimport) ";
1059         printType(Out, I->getType()->getElementType(), Mang->getValueName(I));
1060         Out << ";\n";        
1061       }      
1062     }
1063   }
1064
1065   // Function declarations
1066   Out << "\n/* Function Declarations */\n";
1067   Out << "double fmod(double, double);\n";   // Support for FP rem
1068   Out << "float fmodf(float, float);\n";
1069   
1070   for (Module::iterator I = M.begin(), E = M.end(); I != E; ++I) {
1071     // Don't print declarations for intrinsic functions.
1072     if (!I->getIntrinsicID() &&
1073         I->getName() != "setjmp" && I->getName() != "longjmp") {
1074       printFunctionSignature(I, true);
1075       if (I->hasWeakLinkage() || I->hasLinkOnceLinkage()) 
1076         Out << " __ATTRIBUTE_WEAK__";
1077       if (StaticCtors.count(I))
1078         Out << " __ATTRIBUTE_CTOR__";
1079       if (StaticDtors.count(I))
1080         Out << " __ATTRIBUTE_DTOR__";
1081       
1082       if (I->hasName() && I->getName()[0] == 1)
1083         Out << " LLVM_ASM(\"" << I->getName().c_str()+1 << "\")";
1084           
1085       Out << ";\n";
1086     }
1087   }
1088
1089   // Output the global variable declarations
1090   if (!M.global_empty()) {
1091     Out << "\n\n/* Global Variable Declarations */\n";
1092     for (Module::global_iterator I = M.global_begin(), E = M.global_end();
1093          I != E; ++I)
1094       if (!I->isExternal()) {
1095         // Ignore special globals, such as debug info.
1096         if (getGlobalVariableClass(I))
1097           continue;
1098         
1099         if (I->hasInternalLinkage())
1100           Out << "static ";
1101         else
1102           Out << "extern ";
1103         printType(Out, I->getType()->getElementType(), Mang->getValueName(I));
1104
1105         if (I->hasLinkOnceLinkage())
1106           Out << " __attribute__((common))";
1107         else if (I->hasWeakLinkage())
1108           Out << " __ATTRIBUTE_WEAK__";
1109         Out << ";\n";
1110       }
1111   }
1112
1113   // Output the global variable definitions and contents...
1114   if (!M.global_empty()) {
1115     Out << "\n\n/* Global Variable Definitions and Initialization */\n";
1116     for (Module::global_iterator I = M.global_begin(), E = M.global_end(); 
1117          I != E; ++I)
1118       if (!I->isExternal()) {
1119         // Ignore special globals, such as debug info.
1120         if (getGlobalVariableClass(I))
1121           continue;
1122         
1123         if (I->hasInternalLinkage())
1124           Out << "static ";
1125         else if (I->hasDLLImportLinkage())
1126           Out << "__declspec(dllimport) ";
1127         else if (I->hasDLLExportLinkage())
1128           Out << "__declspec(dllexport) ";
1129             
1130         printType(Out, I->getType()->getElementType(), Mang->getValueName(I));
1131         if (I->hasLinkOnceLinkage())
1132           Out << " __attribute__((common))";
1133         else if (I->hasWeakLinkage())
1134           Out << " __ATTRIBUTE_WEAK__";
1135
1136         // If the initializer is not null, emit the initializer.  If it is null,
1137         // we try to avoid emitting large amounts of zeros.  The problem with
1138         // this, however, occurs when the variable has weak linkage.  In this
1139         // case, the assembler will complain about the variable being both weak
1140         // and common, so we disable this optimization.
1141         if (!I->getInitializer()->isNullValue()) {
1142           Out << " = " ;
1143           writeOperand(I->getInitializer());
1144         } else if (I->hasWeakLinkage()) {
1145           // We have to specify an initializer, but it doesn't have to be
1146           // complete.  If the value is an aggregate, print out { 0 }, and let
1147           // the compiler figure out the rest of the zeros.
1148           Out << " = " ;
1149           if (isa<StructType>(I->getInitializer()->getType()) ||
1150               isa<ArrayType>(I->getInitializer()->getType()) ||
1151               isa<PackedType>(I->getInitializer()->getType())) {
1152             Out << "{ 0 }";
1153           } else {
1154             // Just print it out normally.
1155             writeOperand(I->getInitializer());
1156           }
1157         }
1158         Out << ";\n";
1159       }
1160   }
1161
1162   if (!M.empty())
1163     Out << "\n\n/* Function Bodies */\n";
1164   return false;
1165 }
1166
1167
1168 /// Output all floating point constants that cannot be printed accurately...
1169 void CWriter::printFloatingPointConstants(Function &F) {
1170   // Scan the module for floating point constants.  If any FP constant is used
1171   // in the function, we want to redirect it here so that we do not depend on
1172   // the precision of the printed form, unless the printed form preserves
1173   // precision.
1174   //
1175   static unsigned FPCounter = 0;
1176   for (constant_iterator I = constant_begin(&F), E = constant_end(&F);
1177        I != E; ++I)
1178     if (const ConstantFP *FPC = dyn_cast<ConstantFP>(*I))
1179       if (!isFPCSafeToPrint(FPC) && // Do not put in FPConstantMap if safe.
1180           !FPConstantMap.count(FPC)) {
1181         double Val = FPC->getValue();
1182
1183         FPConstantMap[FPC] = FPCounter;  // Number the FP constants
1184
1185         if (FPC->getType() == Type::DoubleTy) {
1186           Out << "static const ConstantDoubleTy FPConstant" << FPCounter++
1187               << " = 0x" << std::hex << DoubleToBits(Val) << std::dec
1188               << "ULL;    /* " << Val << " */\n";
1189         } else if (FPC->getType() == Type::FloatTy) {
1190           Out << "static const ConstantFloatTy FPConstant" << FPCounter++
1191               << " = 0x" << std::hex << FloatToBits(Val) << std::dec
1192               << "U;    /* " << Val << " */\n";
1193         } else
1194           assert(0 && "Unknown float type!");
1195       }
1196
1197   Out << '\n';
1198 }
1199
1200
1201 /// printSymbolTable - Run through symbol table looking for type names.  If a
1202 /// type name is found, emit its declaration...
1203 ///
1204 void CWriter::printModuleTypes(const SymbolTable &ST) {
1205   // We are only interested in the type plane of the symbol table.
1206   SymbolTable::type_const_iterator I   = ST.type_begin();
1207   SymbolTable::type_const_iterator End = ST.type_end();
1208
1209   // If there are no type names, exit early.
1210   if (I == End) return;
1211
1212   // Print out forward declarations for structure types before anything else!
1213   Out << "/* Structure forward decls */\n";
1214   for (; I != End; ++I)
1215     if (const Type *STy = dyn_cast<StructType>(I->second)) {
1216       std::string Name = "struct l_" + Mang->makeNameProper(I->first);
1217       Out << Name << ";\n";
1218       TypeNames.insert(std::make_pair(STy, Name));
1219     }
1220
1221   Out << '\n';
1222
1223   // Now we can print out typedefs...
1224   Out << "/* Typedefs */\n";
1225   for (I = ST.type_begin(); I != End; ++I) {
1226     const Type *Ty = cast<Type>(I->second);
1227     std::string Name = "l_" + Mang->makeNameProper(I->first);
1228     Out << "typedef ";
1229     printType(Out, Ty, Name);
1230     Out << ";\n";
1231   }
1232
1233   Out << '\n';
1234
1235   // Keep track of which structures have been printed so far...
1236   std::set<const StructType *> StructPrinted;
1237
1238   // Loop over all structures then push them into the stack so they are
1239   // printed in the correct order.
1240   //
1241   Out << "/* Structure contents */\n";
1242   for (I = ST.type_begin(); I != End; ++I)
1243     if (const StructType *STy = dyn_cast<StructType>(I->second))
1244       // Only print out used types!
1245       printContainedStructs(STy, StructPrinted);
1246 }
1247
1248 // Push the struct onto the stack and recursively push all structs
1249 // this one depends on.
1250 //
1251 // TODO:  Make this work properly with packed types
1252 //
1253 void CWriter::printContainedStructs(const Type *Ty,
1254                                     std::set<const StructType*> &StructPrinted){
1255   // Don't walk through pointers.
1256   if (isa<PointerType>(Ty) || Ty->isPrimitiveType()) return;
1257   
1258   // Print all contained types first.
1259   for (Type::subtype_iterator I = Ty->subtype_begin(),
1260        E = Ty->subtype_end(); I != E; ++I)
1261     printContainedStructs(*I, StructPrinted);
1262   
1263   if (const StructType *STy = dyn_cast<StructType>(Ty)) {
1264     // Check to see if we have already printed this struct.
1265     if (StructPrinted.insert(STy).second) {
1266       // Print structure type out.
1267       std::string Name = TypeNames[STy];
1268       printType(Out, STy, Name, true);
1269       Out << ";\n\n";
1270     }
1271   }
1272 }
1273
1274 void CWriter::printFunctionSignature(const Function *F, bool Prototype) {
1275   /// isCStructReturn - Should this function actually return a struct by-value?
1276   bool isCStructReturn = F->getCallingConv() == CallingConv::CSRet;
1277   
1278   if (F->hasInternalLinkage()) Out << "static ";
1279   if (F->hasDLLImportLinkage()) Out << "__declspec(dllimport) ";
1280   if (F->hasDLLExportLinkage()) Out << "__declspec(dllexport) ";  
1281
1282   // Loop over the arguments, printing them...
1283   const FunctionType *FT = cast<FunctionType>(F->getFunctionType());
1284
1285   std::stringstream FunctionInnards;
1286
1287   // Print out the name...
1288   FunctionInnards << Mang->getValueName(F) << '(';
1289
1290   bool PrintedArg = false;
1291   if (!F->isExternal()) {
1292     if (!F->arg_empty()) {
1293       Function::const_arg_iterator I = F->arg_begin(), E = F->arg_end();
1294       
1295       // If this is a struct-return function, don't print the hidden
1296       // struct-return argument.
1297       if (isCStructReturn) {
1298         assert(I != E && "Invalid struct return function!");
1299         ++I;
1300       }
1301       
1302       std::string ArgName;
1303       for (; I != E; ++I) {
1304         if (PrintedArg) FunctionInnards << ", ";
1305         if (I->hasName() || !Prototype)
1306           ArgName = Mang->getValueName(I);
1307         else
1308           ArgName = "";
1309         printType(FunctionInnards, I->getType(), ArgName);
1310         PrintedArg = true;
1311       }
1312     }
1313   } else {
1314     // Loop over the arguments, printing them.
1315     FunctionType::param_iterator I = FT->param_begin(), E = FT->param_end();
1316     
1317     // If this is a struct-return function, don't print the hidden
1318     // struct-return argument.
1319     if (isCStructReturn) {
1320       assert(I != E && "Invalid struct return function!");
1321       ++I;
1322     }
1323     
1324     for (; I != E; ++I) {
1325       if (PrintedArg) FunctionInnards << ", ";
1326       printType(FunctionInnards, *I);
1327       PrintedArg = true;
1328     }
1329   }
1330
1331   // Finish printing arguments... if this is a vararg function, print the ...,
1332   // unless there are no known types, in which case, we just emit ().
1333   //
1334   if (FT->isVarArg() && PrintedArg) {
1335     if (PrintedArg) FunctionInnards << ", ";
1336     FunctionInnards << "...";  // Output varargs portion of signature!
1337   } else if (!FT->isVarArg() && !PrintedArg) {
1338     FunctionInnards << "void"; // ret() -> ret(void) in C.
1339   }
1340   FunctionInnards << ')';
1341   
1342   // Get the return tpe for the function.
1343   const Type *RetTy;
1344   if (!isCStructReturn)
1345     RetTy = F->getReturnType();
1346   else {
1347     // If this is a struct-return function, print the struct-return type.
1348     RetTy = cast<PointerType>(FT->getParamType(0))->getElementType();
1349   }
1350     
1351   // Print out the return type and the signature built above.
1352   printType(Out, RetTy, FunctionInnards.str());
1353 }
1354
1355 void CWriter::printFunction(Function &F) {
1356   printFunctionSignature(&F, false);
1357   Out << " {\n";
1358   
1359   // If this is a struct return function, handle the result with magic.
1360   if (F.getCallingConv() == CallingConv::CSRet) {
1361     const Type *StructTy =
1362       cast<PointerType>(F.arg_begin()->getType())->getElementType();
1363     Out << "  ";
1364     printType(Out, StructTy, "StructReturn");
1365     Out << ";  /* Struct return temporary */\n";
1366
1367     Out << "  ";
1368     printType(Out, F.arg_begin()->getType(), Mang->getValueName(F.arg_begin()));
1369     Out << " = &StructReturn;\n";
1370   }
1371
1372   bool PrintedVar = false;
1373   
1374   // print local variable information for the function
1375   for (inst_iterator I = inst_begin(&F), E = inst_end(&F); I != E; ++I)
1376     if (const AllocaInst *AI = isDirectAlloca(&*I)) {
1377       Out << "  ";
1378       printType(Out, AI->getAllocatedType(), Mang->getValueName(AI));
1379       Out << ";    /* Address-exposed local */\n";
1380       PrintedVar = true;
1381     } else if (I->getType() != Type::VoidTy && !isInlinableInst(*I)) {
1382       Out << "  ";
1383       printType(Out, I->getType(), Mang->getValueName(&*I));
1384       Out << ";\n";
1385
1386       if (isa<PHINode>(*I)) {  // Print out PHI node temporaries as well...
1387         Out << "  ";
1388         printType(Out, I->getType(),
1389                   Mang->getValueName(&*I)+"__PHI_TEMPORARY");
1390         Out << ";\n";
1391       }
1392       PrintedVar = true;
1393     }
1394
1395   if (PrintedVar)
1396     Out << '\n';
1397
1398   if (F.hasExternalLinkage() && F.getName() == "main")
1399     Out << "  CODE_FOR_MAIN();\n";
1400
1401   // print the basic blocks
1402   for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB) {
1403     if (Loop *L = LI->getLoopFor(BB)) {
1404       if (L->getHeader() == BB && L->getParentLoop() == 0)
1405         printLoop(L);
1406     } else {
1407       printBasicBlock(BB);
1408     }
1409   }
1410
1411   Out << "}\n\n";
1412 }
1413
1414 void CWriter::printLoop(Loop *L) {
1415   Out << "  do {     /* Syntactic loop '" << L->getHeader()->getName()
1416       << "' to make GCC happy */\n";
1417   for (unsigned i = 0, e = L->getBlocks().size(); i != e; ++i) {
1418     BasicBlock *BB = L->getBlocks()[i];
1419     Loop *BBLoop = LI->getLoopFor(BB);
1420     if (BBLoop == L)
1421       printBasicBlock(BB);
1422     else if (BB == BBLoop->getHeader() && BBLoop->getParentLoop() == L)
1423       printLoop(BBLoop);
1424   }
1425   Out << "  } while (1); /* end of syntactic loop '"
1426       << L->getHeader()->getName() << "' */\n";
1427 }
1428
1429 void CWriter::printBasicBlock(BasicBlock *BB) {
1430
1431   // Don't print the label for the basic block if there are no uses, or if
1432   // the only terminator use is the predecessor basic block's terminator.
1433   // We have to scan the use list because PHI nodes use basic blocks too but
1434   // do not require a label to be generated.
1435   //
1436   bool NeedsLabel = false;
1437   for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI)
1438     if (isGotoCodeNecessary(*PI, BB)) {
1439       NeedsLabel = true;
1440       break;
1441     }
1442
1443   if (NeedsLabel) Out << Mang->getValueName(BB) << ":\n";
1444
1445   // Output all of the instructions in the basic block...
1446   for (BasicBlock::iterator II = BB->begin(), E = --BB->end(); II != E;
1447        ++II) {
1448     if (!isInlinableInst(*II) && !isDirectAlloca(II)) {
1449       if (II->getType() != Type::VoidTy)
1450         outputLValue(II);
1451       else
1452         Out << "  ";
1453       visit(*II);
1454       Out << ";\n";
1455     }
1456   }
1457
1458   // Don't emit prefix or suffix for the terminator...
1459   visit(*BB->getTerminator());
1460 }
1461
1462
1463 // Specific Instruction type classes... note that all of the casts are
1464 // necessary because we use the instruction classes as opaque types...
1465 //
1466 void CWriter::visitReturnInst(ReturnInst &I) {
1467   // If this is a struct return function, return the temporary struct.
1468   if (I.getParent()->getParent()->getCallingConv() == CallingConv::CSRet) {
1469     Out << "  return StructReturn;\n";
1470     return;
1471   }
1472   
1473   // Don't output a void return if this is the last basic block in the function
1474   if (I.getNumOperands() == 0 &&
1475       &*--I.getParent()->getParent()->end() == I.getParent() &&
1476       !I.getParent()->size() == 1) {
1477     return;
1478   }
1479
1480   Out << "  return";
1481   if (I.getNumOperands()) {
1482     Out << ' ';
1483     writeOperand(I.getOperand(0));
1484   }
1485   Out << ";\n";
1486 }
1487
1488 void CWriter::visitSwitchInst(SwitchInst &SI) {
1489
1490   Out << "  switch (";
1491   writeOperand(SI.getOperand(0));
1492   Out << ") {\n  default:\n";
1493   printPHICopiesForSuccessor (SI.getParent(), SI.getDefaultDest(), 2);
1494   printBranchToBlock(SI.getParent(), SI.getDefaultDest(), 2);
1495   Out << ";\n";
1496   for (unsigned i = 2, e = SI.getNumOperands(); i != e; i += 2) {
1497     Out << "  case ";
1498     writeOperand(SI.getOperand(i));
1499     Out << ":\n";
1500     BasicBlock *Succ = cast<BasicBlock>(SI.getOperand(i+1));
1501     printPHICopiesForSuccessor (SI.getParent(), Succ, 2);
1502     printBranchToBlock(SI.getParent(), Succ, 2);
1503     if (Function::iterator(Succ) == next(Function::iterator(SI.getParent())))
1504       Out << "    break;\n";
1505   }
1506   Out << "  }\n";
1507 }
1508
1509 void CWriter::visitUnreachableInst(UnreachableInst &I) {
1510   Out << "  /*UNREACHABLE*/;\n";
1511 }
1512
1513 bool CWriter::isGotoCodeNecessary(BasicBlock *From, BasicBlock *To) {
1514   /// FIXME: This should be reenabled, but loop reordering safe!!
1515   return true;
1516
1517   if (next(Function::iterator(From)) != Function::iterator(To))
1518     return true;  // Not the direct successor, we need a goto.
1519
1520   //isa<SwitchInst>(From->getTerminator())
1521
1522   if (LI->getLoopFor(From) != LI->getLoopFor(To))
1523     return true;
1524   return false;
1525 }
1526
1527 void CWriter::printPHICopiesForSuccessor (BasicBlock *CurBlock,
1528                                           BasicBlock *Successor,
1529                                           unsigned Indent) {
1530   for (BasicBlock::iterator I = Successor->begin(); isa<PHINode>(I); ++I) {
1531     PHINode *PN = cast<PHINode>(I);
1532     // Now we have to do the printing.
1533     Value *IV = PN->getIncomingValueForBlock(CurBlock);
1534     if (!isa<UndefValue>(IV)) {
1535       Out << std::string(Indent, ' ');
1536       Out << "  " << Mang->getValueName(I) << "__PHI_TEMPORARY = ";
1537       writeOperand(IV);
1538       Out << ";   /* for PHI node */\n";
1539     }
1540   }
1541 }
1542
1543 void CWriter::printBranchToBlock(BasicBlock *CurBB, BasicBlock *Succ,
1544                                  unsigned Indent) {
1545   if (isGotoCodeNecessary(CurBB, Succ)) {
1546     Out << std::string(Indent, ' ') << "  goto ";
1547     writeOperand(Succ);
1548     Out << ";\n";
1549   }
1550 }
1551
1552 // Branch instruction printing - Avoid printing out a branch to a basic block
1553 // that immediately succeeds the current one.
1554 //
1555 void CWriter::visitBranchInst(BranchInst &I) {
1556
1557   if (I.isConditional()) {
1558     if (isGotoCodeNecessary(I.getParent(), I.getSuccessor(0))) {
1559       Out << "  if (";
1560       writeOperand(I.getCondition());
1561       Out << ") {\n";
1562
1563       printPHICopiesForSuccessor (I.getParent(), I.getSuccessor(0), 2);
1564       printBranchToBlock(I.getParent(), I.getSuccessor(0), 2);
1565
1566       if (isGotoCodeNecessary(I.getParent(), I.getSuccessor(1))) {
1567         Out << "  } else {\n";
1568         printPHICopiesForSuccessor (I.getParent(), I.getSuccessor(1), 2);
1569         printBranchToBlock(I.getParent(), I.getSuccessor(1), 2);
1570       }
1571     } else {
1572       // First goto not necessary, assume second one is...
1573       Out << "  if (!";
1574       writeOperand(I.getCondition());
1575       Out << ") {\n";
1576
1577       printPHICopiesForSuccessor (I.getParent(), I.getSuccessor(1), 2);
1578       printBranchToBlock(I.getParent(), I.getSuccessor(1), 2);
1579     }
1580
1581     Out << "  }\n";
1582   } else {
1583     printPHICopiesForSuccessor (I.getParent(), I.getSuccessor(0), 0);
1584     printBranchToBlock(I.getParent(), I.getSuccessor(0), 0);
1585   }
1586   Out << "\n";
1587 }
1588
1589 // PHI nodes get copied into temporary values at the end of predecessor basic
1590 // blocks.  We now need to copy these temporary values into the REAL value for
1591 // the PHI.
1592 void CWriter::visitPHINode(PHINode &I) {
1593   writeOperand(&I);
1594   Out << "__PHI_TEMPORARY";
1595 }
1596
1597
1598 void CWriter::visitBinaryOperator(Instruction &I) {
1599   // binary instructions, shift instructions, setCond instructions.
1600   assert(!isa<PointerType>(I.getType()));
1601
1602   // We must cast the results of binary operations which might be promoted.
1603   bool needsCast = false;
1604   if ((I.getType() == Type::UByteTy) || (I.getType() == Type::SByteTy)
1605       || (I.getType() == Type::UShortTy) || (I.getType() == Type::ShortTy)
1606       || (I.getType() == Type::FloatTy)) {
1607     needsCast = true;
1608     Out << "((";
1609     printType(Out, I.getType());
1610     Out << ")(";
1611   }
1612
1613   // If this is a negation operation, print it out as such.  For FP, we don't
1614   // want to print "-0.0 - X".
1615   if (BinaryOperator::isNeg(&I)) {
1616     Out << "-(";
1617     writeOperand(BinaryOperator::getNegArgument(cast<BinaryOperator>(&I)));
1618     Out << ")";
1619   } else if (I.getOpcode() == Instruction::Rem && 
1620              I.getType()->isFloatingPoint()) {
1621     // Output a call to fmod/fmodf instead of emitting a%b
1622     if (I.getType() == Type::FloatTy)
1623       Out << "fmodf(";
1624     else
1625       Out << "fmod(";
1626     writeOperand(I.getOperand(0));
1627     Out << ", ";
1628     writeOperand(I.getOperand(1));
1629     Out << ")";
1630   } else {
1631     writeOperand(I.getOperand(0));
1632
1633     switch (I.getOpcode()) {
1634     case Instruction::Add: Out << " + "; break;
1635     case Instruction::Sub: Out << " - "; break;
1636     case Instruction::Mul: Out << '*'; break;
1637     case Instruction::Div: Out << '/'; break;
1638     case Instruction::Rem: Out << '%'; break;
1639     case Instruction::And: Out << " & "; break;
1640     case Instruction::Or: Out << " | "; break;
1641     case Instruction::Xor: Out << " ^ "; break;
1642     case Instruction::SetEQ: Out << " == "; break;
1643     case Instruction::SetNE: Out << " != "; break;
1644     case Instruction::SetLE: Out << " <= "; break;
1645     case Instruction::SetGE: Out << " >= "; break;
1646     case Instruction::SetLT: Out << " < "; break;
1647     case Instruction::SetGT: Out << " > "; break;
1648     case Instruction::Shl : Out << " << "; break;
1649     case Instruction::Shr : Out << " >> "; break;
1650     default: std::cerr << "Invalid operator type!" << I; abort();
1651     }
1652
1653     writeOperand(I.getOperand(1));
1654   }
1655
1656   if (needsCast) {
1657     Out << "))";
1658   }
1659 }
1660
1661 void CWriter::visitCastInst(CastInst &I) {
1662   if (I.getType() == Type::BoolTy) {
1663     Out << '(';
1664     writeOperand(I.getOperand(0));
1665     Out << " != 0)";
1666     return;
1667   }
1668   Out << '(';
1669   printType(Out, I.getType());
1670   Out << ')';
1671   if (isa<PointerType>(I.getType())&&I.getOperand(0)->getType()->isIntegral() ||
1672       isa<PointerType>(I.getOperand(0)->getType())&&I.getType()->isIntegral()) {
1673     // Avoid "cast to pointer from integer of different size" warnings
1674     Out << "(long)";
1675   }
1676
1677   writeOperand(I.getOperand(0));
1678 }
1679
1680 void CWriter::visitSelectInst(SelectInst &I) {
1681   Out << "((";
1682   writeOperand(I.getCondition());
1683   Out << ") ? (";
1684   writeOperand(I.getTrueValue());
1685   Out << ") : (";
1686   writeOperand(I.getFalseValue());
1687   Out << "))";
1688 }
1689
1690
1691 void CWriter::lowerIntrinsics(Function &F) {
1692   for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
1693     for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; )
1694       if (CallInst *CI = dyn_cast<CallInst>(I++))
1695         if (Function *F = CI->getCalledFunction())
1696           switch (F->getIntrinsicID()) {
1697           case Intrinsic::not_intrinsic:
1698           case Intrinsic::vastart:
1699           case Intrinsic::vacopy:
1700           case Intrinsic::vaend:
1701           case Intrinsic::returnaddress:
1702           case Intrinsic::frameaddress:
1703           case Intrinsic::setjmp:
1704           case Intrinsic::longjmp:
1705           case Intrinsic::prefetch:
1706           case Intrinsic::dbg_stoppoint:
1707           case Intrinsic::powi_f32:
1708           case Intrinsic::powi_f64:
1709             // We directly implement these intrinsics
1710             break;
1711           default:
1712             // If this is an intrinsic that directly corresponds to a GCC
1713             // builtin, we handle it.
1714             const char *BuiltinName = "";
1715 #define GET_GCC_BUILTIN_NAME
1716 #include "llvm/Intrinsics.gen"
1717 #undef GET_GCC_BUILTIN_NAME
1718             // If we handle it, don't lower it.
1719             if (BuiltinName[0]) break;
1720             
1721             // All other intrinsic calls we must lower.
1722             Instruction *Before = 0;
1723             if (CI != &BB->front())
1724               Before = prior(BasicBlock::iterator(CI));
1725
1726             IL.LowerIntrinsicCall(CI);
1727             if (Before) {        // Move iterator to instruction after call
1728               I = Before; ++I;
1729             } else {
1730               I = BB->begin();
1731             }
1732             break;
1733           }
1734 }
1735
1736
1737
1738 void CWriter::visitCallInst(CallInst &I) {
1739   bool WroteCallee = false;
1740
1741   // Handle intrinsic function calls first...
1742   if (Function *F = I.getCalledFunction())
1743     if (Intrinsic::ID ID = (Intrinsic::ID)F->getIntrinsicID()) {
1744       switch (ID) {
1745       default: {
1746         // If this is an intrinsic that directly corresponds to a GCC
1747         // builtin, we emit it here.
1748         const char *BuiltinName = "";
1749 #define GET_GCC_BUILTIN_NAME
1750 #include "llvm/Intrinsics.gen"
1751 #undef GET_GCC_BUILTIN_NAME
1752         assert(BuiltinName[0] && "Unknown LLVM intrinsic!");
1753
1754         Out << BuiltinName;
1755         WroteCallee = true;
1756         break;
1757       }
1758       case Intrinsic::vastart:
1759         Out << "0; ";
1760
1761         Out << "va_start(*(va_list*)";
1762         writeOperand(I.getOperand(1));
1763         Out << ", ";
1764         // Output the last argument to the enclosing function...
1765         if (I.getParent()->getParent()->arg_empty()) {
1766           std::cerr << "The C backend does not currently support zero "
1767                     << "argument varargs functions, such as '"
1768                     << I.getParent()->getParent()->getName() << "'!\n";
1769           abort();
1770         }
1771         writeOperand(--I.getParent()->getParent()->arg_end());
1772         Out << ')';
1773         return;
1774       case Intrinsic::vaend:
1775         if (!isa<ConstantPointerNull>(I.getOperand(1))) {
1776           Out << "0; va_end(*(va_list*)";
1777           writeOperand(I.getOperand(1));
1778           Out << ')';
1779         } else {
1780           Out << "va_end(*(va_list*)0)";
1781         }
1782         return;
1783       case Intrinsic::vacopy:
1784         Out << "0; ";
1785         Out << "va_copy(*(va_list*)";
1786         writeOperand(I.getOperand(1));
1787         Out << ", *(va_list*)";
1788         writeOperand(I.getOperand(2));
1789         Out << ')';
1790         return;
1791       case Intrinsic::returnaddress:
1792         Out << "__builtin_return_address(";
1793         writeOperand(I.getOperand(1));
1794         Out << ')';
1795         return;
1796       case Intrinsic::frameaddress:
1797         Out << "__builtin_frame_address(";
1798         writeOperand(I.getOperand(1));
1799         Out << ')';
1800         return;
1801       case Intrinsic::powi_f32:
1802       case Intrinsic::powi_f64:
1803         Out << "__builtin_powi(";
1804         writeOperand(I.getOperand(1));
1805         Out << ", ";
1806         writeOperand(I.getOperand(2));
1807         Out << ')';
1808         return;
1809       case Intrinsic::setjmp:
1810 #if defined(HAVE__SETJMP) && defined(HAVE__LONGJMP)
1811         Out << "_";  // Use _setjmp on systems that support it!
1812 #endif
1813         Out << "setjmp(*(jmp_buf*)";
1814         writeOperand(I.getOperand(1));
1815         Out << ')';
1816         return;
1817       case Intrinsic::longjmp:
1818 #if defined(HAVE__SETJMP) && defined(HAVE__LONGJMP)
1819         Out << "_";  // Use _longjmp on systems that support it!
1820 #endif
1821         Out << "longjmp(*(jmp_buf*)";
1822         writeOperand(I.getOperand(1));
1823         Out << ", ";
1824         writeOperand(I.getOperand(2));
1825         Out << ')';
1826         return;
1827       case Intrinsic::prefetch:
1828         Out << "LLVM_PREFETCH((const void *)";
1829         writeOperand(I.getOperand(1));
1830         Out << ", ";
1831         writeOperand(I.getOperand(2));
1832         Out << ", ";
1833         writeOperand(I.getOperand(3));
1834         Out << ")";
1835         return;
1836       case Intrinsic::dbg_stoppoint: {
1837         // If we use writeOperand directly we get a "u" suffix which is rejected
1838         // by gcc.
1839         DbgStopPointInst &SPI = cast<DbgStopPointInst>(I);
1840
1841         Out << "\n#line "
1842             << SPI.getLine()
1843             << " \"" << SPI.getDirectory()
1844             << SPI.getFileName() << "\"\n";
1845         return;
1846       }
1847       }
1848     }
1849
1850   Value *Callee = I.getCalledValue();
1851
1852   // If this is a call to a struct-return function, assign to the first
1853   // parameter instead of passing it to the call.
1854   bool isStructRet = I.getCallingConv() == CallingConv::CSRet;
1855   if (isStructRet) {
1856     Out << "*(";
1857     writeOperand(I.getOperand(1));
1858     Out << ") = ";
1859   }
1860   
1861   if (I.isTailCall()) Out << " /*tail*/ ";
1862
1863   const PointerType  *PTy   = cast<PointerType>(Callee->getType());
1864   const FunctionType *FTy   = cast<FunctionType>(PTy->getElementType());
1865   
1866   if (!WroteCallee) {
1867     // If this is an indirect call to a struct return function, we need to cast
1868     // the pointer.
1869     bool NeedsCast = isStructRet && !isa<Function>(Callee);
1870
1871     // GCC is a real PITA.  It does not permit codegening casts of functions to
1872     // function pointers if they are in a call (it generates a trap instruction
1873     // instead!).  We work around this by inserting a cast to void* in between
1874     // the function and the function pointer cast.  Unfortunately, we can't just
1875     // form the constant expression here, because the folder will immediately
1876     // nuke it.
1877     //
1878     // Note finally, that this is completely unsafe.  ANSI C does not guarantee
1879     // that void* and function pointers have the same size. :( To deal with this
1880     // in the common case, we handle casts where the number of arguments passed
1881     // match exactly.
1882     //
1883     if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Callee))
1884       if (CE->getOpcode() == Instruction::Cast)
1885         if (Function *RF = dyn_cast<Function>(CE->getOperand(0))) {
1886           NeedsCast = true;
1887           Callee = RF;
1888         }
1889   
1890     if (NeedsCast) {
1891       // Ok, just cast the pointer type.
1892       Out << "((";
1893       if (!isStructRet)
1894         printType(Out, I.getCalledValue()->getType());
1895       else
1896         printStructReturnPointerFunctionType(Out, 
1897                              cast<PointerType>(I.getCalledValue()->getType()));
1898       Out << ")(void*)";
1899     }
1900     writeOperand(Callee);
1901     if (NeedsCast) Out << ')';
1902   }
1903
1904   Out << '(';
1905
1906   unsigned NumDeclaredParams = FTy->getNumParams();
1907
1908   CallSite::arg_iterator AI = I.op_begin()+1, AE = I.op_end();
1909   unsigned ArgNo = 0;
1910   if (isStructRet) {   // Skip struct return argument.
1911     ++AI;
1912     ++ArgNo;
1913   }
1914       
1915   bool PrintedArg = false;
1916   for (; AI != AE; ++AI, ++ArgNo) {
1917     if (PrintedArg) Out << ", ";
1918     if (ArgNo < NumDeclaredParams &&
1919         (*AI)->getType() != FTy->getParamType(ArgNo)) {
1920       Out << '(';
1921       printType(Out, FTy->getParamType(ArgNo));
1922       Out << ')';
1923     }
1924     writeOperand(*AI);
1925     PrintedArg = true;
1926   }
1927   Out << ')';
1928 }
1929
1930 void CWriter::visitMallocInst(MallocInst &I) {
1931   assert(0 && "lowerallocations pass didn't work!");
1932 }
1933
1934 void CWriter::visitAllocaInst(AllocaInst &I) {
1935   Out << '(';
1936   printType(Out, I.getType());
1937   Out << ") alloca(sizeof(";
1938   printType(Out, I.getType()->getElementType());
1939   Out << ')';
1940   if (I.isArrayAllocation()) {
1941     Out << " * " ;
1942     writeOperand(I.getOperand(0));
1943   }
1944   Out << ')';
1945 }
1946
1947 void CWriter::visitFreeInst(FreeInst &I) {
1948   assert(0 && "lowerallocations pass didn't work!");
1949 }
1950
1951 void CWriter::printIndexingExpression(Value *Ptr, gep_type_iterator I,
1952                                       gep_type_iterator E) {
1953   bool HasImplicitAddress = false;
1954   // If accessing a global value with no indexing, avoid *(&GV) syndrome
1955   if (GlobalValue *V = dyn_cast<GlobalValue>(Ptr)) {
1956     HasImplicitAddress = true;
1957   } else if (isDirectAlloca(Ptr)) {
1958     HasImplicitAddress = true;
1959   }
1960
1961   if (I == E) {
1962     if (!HasImplicitAddress)
1963       Out << '*';  // Implicit zero first argument: '*x' is equivalent to 'x[0]'
1964
1965     writeOperandInternal(Ptr);
1966     return;
1967   }
1968
1969   const Constant *CI = dyn_cast<Constant>(I.getOperand());
1970   if (HasImplicitAddress && (!CI || !CI->isNullValue()))
1971     Out << "(&";
1972
1973   writeOperandInternal(Ptr);
1974
1975   if (HasImplicitAddress && (!CI || !CI->isNullValue())) {
1976     Out << ')';
1977     HasImplicitAddress = false;  // HIA is only true if we haven't addressed yet
1978   }
1979
1980   assert(!HasImplicitAddress || (CI && CI->isNullValue()) &&
1981          "Can only have implicit address with direct accessing");
1982
1983   if (HasImplicitAddress) {
1984     ++I;
1985   } else if (CI && CI->isNullValue()) {
1986     gep_type_iterator TmpI = I; ++TmpI;
1987
1988     // Print out the -> operator if possible...
1989     if (TmpI != E && isa<StructType>(*TmpI)) {
1990       Out << (HasImplicitAddress ? "." : "->");
1991       Out << "field" << cast<ConstantUInt>(TmpI.getOperand())->getValue();
1992       I = ++TmpI;
1993     }
1994   }
1995
1996   for (; I != E; ++I)
1997     if (isa<StructType>(*I)) {
1998       Out << ".field" << cast<ConstantUInt>(I.getOperand())->getValue();
1999     } else {
2000       Out << '[';
2001       writeOperand(I.getOperand());
2002       Out << ']';
2003     }
2004 }
2005
2006 void CWriter::visitLoadInst(LoadInst &I) {
2007   Out << '*';
2008   if (I.isVolatile()) {
2009     Out << "((";
2010     printType(Out, I.getType(), "volatile*");
2011     Out << ")";
2012   }
2013
2014   writeOperand(I.getOperand(0));
2015
2016   if (I.isVolatile())
2017     Out << ')';
2018 }
2019
2020 void CWriter::visitStoreInst(StoreInst &I) {
2021   Out << '*';
2022   if (I.isVolatile()) {
2023     Out << "((";
2024     printType(Out, I.getOperand(0)->getType(), " volatile*");
2025     Out << ")";
2026   }
2027   writeOperand(I.getPointerOperand());
2028   if (I.isVolatile()) Out << ')';
2029   Out << " = ";
2030   writeOperand(I.getOperand(0));
2031 }
2032
2033 void CWriter::visitGetElementPtrInst(GetElementPtrInst &I) {
2034   Out << '&';
2035   printIndexingExpression(I.getPointerOperand(), gep_type_begin(I),
2036                           gep_type_end(I));
2037 }
2038
2039 void CWriter::visitVAArgInst(VAArgInst &I) {
2040   Out << "va_arg(*(va_list*)";
2041   writeOperand(I.getOperand(0));
2042   Out << ", ";
2043   printType(Out, I.getType());
2044   Out << ");\n ";
2045 }
2046
2047 //===----------------------------------------------------------------------===//
2048 //                       External Interface declaration
2049 //===----------------------------------------------------------------------===//
2050
2051 bool CTargetMachine::addPassesToEmitWholeFile(PassManager &PM,
2052                                               std::ostream &o,
2053                                               CodeGenFileType FileType,
2054                                               bool Fast) {
2055   if (FileType != TargetMachine::AssemblyFile) return true;
2056
2057   PM.add(createLowerGCPass());
2058   PM.add(createLowerAllocationsPass(true));
2059   PM.add(createLowerInvokePass());
2060   PM.add(createCFGSimplificationPass());   // clean up after lower invoke.
2061   PM.add(new CBackendNameAllUsedStructsAndMergeFunctions());
2062   PM.add(new CWriter(o));
2063   return false;
2064 }