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