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