Fixes for PR258 and PR259.
[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/Target/TargetMachineImpls.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/IntrinsicLowering.h"
26 #include "llvm/Analysis/FindUsedTypes.h"
27 #include "llvm/Analysis/ConstantsScanner.h"
28 #include "llvm/Transforms/Scalar.h"
29 #include "llvm/Support/CallSite.h"
30 #include "llvm/Support/GetElementPtrTypeIterator.h"
31 #include "llvm/Support/InstVisitor.h"
32 #include "llvm/Support/Mangler.h"
33 #include "Support/StringExtras.h"
34 #include "Config/config.h"
35 #include <algorithm>
36 #include <sstream>
37 using namespace llvm;
38
39 namespace {
40   class CWriter : public Pass, public InstVisitor<CWriter> {
41     std::ostream &Out; 
42     IntrinsicLowering &IL;
43     Mangler *Mang;
44     const Module *TheModule;
45     FindUsedTypes *FUT;
46
47     std::map<const Type *, std::string> TypeNames;
48
49     std::map<const ConstantFP *, unsigned> FPConstantMap;
50   public:
51     CWriter(std::ostream &o, IntrinsicLowering &il) : Out(o), IL(il) {}
52
53     void getAnalysisUsage(AnalysisUsage &AU) const {
54       AU.addRequired<FindUsedTypes>();
55     }
56
57     virtual const char *getPassName() const { return "C backend"; }
58
59     bool doInitialization(Module &M);
60     bool run(Module &M) {
61       // First pass, lower all unhandled intrinsics.
62       lowerIntrinsics(M);
63
64       doInitialization(M);
65
66       for (Module::iterator I = M.begin(), E = M.end(); I != E; ++I)
67         if (!I->isExternal())
68           printFunction(*I);
69
70       // Free memory...
71       delete Mang;
72       TypeNames.clear();
73       return true;
74     }
75
76     std::ostream &printType(std::ostream &Out, const Type *Ty,
77                             const std::string &VariableName = "",
78                             bool IgnoreName = false);
79
80     void writeOperand(Value *Operand);
81     void writeOperandInternal(Value *Operand);
82
83   private :
84     void lowerIntrinsics(Module &M);
85
86     bool nameAllUsedStructureTypes(Module &M);
87     void printModule(Module *M);
88     void printFloatingPointConstants(Module &M);
89     void printSymbolTable(const SymbolTable &ST);
90     void printContainedStructs(const Type *Ty, std::set<const StructType *> &);
91     void printFunctionSignature(const Function *F, bool Prototype);
92
93     void printFunction(Function &);
94
95     void printConstant(Constant *CPV);
96     void printConstantArray(ConstantArray *CPA);
97
98     // isInlinableInst - Attempt to inline instructions into their uses to build
99     // trees as much as possible.  To do this, we have to consistently decide
100     // what is acceptable to inline, so that variable declarations don't get
101     // printed and an extra copy of the expr is not emitted.
102     //
103     static bool isInlinableInst(const Instruction &I) {
104       // Must be an expression, must be used exactly once.  If it is dead, we
105       // emit it inline where it would go.
106       if (I.getType() == Type::VoidTy || !I.hasOneUse() ||
107           isa<TerminatorInst>(I) || isa<CallInst>(I) || isa<PHINode>(I) || 
108           isa<LoadInst>(I) || isa<VAArgInst>(I) || isa<VANextInst>(I))
109         // Don't inline a load across a store or other bad things!
110         return false;
111
112       // Only inline instruction it it's use is in the same BB as the inst.
113       return I.getParent() == cast<Instruction>(I.use_back())->getParent();
114     }
115
116     // isDirectAlloca - Define fixed sized allocas in the entry block as direct
117     // variables which are accessed with the & operator.  This causes GCC to
118     // generate significantly better code than to emit alloca calls directly.
119     //
120     static const AllocaInst *isDirectAlloca(const Value *V) {
121       const AllocaInst *AI = dyn_cast<AllocaInst>(V);
122       if (!AI) return false;
123       if (AI->isArrayAllocation())
124         return 0;   // FIXME: we can also inline fixed size array allocas!
125       if (AI->getParent() != &AI->getParent()->getParent()->getEntryBlock())
126         return 0;
127       return AI;
128     }
129
130     // Instruction visitation functions
131     friend class InstVisitor<CWriter>;
132
133     void visitReturnInst(ReturnInst &I);
134     void visitBranchInst(BranchInst &I);
135     void visitSwitchInst(SwitchInst &I);
136     void visitInvokeInst(InvokeInst &I);
137     void visitUnwindInst(UnwindInst &I);
138
139     void visitPHINode(PHINode &I);
140     void visitBinaryOperator(Instruction &I);
141
142     void visitCastInst (CastInst &I);
143     void visitCallInst (CallInst &I);
144     void visitCallSite (CallSite CS);
145     void visitShiftInst(ShiftInst &I) { visitBinaryOperator(I); }
146
147     void visitMallocInst(MallocInst &I);
148     void visitAllocaInst(AllocaInst &I);
149     void visitFreeInst  (FreeInst   &I);
150     void visitLoadInst  (LoadInst   &I);
151     void visitStoreInst (StoreInst  &I);
152     void visitGetElementPtrInst(GetElementPtrInst &I);
153     void visitVANextInst(VANextInst &I);
154     void visitVAArgInst (VAArgInst &I);
155
156     void visitInstruction(Instruction &I) {
157       std::cerr << "C Writer does not know about " << I;
158       abort();
159     }
160
161     void outputLValue(Instruction *I) {
162       Out << "  " << Mang->getValueName(I) << " = ";
163     }
164     void printBranchToBlock(BasicBlock *CurBlock, BasicBlock *SuccBlock,
165                             unsigned Indent);
166     void printIndexingExpression(Value *Ptr, gep_type_iterator I,
167                                  gep_type_iterator E);
168   };
169 }
170
171 // Pass the Type* and the variable name and this prints out the variable
172 // declaration.
173 //
174 std::ostream &CWriter::printType(std::ostream &Out, const Type *Ty,
175                                  const std::string &NameSoFar,
176                                  bool IgnoreName) {
177   if (Ty->isPrimitiveType())
178     switch (Ty->getPrimitiveID()) {
179     case Type::VoidTyID:   return Out << "void "               << NameSoFar;
180     case Type::BoolTyID:   return Out << "bool "               << NameSoFar;
181     case Type::UByteTyID:  return Out << "unsigned char "      << NameSoFar;
182     case Type::SByteTyID:  return Out << "signed char "        << NameSoFar;
183     case Type::UShortTyID: return Out << "unsigned short "     << NameSoFar;
184     case Type::ShortTyID:  return Out << "short "              << NameSoFar;
185     case Type::UIntTyID:   return Out << "unsigned "           << NameSoFar;
186     case Type::IntTyID:    return Out << "int "                << NameSoFar;
187     case Type::ULongTyID:  return Out << "unsigned long long " << NameSoFar;
188     case Type::LongTyID:   return Out << "signed long long "   << NameSoFar;
189     case Type::FloatTyID:  return Out << "float "              << NameSoFar;
190     case Type::DoubleTyID: return Out << "double "             << NameSoFar;
191     default :
192       std::cerr << "Unknown primitive type: " << Ty << "\n";
193       abort();
194     }
195   
196   // Check to see if the type is named.
197   if (!IgnoreName || isa<OpaqueType>(Ty)) {
198     std::map<const Type *, std::string>::iterator I = TypeNames.find(Ty);
199     if (I != TypeNames.end()) return Out << I->second << " " << NameSoFar;
200   }
201
202   switch (Ty->getPrimitiveID()) {
203   case Type::FunctionTyID: {
204     const FunctionType *MTy = cast<FunctionType>(Ty);
205     std::stringstream FunctionInnards; 
206     FunctionInnards << " (" << NameSoFar << ") (";
207     for (FunctionType::param_iterator I = MTy->param_begin(),
208            E = MTy->param_end(); I != E; ++I) {
209       if (I != MTy->param_begin())
210         FunctionInnards << ", ";
211       printType(FunctionInnards, *I, "");
212     }
213     if (MTy->isVarArg()) {
214       if (MTy->getNumParams()) 
215         FunctionInnards << ", ...";
216     } else if (!MTy->getNumParams()) {
217       FunctionInnards << "void";
218     }
219     FunctionInnards << ")";
220     std::string tstr = FunctionInnards.str();
221     printType(Out, MTy->getReturnType(), tstr);
222     return Out;
223   }
224   case Type::StructTyID: {
225     const StructType *STy = cast<StructType>(Ty);
226     Out << NameSoFar + " {\n";
227     unsigned Idx = 0;
228     for (StructType::element_iterator I = STy->element_begin(),
229            E = STy->element_end(); I != E; ++I) {
230       Out << "  ";
231       printType(Out, *I, "field" + utostr(Idx++));
232       Out << ";\n";
233     }
234     return Out << "}";
235   }  
236
237   case Type::PointerTyID: {
238     const PointerType *PTy = cast<PointerType>(Ty);
239     std::string ptrName = "*" + NameSoFar;
240
241     if (isa<ArrayType>(PTy->getElementType()))
242       ptrName = "(" + ptrName + ")";
243
244     return printType(Out, PTy->getElementType(), ptrName);
245   }
246
247   case Type::ArrayTyID: {
248     const ArrayType *ATy = cast<ArrayType>(Ty);
249     unsigned NumElements = ATy->getNumElements();
250     return printType(Out, ATy->getElementType(),
251                      NameSoFar + "[" + utostr(NumElements) + "]");
252   }
253
254   case Type::OpaqueTyID: {
255     static int Count = 0;
256     std::string TyName = "struct opaque_" + itostr(Count++);
257     assert(TypeNames.find(Ty) == TypeNames.end());
258     TypeNames[Ty] = TyName;
259     return Out << TyName << " " << NameSoFar;
260   }
261   default:
262     assert(0 && "Unhandled case in getTypeProps!");
263     abort();
264   }
265
266   return Out;
267 }
268
269 void CWriter::printConstantArray(ConstantArray *CPA) {
270
271   // As a special case, print the array as a string if it is an array of
272   // ubytes or an array of sbytes with positive values.
273   // 
274   const Type *ETy = CPA->getType()->getElementType();
275   bool isString = (ETy == Type::SByteTy || ETy == Type::UByteTy);
276
277   // Make sure the last character is a null char, as automatically added by C
278   if (isString && (CPA->getNumOperands() == 0 ||
279                    !cast<Constant>(*(CPA->op_end()-1))->isNullValue()))
280     isString = false;
281   
282   if (isString) {
283     Out << "\"";
284     // Keep track of whether the last number was a hexadecimal escape
285     bool LastWasHex = false;
286
287     // Do not include the last character, which we know is null
288     for (unsigned i = 0, e = CPA->getNumOperands()-1; i != e; ++i) {
289       unsigned char C = cast<ConstantInt>(CPA->getOperand(i))->getRawValue();
290       
291       // Print it out literally if it is a printable character.  The only thing
292       // to be careful about is when the last letter output was a hex escape
293       // code, in which case we have to be careful not to print out hex digits
294       // explicitly (the C compiler thinks it is a continuation of the previous
295       // character, sheesh...)
296       //
297       if (isprint(C) && (!LastWasHex || !isxdigit(C))) {
298         LastWasHex = false;
299         if (C == '"' || C == '\\')
300           Out << "\\" << C;
301         else
302           Out << C;
303       } else {
304         LastWasHex = false;
305         switch (C) {
306         case '\n': Out << "\\n"; break;
307         case '\t': Out << "\\t"; break;
308         case '\r': Out << "\\r"; break;
309         case '\v': Out << "\\v"; break;
310         case '\a': Out << "\\a"; break;
311         case '\"': Out << "\\\""; break;
312         case '\'': Out << "\\\'"; break;           
313         default:
314           Out << "\\x";
315           Out << (char)(( C/16  < 10) ? ( C/16 +'0') : ( C/16 -10+'A'));
316           Out << (char)(((C&15) < 10) ? ((C&15)+'0') : ((C&15)-10+'A'));
317           LastWasHex = true;
318           break;
319         }
320       }
321     }
322     Out << "\"";
323   } else {
324     Out << "{";
325     if (CPA->getNumOperands()) {
326       Out << " ";
327       printConstant(cast<Constant>(CPA->getOperand(0)));
328       for (unsigned i = 1, e = CPA->getNumOperands(); i != e; ++i) {
329         Out << ", ";
330         printConstant(cast<Constant>(CPA->getOperand(i)));
331       }
332     }
333     Out << " }";
334   }
335 }
336
337 // isFPCSafeToPrint - Returns true if we may assume that CFP may be written out
338 // textually as a double (rather than as a reference to a stack-allocated
339 // variable). We decide this by converting CFP to a string and back into a
340 // double, and then checking whether the conversion results in a bit-equal
341 // double to the original value of CFP. This depends on us and the target C
342 // compiler agreeing on the conversion process (which is pretty likely since we
343 // only deal in IEEE FP).
344 //
345 bool isFPCSafeToPrint(const ConstantFP *CFP) {
346 #if HAVE_PRINTF_A
347   char Buffer[100];
348   sprintf(Buffer, "%a", CFP->getValue());
349
350   if (!strncmp(Buffer, "0x", 2) ||
351       !strncmp(Buffer, "-0x", 3) ||
352       !strncmp(Buffer, "+0x", 3))
353     return atof(Buffer) == CFP->getValue();
354   return false;
355 #else
356   std::string StrVal = ftostr(CFP->getValue());
357
358   while (StrVal[0] == ' ')
359     StrVal.erase(StrVal.begin());
360
361   // Check to make sure that the stringized number is not some string like "Inf"
362   // or NaN.  Check that the string matches the "[-+]?[0-9]" regex.
363   if ((StrVal[0] >= '0' && StrVal[0] <= '9') ||
364       ((StrVal[0] == '-' || StrVal[0] == '+') &&
365        (StrVal[1] >= '0' && StrVal[1] <= '9')))
366     // Reparse stringized version!
367     return atof(StrVal.c_str()) == CFP->getValue();
368   return false;
369 #endif
370 }
371
372 // printConstant - The LLVM Constant to C Constant converter.
373 void CWriter::printConstant(Constant *CPV) {
374   if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(CPV)) {
375     switch (CE->getOpcode()) {
376     case Instruction::Cast:
377       Out << "((";
378       printType(Out, CPV->getType());
379       Out << ")";
380       printConstant(CE->getOperand(0));
381       Out << ")";
382       return;
383
384     case Instruction::GetElementPtr:
385       Out << "(&(";
386       printIndexingExpression(CE->getOperand(0), gep_type_begin(CPV),
387                               gep_type_end(CPV));
388       Out << "))";
389       return;
390     case Instruction::Add:
391     case Instruction::Sub:
392     case Instruction::Mul:
393     case Instruction::Div:
394     case Instruction::Rem:
395     case Instruction::SetEQ:
396     case Instruction::SetNE:
397     case Instruction::SetLT:
398     case Instruction::SetLE:
399     case Instruction::SetGT:
400     case Instruction::SetGE:
401     case Instruction::Shl:
402     case Instruction::Shr:
403       Out << "(";
404       printConstant(CE->getOperand(0));
405       switch (CE->getOpcode()) {
406       case Instruction::Add: Out << " + "; break;
407       case Instruction::Sub: Out << " - "; break;
408       case Instruction::Mul: Out << " * "; break;
409       case Instruction::Div: Out << " / "; break;
410       case Instruction::Rem: Out << " % "; break;
411       case Instruction::SetEQ: Out << " == "; break;
412       case Instruction::SetNE: Out << " != "; break;
413       case Instruction::SetLT: Out << " < "; break;
414       case Instruction::SetLE: Out << " <= "; break;
415       case Instruction::SetGT: Out << " > "; break;
416       case Instruction::SetGE: Out << " >= "; break;
417       case Instruction::Shl: Out << " << "; break;
418       case Instruction::Shr: Out << " >> "; break;
419       default: assert(0 && "Illegal opcode here!");
420       }
421       printConstant(CE->getOperand(1));
422       Out << ")";
423       return;
424
425     default:
426       std::cerr << "CWriter Error: Unhandled constant expression: "
427                 << CE << "\n";
428       abort();
429     }
430   }
431
432   switch (CPV->getType()->getPrimitiveID()) {
433   case Type::BoolTyID:
434     Out << (CPV == ConstantBool::False ? "0" : "1"); break;
435   case Type::SByteTyID:
436   case Type::ShortTyID:
437     Out << cast<ConstantSInt>(CPV)->getValue(); break;
438   case Type::IntTyID:
439     if ((int)cast<ConstantSInt>(CPV)->getValue() == (int)0x80000000)
440       Out << "((int)0x80000000)";   // Handle MININT specially to avoid warning
441     else
442       Out << cast<ConstantSInt>(CPV)->getValue();
443     break;
444
445   case Type::LongTyID:
446     Out << cast<ConstantSInt>(CPV)->getValue() << "ll"; break;
447
448   case Type::UByteTyID:
449   case Type::UShortTyID:
450     Out << cast<ConstantUInt>(CPV)->getValue(); break;
451   case Type::UIntTyID:
452     Out << cast<ConstantUInt>(CPV)->getValue() << "u"; break;
453   case Type::ULongTyID:
454     Out << cast<ConstantUInt>(CPV)->getValue() << "ull"; break;
455
456   case Type::FloatTyID:
457   case Type::DoubleTyID: {
458     ConstantFP *FPC = cast<ConstantFP>(CPV);
459     std::map<const ConstantFP*, unsigned>::iterator I = FPConstantMap.find(FPC);
460     if (I != FPConstantMap.end()) {
461       // Because of FP precision problems we must load from a stack allocated
462       // value that holds the value in hex.
463       Out << "(*(" << (FPC->getType() == Type::FloatTy ? "float" : "double")
464           << "*)&FPConstant" << I->second << ")";
465     } else {
466 #if HAVE_PRINTF_A
467       // Print out the constant as a floating point number.
468       char Buffer[100];
469       sprintf(Buffer, "%a", FPC->getValue());
470       Out << Buffer << " /*" << FPC->getValue() << "*/ ";
471 #else
472       Out << ftostr(FPC->getValue());
473 #endif
474     }
475     break;
476   }
477
478   case Type::ArrayTyID:
479     if (isa<ConstantAggregateZero>(CPV)) {
480       const ArrayType *AT = cast<ArrayType>(CPV->getType());
481       Out << "{";
482       if (AT->getNumElements()) {
483         Out << " ";
484         Constant *CZ = Constant::getNullValue(AT->getElementType());
485         printConstant(CZ);
486         for (unsigned i = 1, e = AT->getNumElements(); i != e; ++i) {
487           Out << ", ";
488           printConstant(CZ);
489         }
490       }
491       Out << " }";
492     } else {
493       printConstantArray(cast<ConstantArray>(CPV));
494     }
495     break;
496
497   case Type::StructTyID:
498     if (isa<ConstantAggregateZero>(CPV)) {
499       const StructType *ST = cast<StructType>(CPV->getType());
500       Out << "{";
501       if (ST->getNumElements()) {
502         Out << " ";
503         printConstant(Constant::getNullValue(ST->getElementType(0)));
504         for (unsigned i = 1, e = ST->getNumElements(); i != e; ++i) {
505           Out << ", ";
506           printConstant(Constant::getNullValue(ST->getElementType(i)));
507         }
508       }
509       Out << " }";
510     } else {
511       Out << "{";
512       if (CPV->getNumOperands()) {
513         Out << " ";
514         printConstant(cast<Constant>(CPV->getOperand(0)));
515         for (unsigned i = 1, e = CPV->getNumOperands(); i != e; ++i) {
516           Out << ", ";
517           printConstant(cast<Constant>(CPV->getOperand(i)));
518         }
519       }
520       Out << " }";
521     }
522     break;
523
524   case Type::PointerTyID:
525     if (isa<ConstantPointerNull>(CPV)) {
526       Out << "((";
527       printType(Out, CPV->getType());
528       Out << ")/*NULL*/0)";
529       break;
530     } else if (ConstantPointerRef *CPR = dyn_cast<ConstantPointerRef>(CPV)) {
531       writeOperand(CPR->getValue());
532       break;
533     }
534     // FALL THROUGH
535   default:
536     std::cerr << "Unknown constant type: " << CPV << "\n";
537     abort();
538   }
539 }
540
541 void CWriter::writeOperandInternal(Value *Operand) {
542   if (Instruction *I = dyn_cast<Instruction>(Operand))
543     if (isInlinableInst(*I) && !isDirectAlloca(I)) {
544       // Should we inline this instruction to build a tree?
545       Out << "(";
546       visit(*I);
547       Out << ")";    
548       return;
549     }
550   
551   if (Constant *CPV = dyn_cast<Constant>(Operand)) {
552     printConstant(CPV); 
553   } else {
554     Out << Mang->getValueName(Operand);
555   }
556 }
557
558 void CWriter::writeOperand(Value *Operand) {
559   if (isa<GlobalVariable>(Operand) || isDirectAlloca(Operand))
560     Out << "(&";  // Global variables are references as their addresses by llvm
561
562   writeOperandInternal(Operand);
563
564   if (isa<GlobalVariable>(Operand) || isDirectAlloca(Operand))
565     Out << ")";
566 }
567
568 // nameAllUsedStructureTypes - If there are structure types in the module that
569 // are used but do not have names assigned to them in the symbol table yet then
570 // we assign them names now.
571 //
572 bool CWriter::nameAllUsedStructureTypes(Module &M) {
573   // Get a set of types that are used by the program...
574   std::set<const Type *> UT = FUT->getTypes();
575
576   // Loop over the module symbol table, removing types from UT that are already
577   // named.
578   //
579   SymbolTable &MST = M.getSymbolTable();
580   if (MST.find(Type::TypeTy) != MST.end())
581     for (SymbolTable::type_iterator I = MST.type_begin(Type::TypeTy),
582            E = MST.type_end(Type::TypeTy); I != E; ++I)
583       UT.erase(cast<Type>(I->second));
584
585   // UT now contains types that are not named.  Loop over it, naming structure
586   // types.
587   //
588   bool Changed = false;
589   for (std::set<const Type *>::const_iterator I = UT.begin(), E = UT.end();
590        I != E; ++I)
591     if (const StructType *ST = dyn_cast<StructType>(*I)) {
592       ((Value*)ST)->setName("unnamed", &MST);
593       Changed = true;
594     }
595   return Changed;
596 }
597
598 // generateCompilerSpecificCode - This is where we add conditional compilation
599 // directives to cater to specific compilers as need be.
600 //
601 static void generateCompilerSpecificCode(std::ostream& Out) {
602   // Alloca is hard to get, and we don't want to include stdlib.h here...
603   Out << "/* get a declaration for alloca */\n"
604       << "#ifdef sun\n"
605       << "extern void *__builtin_alloca(unsigned long);\n"
606       << "#define alloca(x) __builtin_alloca(x)\n"
607       << "#else\n"
608       << "#ifndef __FreeBSD__\n"
609       << "#include <alloca.h>\n"
610       << "#endif\n"
611       << "#endif\n\n";
612
613   // We output GCC specific attributes to preserve 'linkonce'ness on globals.
614   // If we aren't being compiled with GCC, just drop these attributes.
615   Out << "#ifndef __GNUC__  /* Can only support \"linkonce\" vars with GCC */\n"
616       << "#define __attribute__(X)\n"
617       << "#endif\n\n";
618
619 #if 0
620   // At some point, we should support "external weak" vs. "weak" linkages.
621   // On Mac OS X, "external weak" is spelled "__attribute__((weak_import))".
622   Out << "#if defined(__GNUC__) && defined(__APPLE_CC__)\n"
623       << "#define __EXTERNAL_WEAK__ __attribute__((weak_import))\n"
624       << "#elif defined(__GNUC__)\n"
625       << "#define __EXTERNAL_WEAK__ __attribute__((weak))\n"
626       << "#else\n"
627       << "#define __EXTERNAL_WEAK__\n"
628       << "#endif\n\n";
629 #endif
630
631   // For now, turn off the weak linkage attribute on Mac OS X. (See above.)
632   Out << "#if defined(__GNUC__) && defined(__APPLE_CC__)\n"
633       << "#define __ATTRIBUTE_WEAK__\n"
634       << "#elif defined(__GNUC__)\n"
635       << "#define __ATTRIBUTE_WEAK__ __attribute__((weak))\n"
636       << "#else\n"
637       << "#define __ATTRIBUTE_WEAK__\n"
638       << "#endif\n\n";
639 }
640
641 bool CWriter::doInitialization(Module &M) {
642   // Initialize
643   TheModule = &M;
644   FUT = &getAnalysis<FindUsedTypes>();
645   
646   // Ensure that all structure types have names...
647   bool Changed = nameAllUsedStructureTypes(M);
648   Mang = new Mangler(M);
649
650   // get declaration for alloca
651   Out << "/* Provide Declarations */\n";
652   Out << "#include <stdarg.h>\n";      // Varargs support
653   Out << "#include <setjmp.h>\n";      // Unwind support
654   generateCompilerSpecificCode(Out);
655
656   // Provide a definition for `bool' if not compiling with a C++ compiler.
657   Out << "\n"
658       << "#ifndef __cplusplus\ntypedef unsigned char bool;\n#endif\n"
659     
660       << "\n\n/* Support for floating point constants */\n"
661       << "typedef unsigned long long ConstantDoubleTy;\n"
662       << "typedef unsigned int        ConstantFloatTy;\n"
663     
664       << "\n\n/* Global Declarations */\n";
665
666   // First output all the declarations for the program, because C requires
667   // Functions & globals to be declared before they are used.
668   //
669
670   // Loop over the symbol table, emitting all named constants...
671   printSymbolTable(M.getSymbolTable());
672
673   // Global variable declarations...
674   if (!M.gempty()) {
675     Out << "\n/* External Global Variable Declarations */\n";
676     for (Module::giterator I = M.gbegin(), E = M.gend(); I != E; ++I) {
677       if (I->hasExternalLinkage()) {
678         Out << "extern ";
679         printType(Out, I->getType()->getElementType(), Mang->getValueName(I));
680         Out << ";\n";
681       }
682     }
683   }
684
685   // Function declarations
686   if (!M.empty()) {
687     Out << "\n/* Function Declarations */\n";
688     for (Module::iterator I = M.begin(), E = M.end(); I != E; ++I) {
689       // Don't print declarations for intrinsic functions.
690       if (!I->getIntrinsicID()) {
691         printFunctionSignature(I, true);
692         if (I->hasWeakLinkage()) Out << " __ATTRIBUTE_WEAK__";
693         if (I->hasLinkOnceLinkage()) Out << " __ATTRIBUTE_WEAK__";
694         Out << ";\n";
695       }
696     }
697   }
698
699   // Output the global variable declarations
700   if (!M.gempty()) {
701     Out << "\n\n/* Global Variable Declarations */\n";
702     for (Module::giterator I = M.gbegin(), E = M.gend(); I != E; ++I)
703       if (!I->isExternal()) {
704         Out << "extern ";
705         printType(Out, I->getType()->getElementType(), Mang->getValueName(I));
706
707         if (I->hasLinkOnceLinkage())
708           Out << " __attribute__((common))";
709         else if (I->hasWeakLinkage())
710           Out << " __ATTRIBUTE_WEAK__";
711         Out << ";\n";
712       }
713   }
714
715   // Output the global variable definitions and contents...
716   if (!M.gempty()) {
717     Out << "\n\n/* Global Variable Definitions and Initialization */\n";
718     for (Module::giterator I = M.gbegin(), E = M.gend(); I != E; ++I)
719       if (!I->isExternal()) {
720         if (I->hasInternalLinkage())
721           Out << "static ";
722         printType(Out, I->getType()->getElementType(), Mang->getValueName(I));
723         if (I->hasLinkOnceLinkage())
724           Out << " __attribute__((common))";
725         else if (I->hasWeakLinkage())
726           Out << " __ATTRIBUTE_WEAK__";
727
728         // If the initializer is not null, emit the initializer.  If it is null,
729         // we try to avoid emitting large amounts of zeros.  The problem with
730         // this, however, occurs when the variable has weak linkage.  In this
731         // case, the assembler will complain about the variable being both weak
732         // and common, so we disable this optimization.
733         if (!I->getInitializer()->isNullValue()) {
734           Out << " = " ;
735           writeOperand(I->getInitializer());
736         } else if (I->hasWeakLinkage()) {
737           // We have to specify an initializer, but it doesn't have to be
738           // complete.  If the value is an aggregate, print out { 0 }, and let
739           // the compiler figure out the rest of the zeros.
740           Out << " = " ;
741           if (isa<StructType>(I->getInitializer()->getType()) ||
742               isa<ArrayType>(I->getInitializer()->getType())) {
743             Out << "{ 0 }";
744           } else {
745             // Just print it out normally.
746             writeOperand(I->getInitializer());
747           }
748         }
749         Out << ";\n";
750       }
751   }
752
753   // Output all floating point constants that cannot be printed accurately...
754   printFloatingPointConstants(M);
755   
756   if (!M.empty())
757     Out << "\n\n/* Function Bodies */\n";
758   return false;
759 }
760
761
762 /// Output all floating point constants that cannot be printed accurately...
763 void CWriter::printFloatingPointConstants(Module &M) {
764   union {
765     double D;
766     unsigned long long U;
767   } DBLUnion;
768
769   union {
770     float F;
771     unsigned U;
772   } FLTUnion;
773
774   // Scan the module for floating point constants.  If any FP constant is used
775   // in the function, we want to redirect it here so that we do not depend on
776   // the precision of the printed form, unless the printed form preserves
777   // precision.
778   //
779   unsigned FPCounter = 0;
780   for (Module::iterator F = M.begin(), E = M.end(); F != E; ++F)
781     for (constant_iterator I = constant_begin(F), E = constant_end(F);
782          I != E; ++I)
783       if (const ConstantFP *FPC = dyn_cast<ConstantFP>(*I))
784         if (!isFPCSafeToPrint(FPC) && // Do not put in FPConstantMap if safe.
785             !FPConstantMap.count(FPC)) {
786           double Val = FPC->getValue();
787           
788           FPConstantMap[FPC] = FPCounter;  // Number the FP constants
789           
790           if (FPC->getType() == Type::DoubleTy) {
791             DBLUnion.D = Val;
792             Out << "static const ConstantDoubleTy FPConstant" << FPCounter++
793                 << " = 0x" << std::hex << DBLUnion.U << std::dec
794                 << "ULL;    /* " << Val << " */\n";
795           } else if (FPC->getType() == Type::FloatTy) {
796             FLTUnion.F = Val;
797             Out << "static const ConstantFloatTy FPConstant" << FPCounter++
798                 << " = 0x" << std::hex << FLTUnion.U << std::dec
799                 << "U;    /* " << Val << " */\n";
800           } else
801             assert(0 && "Unknown float type!");
802         }
803   
804   Out << "\n";
805  }
806
807
808 /// printSymbolTable - Run through symbol table looking for type names.  If a
809 /// type name is found, emit it's declaration...
810 ///
811 void CWriter::printSymbolTable(const SymbolTable &ST) {
812   // If there are no type names, exit early.
813   if (ST.find(Type::TypeTy) == ST.end())
814     return;
815
816   // We are only interested in the type plane of the symbol table...
817   SymbolTable::type_const_iterator I   = ST.type_begin(Type::TypeTy);
818   SymbolTable::type_const_iterator End = ST.type_end(Type::TypeTy);
819   
820   // Print out forward declarations for structure types before anything else!
821   Out << "/* Structure forward decls */\n";
822   for (; I != End; ++I)
823     if (const Type *STy = dyn_cast<StructType>(I->second))
824       // Only print out used types!
825       if (FUT->getTypes().count(STy)) {
826         std::string Name = "struct l_" + Mangler::makeNameProper(I->first);
827         Out << Name << ";\n";
828         TypeNames.insert(std::make_pair(STy, Name));
829       }
830
831   Out << "\n";
832
833   // Now we can print out typedefs...
834   Out << "/* Typedefs */\n";
835   for (I = ST.type_begin(Type::TypeTy); I != End; ++I)
836     // Only print out used types!
837     if (FUT->getTypes().count(cast<Type>(I->second))) {
838       const Type *Ty = cast<Type>(I->second);
839       std::string Name = "l_" + Mangler::makeNameProper(I->first);
840       Out << "typedef ";
841       printType(Out, Ty, Name);
842       Out << ";\n";
843     }
844   
845   Out << "\n";
846
847   // Keep track of which structures have been printed so far...
848   std::set<const StructType *> StructPrinted;
849
850   // Loop over all structures then push them into the stack so they are
851   // printed in the correct order.
852   //
853   Out << "/* Structure contents */\n";
854   for (I = ST.type_begin(Type::TypeTy); I != End; ++I)
855     if (const StructType *STy = dyn_cast<StructType>(I->second))
856       // Only print out used types!
857       if (FUT->getTypes().count(STy))
858         printContainedStructs(STy, StructPrinted);
859 }
860
861 // Push the struct onto the stack and recursively push all structs
862 // this one depends on.
863 void CWriter::printContainedStructs(const Type *Ty,
864                                     std::set<const StructType*> &StructPrinted){
865   if (const StructType *STy = dyn_cast<StructType>(Ty)) {
866     //Check to see if we have already printed this struct
867     if (StructPrinted.count(STy) == 0) {
868       // Print all contained types first...
869       for (StructType::element_iterator I = STy->element_begin(),
870              E = STy->element_end(); I != E; ++I) {
871         const Type *Ty1 = I->get();
872         if (isa<StructType>(Ty1) || isa<ArrayType>(Ty1))
873           printContainedStructs(*I, StructPrinted);
874       }
875       
876       //Print structure type out..
877       StructPrinted.insert(STy);
878       std::string Name = TypeNames[STy];  
879       printType(Out, STy, Name, true);
880       Out << ";\n\n";
881     }
882
883     // If it is an array, check contained types and continue
884   } else if (const ArrayType *ATy = dyn_cast<ArrayType>(Ty)){
885     const Type *Ty1 = ATy->getElementType();
886     if (isa<StructType>(Ty1) || isa<ArrayType>(Ty1))
887       printContainedStructs(Ty1, StructPrinted);
888   }
889 }
890
891
892 void CWriter::printFunctionSignature(const Function *F, bool Prototype) {
893   if (F->hasInternalLinkage()) Out << "static ";
894   
895   // Loop over the arguments, printing them...
896   const FunctionType *FT = cast<FunctionType>(F->getFunctionType());
897   
898   std::stringstream FunctionInnards; 
899     
900   // Print out the name...
901   FunctionInnards << Mang->getValueName(F) << "(";
902     
903   if (!F->isExternal()) {
904     if (!F->aempty()) {
905       std::string ArgName;
906       if (F->abegin()->hasName() || !Prototype)
907         ArgName = Mang->getValueName(F->abegin());
908       printType(FunctionInnards, F->afront().getType(), ArgName);
909       for (Function::const_aiterator I = ++F->abegin(), E = F->aend();
910            I != E; ++I) {
911         FunctionInnards << ", ";
912         if (I->hasName() || !Prototype)
913           ArgName = Mang->getValueName(I);
914         else 
915           ArgName = "";
916         printType(FunctionInnards, I->getType(), ArgName);
917       }
918     }
919   } else {
920     // Loop over the arguments, printing them...
921     for (FunctionType::param_iterator I = FT->param_begin(),
922            E = FT->param_end(); I != E; ++I) {
923       if (I != FT->param_begin()) FunctionInnards << ", ";
924       printType(FunctionInnards, *I);
925     }
926   }
927
928   // Finish printing arguments... if this is a vararg function, print the ...,
929   // unless there are no known types, in which case, we just emit ().
930   //
931   if (FT->isVarArg() && FT->getNumParams()) {
932     if (FT->getNumParams()) FunctionInnards << ", ";
933     FunctionInnards << "...";  // Output varargs portion of signature!
934   } else if (!FT->isVarArg() && FT->getNumParams() == 0) {
935     FunctionInnards << "void"; // ret() -> ret(void) in C.
936   }
937   FunctionInnards << ")";
938   // Print out the return type and the entire signature for that matter
939   printType(Out, F->getReturnType(), FunctionInnards.str());
940 }
941
942 void CWriter::printFunction(Function &F) {
943   printFunctionSignature(&F, false);
944   Out << " {\n";
945
946   // print local variable information for the function
947   for (inst_iterator I = inst_begin(&F), E = inst_end(&F); I != E; ++I)
948     if (const AllocaInst *AI = isDirectAlloca(*I)) {
949       Out << "  ";
950       printType(Out, AI->getAllocatedType(), Mang->getValueName(AI));
951       Out << ";    /* Address exposed local */\n";
952     } else if ((*I)->getType() != Type::VoidTy && !isInlinableInst(**I)) {
953       Out << "  ";
954       printType(Out, (*I)->getType(), Mang->getValueName(*I));
955       Out << ";\n";
956       
957       if (isa<PHINode>(*I)) {  // Print out PHI node temporaries as well...
958         Out << "  ";
959         printType(Out, (*I)->getType(),
960                   Mang->getValueName(*I)+"__PHI_TEMPORARY");
961         Out << ";\n";
962       }
963     }
964
965   Out << "\n";
966
967   // print the basic blocks
968   for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB) {
969     BasicBlock *Prev = BB->getPrev();
970
971     // Don't print the label for the basic block if there are no uses, or if the
972     // only terminator use is the predecessor basic block's terminator.  We have
973     // to scan the use list because PHI nodes use basic blocks too but do not
974     // require a label to be generated.
975     //
976     bool NeedsLabel = false;
977     for (Value::use_iterator UI = BB->use_begin(), UE = BB->use_end();
978          UI != UE; ++UI)
979       if (TerminatorInst *TI = dyn_cast<TerminatorInst>(*UI))
980         if (TI != Prev->getTerminator() ||
981             isa<SwitchInst>(Prev->getTerminator()) ||
982             isa<InvokeInst>(Prev->getTerminator())) {
983           NeedsLabel = true;
984           break;        
985         }
986
987     if (NeedsLabel) Out << Mang->getValueName(BB) << ":\n";
988
989     // Output all of the instructions in the basic block...
990     for (BasicBlock::iterator II = BB->begin(), E = --BB->end(); II != E; ++II){
991       if (!isInlinableInst(*II) && !isDirectAlloca(II)) {
992         if (II->getType() != Type::VoidTy)
993           outputLValue(II);
994         else
995           Out << "  ";
996         visit(*II);
997         Out << ";\n";
998       }
999     }
1000
1001     // Don't emit prefix or suffix for the terminator...
1002     visit(*BB->getTerminator());
1003   }
1004   
1005   Out << "}\n\n";
1006 }
1007
1008 // Specific Instruction type classes... note that all of the casts are
1009 // necessary because we use the instruction classes as opaque types...
1010 //
1011 void CWriter::visitReturnInst(ReturnInst &I) {
1012   // Don't output a void return if this is the last basic block in the function
1013   if (I.getNumOperands() == 0 && 
1014       &*--I.getParent()->getParent()->end() == I.getParent() &&
1015       !I.getParent()->size() == 1) {
1016     return;
1017   }
1018
1019   Out << "  return";
1020   if (I.getNumOperands()) {
1021     Out << " ";
1022     writeOperand(I.getOperand(0));
1023   }
1024   Out << ";\n";
1025 }
1026
1027 void CWriter::visitSwitchInst(SwitchInst &SI) {
1028   Out << "  switch (";
1029   writeOperand(SI.getOperand(0));
1030   Out << ") {\n  default:\n";
1031   printBranchToBlock(SI.getParent(), SI.getDefaultDest(), 2);
1032   Out << ";\n";
1033   for (unsigned i = 2, e = SI.getNumOperands(); i != e; i += 2) {
1034     Out << "  case ";
1035     writeOperand(SI.getOperand(i));
1036     Out << ":\n";
1037     BasicBlock *Succ = cast<BasicBlock>(SI.getOperand(i+1));
1038     printBranchToBlock(SI.getParent(), Succ, 2);
1039     if (Succ == SI.getParent()->getNext())
1040       Out << "    break;\n";
1041   }
1042   Out << "  }\n";
1043 }
1044
1045 void CWriter::visitInvokeInst(InvokeInst &II) {
1046   assert(0 && "Lowerinvoke pass didn't work!");
1047 }
1048
1049
1050 void CWriter::visitUnwindInst(UnwindInst &I) {
1051   assert(0 && "Lowerinvoke pass didn't work!");
1052 }
1053
1054 bool isGotoCodeNecessary(BasicBlock *From, BasicBlock *To) {
1055   // If PHI nodes need copies, we need the copy code...
1056   if (isa<PHINode>(To->front()) ||
1057       From->getNext() != To)      // Not directly successor, need goto
1058     return true;
1059
1060   // Otherwise we don't need the code.
1061   return false;
1062 }
1063
1064 void CWriter::printBranchToBlock(BasicBlock *CurBB, BasicBlock *Succ,
1065                                  unsigned Indent) {
1066   for (BasicBlock::iterator I = Succ->begin();
1067        PHINode *PN = dyn_cast<PHINode>(I); ++I) {
1068     //  now we have to do the printing
1069     Out << std::string(Indent, ' ');
1070     Out << "  " << Mang->getValueName(I) << "__PHI_TEMPORARY = ";
1071     writeOperand(PN->getIncomingValue(PN->getBasicBlockIndex(CurBB)));
1072     Out << ";   /* for PHI node */\n";
1073   }
1074
1075   if (CurBB->getNext() != Succ ||
1076       isa<InvokeInst>(CurBB->getTerminator()) ||
1077       isa<SwitchInst>(CurBB->getTerminator())) {
1078     Out << std::string(Indent, ' ') << "  goto ";
1079     writeOperand(Succ);
1080     Out << ";\n";
1081   }
1082 }
1083
1084 // Branch instruction printing - Avoid printing out a branch to a basic block
1085 // that immediately succeeds the current one.
1086 //
1087 void CWriter::visitBranchInst(BranchInst &I) {
1088   if (I.isConditional()) {
1089     if (isGotoCodeNecessary(I.getParent(), I.getSuccessor(0))) {
1090       Out << "  if (";
1091       writeOperand(I.getCondition());
1092       Out << ") {\n";
1093       
1094       printBranchToBlock(I.getParent(), I.getSuccessor(0), 2);
1095       
1096       if (isGotoCodeNecessary(I.getParent(), I.getSuccessor(1))) {
1097         Out << "  } else {\n";
1098         printBranchToBlock(I.getParent(), I.getSuccessor(1), 2);
1099       }
1100     } else {
1101       // First goto not necessary, assume second one is...
1102       Out << "  if (!";
1103       writeOperand(I.getCondition());
1104       Out << ") {\n";
1105
1106       printBranchToBlock(I.getParent(), I.getSuccessor(1), 2);
1107     }
1108
1109     Out << "  }\n";
1110   } else {
1111     printBranchToBlock(I.getParent(), I.getSuccessor(0), 0);
1112   }
1113   Out << "\n";
1114 }
1115
1116 // PHI nodes get copied into temporary values at the end of predecessor basic
1117 // blocks.  We now need to copy these temporary values into the REAL value for
1118 // the PHI.
1119 void CWriter::visitPHINode(PHINode &I) {
1120   writeOperand(&I);
1121   Out << "__PHI_TEMPORARY";
1122 }
1123
1124
1125 void CWriter::visitBinaryOperator(Instruction &I) {
1126   // binary instructions, shift instructions, setCond instructions.
1127   assert(!isa<PointerType>(I.getType()));
1128
1129   // We must cast the results of binary operations which might be promoted.
1130   bool needsCast = false;
1131   if ((I.getType() == Type::UByteTy) || (I.getType() == Type::SByteTy)
1132       || (I.getType() == Type::UShortTy) || (I.getType() == Type::ShortTy)
1133       || (I.getType() == Type::FloatTy)) {
1134     needsCast = true;
1135     Out << "((";
1136     printType(Out, I.getType());
1137     Out << ")(";
1138   }
1139       
1140   writeOperand(I.getOperand(0));
1141
1142   switch (I.getOpcode()) {
1143   case Instruction::Add: Out << " + "; break;
1144   case Instruction::Sub: Out << " - "; break;
1145   case Instruction::Mul: Out << "*"; break;
1146   case Instruction::Div: Out << "/"; break;
1147   case Instruction::Rem: Out << "%"; break;
1148   case Instruction::And: Out << " & "; break;
1149   case Instruction::Or: Out << " | "; break;
1150   case Instruction::Xor: Out << " ^ "; break;
1151   case Instruction::SetEQ: Out << " == "; break;
1152   case Instruction::SetNE: Out << " != "; break;
1153   case Instruction::SetLE: Out << " <= "; break;
1154   case Instruction::SetGE: Out << " >= "; break;
1155   case Instruction::SetLT: Out << " < "; break;
1156   case Instruction::SetGT: Out << " > "; break;
1157   case Instruction::Shl : Out << " << "; break;
1158   case Instruction::Shr : Out << " >> "; break;
1159   default: std::cerr << "Invalid operator type!" << I; abort();
1160   }
1161
1162   writeOperand(I.getOperand(1));
1163
1164   if (needsCast) {
1165     Out << "))";
1166   }
1167 }
1168
1169 void CWriter::visitCastInst(CastInst &I) {
1170   if (I.getType() == Type::BoolTy) {
1171     Out << "(";
1172     writeOperand(I.getOperand(0));
1173     Out << " != 0)";
1174     return;
1175   }
1176   Out << "(";
1177   printType(Out, I.getType());
1178   Out << ")";
1179   if (isa<PointerType>(I.getType())&&I.getOperand(0)->getType()->isIntegral() ||
1180       isa<PointerType>(I.getOperand(0)->getType())&&I.getType()->isIntegral()) {
1181     // Avoid "cast to pointer from integer of different size" warnings
1182     Out << "(long)";  
1183   }
1184   
1185   writeOperand(I.getOperand(0));
1186 }
1187
1188 void CWriter::lowerIntrinsics(Module &M) {
1189   for (Module::iterator F = M.begin(), E = M.end(); F != E; ++F)
1190     for (Function::iterator BB = F->begin(), E = F->end(); BB != E; ++BB)
1191       for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; )
1192         if (CallInst *CI = dyn_cast<CallInst>(I++))
1193           if (Function *F = CI->getCalledFunction())
1194             switch (F->getIntrinsicID()) {
1195             case Intrinsic::not_intrinsic:
1196             case Intrinsic::va_start:
1197             case Intrinsic::va_copy:
1198             case Intrinsic::va_end:
1199             case Intrinsic::returnaddress:
1200             case Intrinsic::frameaddress:
1201             case Intrinsic::setjmp:
1202             case Intrinsic::longjmp:
1203               // We directly implement these intrinsics
1204               break;
1205             default:
1206               // All other intrinsic calls we must lower.
1207               Instruction *Before = CI->getPrev();
1208               IL.LowerIntrinsicCall(CI);
1209               if (Before) {        // Move iterator to instruction after call
1210                 I = Before; ++I;
1211               } else {
1212                 I = BB->begin();
1213               }
1214             }
1215 }
1216
1217
1218
1219 void CWriter::visitCallInst(CallInst &I) {
1220   // Handle intrinsic function calls first...
1221   if (Function *F = I.getCalledFunction())
1222     if (Intrinsic::ID ID = (Intrinsic::ID)F->getIntrinsicID()) {
1223       switch (ID) {
1224       default: assert(0 && "Unknown LLVM intrinsic!");
1225       case Intrinsic::va_start: 
1226         Out << "0; ";
1227         
1228         Out << "va_start(*(va_list*)&" << Mang->getValueName(&I) << ", ";
1229         // Output the last argument to the enclosing function...
1230         if (I.getParent()->getParent()->aempty()) {
1231           std::cerr << "The C backend does not currently support zero "
1232                     << "argument varargs functions, such as '"
1233                     << I.getParent()->getParent()->getName() << "'!\n";
1234           abort();
1235         }
1236         writeOperand(&I.getParent()->getParent()->aback());
1237         Out << ")";
1238         return;
1239       case Intrinsic::va_end:
1240         Out << "va_end(*(va_list*)&";
1241         writeOperand(I.getOperand(1));
1242         Out << ")";
1243         return;
1244       case Intrinsic::va_copy:
1245         Out << "0;";
1246         Out << "va_copy(*(va_list*)&" << Mang->getValueName(&I) << ", ";
1247         Out << "*(va_list*)&";
1248         writeOperand(I.getOperand(1));
1249         Out << ")";
1250         return;
1251       case Intrinsic::returnaddress:
1252         Out << "__builtin_return_address(";
1253         writeOperand(I.getOperand(1));
1254         Out << ")";
1255         return;
1256       case Intrinsic::frameaddress:
1257         Out << "__builtin_frame_address(";
1258         writeOperand(I.getOperand(1));
1259         Out << ")";
1260         return;
1261       case Intrinsic::setjmp:
1262         Out << "setjmp(*(jmp_buf*)";
1263         writeOperand(I.getOperand(1));
1264         Out << ")";
1265         return;
1266       case Intrinsic::longjmp:
1267         Out << "longjmp(*(jmp_buf*)";
1268         writeOperand(I.getOperand(1));
1269         Out << ", ";
1270         writeOperand(I.getOperand(2));
1271         Out << ")";
1272         return;
1273       }
1274     }
1275   visitCallSite(&I);
1276 }
1277
1278 void CWriter::visitCallSite(CallSite CS) {
1279   const PointerType  *PTy   = cast<PointerType>(CS.getCalledValue()->getType());
1280   const FunctionType *FTy   = cast<FunctionType>(PTy->getElementType());
1281   const Type         *RetTy = FTy->getReturnType();
1282   
1283   writeOperand(CS.getCalledValue());
1284   Out << "(";
1285
1286   if (CS.arg_begin() != CS.arg_end()) {
1287     CallSite::arg_iterator AI = CS.arg_begin(), AE = CS.arg_end();
1288     writeOperand(*AI);
1289
1290     for (++AI; AI != AE; ++AI) {
1291       Out << ", ";
1292       writeOperand(*AI);
1293     }
1294   }
1295   Out << ")";
1296 }  
1297
1298 void CWriter::visitMallocInst(MallocInst &I) {
1299   assert(0 && "lowerallocations pass didn't work!");
1300 }
1301
1302 void CWriter::visitAllocaInst(AllocaInst &I) {
1303   Out << "(";
1304   printType(Out, I.getType());
1305   Out << ") alloca(sizeof(";
1306   printType(Out, I.getType()->getElementType());
1307   Out << ")";
1308   if (I.isArrayAllocation()) {
1309     Out << " * " ;
1310     writeOperand(I.getOperand(0));
1311   }
1312   Out << ")";
1313 }
1314
1315 void CWriter::visitFreeInst(FreeInst &I) {
1316   assert(0 && "lowerallocations pass didn't work!");
1317 }
1318
1319 void CWriter::printIndexingExpression(Value *Ptr, gep_type_iterator I,
1320                                       gep_type_iterator E) {
1321   bool HasImplicitAddress = false;
1322   // If accessing a global value with no indexing, avoid *(&GV) syndrome
1323   if (GlobalValue *V = dyn_cast<GlobalValue>(Ptr)) {
1324     HasImplicitAddress = true;
1325   } else if (ConstantPointerRef *CPR = dyn_cast<ConstantPointerRef>(Ptr)) {
1326     HasImplicitAddress = true;
1327     Ptr = CPR->getValue();         // Get to the global...
1328   } else if (isDirectAlloca(Ptr)) {
1329     HasImplicitAddress = true;
1330   }
1331
1332   if (I == E) {
1333     if (!HasImplicitAddress)
1334       Out << "*";  // Implicit zero first argument: '*x' is equivalent to 'x[0]'
1335
1336     writeOperandInternal(Ptr);
1337     return;
1338   }
1339
1340   const Constant *CI = dyn_cast<Constant>(I.getOperand());
1341   if (HasImplicitAddress && (!CI || !CI->isNullValue()))
1342     Out << "(&";
1343
1344   writeOperandInternal(Ptr);
1345
1346   if (HasImplicitAddress && (!CI || !CI->isNullValue())) {
1347     Out << ")";
1348     HasImplicitAddress = false;  // HIA is only true if we haven't addressed yet
1349   }
1350
1351   assert(!HasImplicitAddress || (CI && CI->isNullValue()) &&
1352          "Can only have implicit address with direct accessing");
1353
1354   if (HasImplicitAddress) {
1355     ++I;
1356   } else if (CI && CI->isNullValue()) {
1357     gep_type_iterator TmpI = I; ++TmpI;
1358
1359     // Print out the -> operator if possible...
1360     if (TmpI != E && isa<StructType>(*TmpI)) {
1361       Out << (HasImplicitAddress ? "." : "->");
1362       Out << "field" << cast<ConstantUInt>(TmpI.getOperand())->getValue();
1363       I = ++TmpI;
1364     }
1365   }
1366
1367   for (; I != E; ++I)
1368     if (isa<StructType>(*I)) {
1369       Out << ".field" << cast<ConstantUInt>(I.getOperand())->getValue();
1370     } else {
1371       Out << "[";
1372       writeOperand(I.getOperand());
1373       Out << "]";
1374     }
1375 }
1376
1377 void CWriter::visitLoadInst(LoadInst &I) {
1378   Out << "*";
1379   writeOperand(I.getOperand(0));
1380 }
1381
1382 void CWriter::visitStoreInst(StoreInst &I) {
1383   Out << "*";
1384   writeOperand(I.getPointerOperand());
1385   Out << " = ";
1386   writeOperand(I.getOperand(0));
1387 }
1388
1389 void CWriter::visitGetElementPtrInst(GetElementPtrInst &I) {
1390   Out << "&";
1391   printIndexingExpression(I.getPointerOperand(), gep_type_begin(I),
1392                           gep_type_end(I));
1393 }
1394
1395 void CWriter::visitVANextInst(VANextInst &I) {
1396   Out << Mang->getValueName(I.getOperand(0));
1397   Out << ";  va_arg(*(va_list*)&" << Mang->getValueName(&I) << ", ";
1398   printType(Out, I.getArgType());
1399   Out << ")";  
1400 }
1401
1402 void CWriter::visitVAArgInst(VAArgInst &I) {
1403   Out << "0;\n";
1404   Out << "{ va_list Tmp; va_copy(Tmp, *(va_list*)&";
1405   writeOperand(I.getOperand(0));
1406   Out << ");\n  " << Mang->getValueName(&I) << " = va_arg(Tmp, ";
1407   printType(Out, I.getType());
1408   Out << ");\n  va_end(Tmp); }";
1409 }
1410
1411 //===----------------------------------------------------------------------===//
1412 //                       External Interface declaration
1413 //===----------------------------------------------------------------------===//
1414
1415 bool CTargetMachine::addPassesToEmitAssembly(PassManager &PM, std::ostream &o) {
1416   PM.add(createLowerAllocationsPass());
1417   PM.add(createLowerInvokePass());
1418   PM.add(new CWriter(o, getIntrinsicLowering()));
1419   return false;
1420 }
1421
1422 TargetMachine *llvm::allocateCTargetMachine(const Module &M,
1423                                             IntrinsicLowering *IL) {
1424   return new CTargetMachine(M, IL);
1425 }