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