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