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