1 //===-- Writer.cpp - Library for converting LLVM code to C ----------------===//
3 // This library converts LLVM code to C code, compilable by GCC.
5 //===-----------------------------------------------------------------------==//
6 #include "llvm/Assembly/CWriter.h"
7 #include "llvm/Constants.h"
8 #include "llvm/DerivedTypes.h"
9 #include "llvm/Module.h"
10 #include "llvm/iMemory.h"
11 #include "llvm/iTerminators.h"
12 #include "llvm/iPHINode.h"
13 #include "llvm/iOther.h"
14 #include "llvm/iOperators.h"
15 #include "llvm/Pass.h"
16 #include "llvm/SymbolTable.h"
17 #include "llvm/SlotCalculator.h"
18 #include "llvm/Analysis/FindUsedTypes.h"
19 #include "llvm/Analysis/ConstantsScanner.h"
20 #include "llvm/Support/InstVisitor.h"
21 #include "llvm/Support/InstIterator.h"
22 #include "Support/StringExtras.h"
23 #include "Support/STLExtras.h"
33 class CWriter : public Pass, public InstVisitor<CWriter> {
35 SlotCalculator *Table;
36 const Module *TheModule;
37 map<const Type *, string> TypeNames;
38 std::set<const Value*> MangledGlobals;
41 map<const ConstantFP *, unsigned> FPConstantMap;
43 CWriter(ostream &o) : Out(o) {}
45 void getAnalysisUsage(AnalysisUsage &AU) const {
47 AU.addRequired<FindUsedTypes>();
50 virtual bool run(Module &M) {
52 Table = new SlotCalculator(&M, false);
55 // Ensure that all structure types have names...
56 bool Changed = nameAllUsedStructureTypes(M);
64 MangledGlobals.clear();
68 ostream &printType(std::ostream &Out, const Type *Ty, const string &VariableName = "",
69 bool IgnoreName = false, bool namedContext = true);
71 void writeOperand(Value *Operand);
72 void writeOperandInternal(Value *Operand);
74 string getValueName(const Value *V);
77 bool nameAllUsedStructureTypes(Module &M);
78 void printModule(Module *M);
79 void printSymbolTable(const SymbolTable &ST);
80 void printContainedStructs(const Type *Ty, std::set<const StructType *> &);
81 void printGlobal(const GlobalVariable *GV);
82 void printFunctionSignature(const Function *F, bool Prototype);
84 void printFunction(Function *);
86 void printConstant(Constant *CPV);
87 void printConstantArray(ConstantArray *CPA);
89 // isInlinableInst - Attempt to inline instructions into their uses to build
90 // trees as much as possible. To do this, we have to consistently decide
91 // what is acceptable to inline, so that variable declarations don't get
92 // printed and an extra copy of the expr is not emitted.
94 static bool isInlinableInst(const Instruction &I) {
95 // Must be an expression, must be used exactly once. If it is dead, we
96 // emit it inline where it would go.
97 if (I.getType() == Type::VoidTy || I.use_size() != 1 ||
98 isa<TerminatorInst>(I) || isa<CallInst>(I) || isa<PHINode>(I) ||
99 isa<LoadInst>(I)) // Don't inline a load across a store!
102 // Only inline instruction it it's use is in the same BB as the inst.
103 return I.getParent() == cast<Instruction>(I.use_back())->getParent();
106 // Instruction visitation functions
107 friend class InstVisitor<CWriter>;
109 void visitReturnInst(ReturnInst &I);
110 void visitBranchInst(BranchInst &I);
112 void visitPHINode(PHINode &I) {}
113 void visitBinaryOperator(Instruction &I);
115 void visitCastInst (CastInst &I);
116 void visitCallInst (CallInst &I);
117 void visitShiftInst(ShiftInst &I) { visitBinaryOperator(I); }
119 void visitMallocInst(MallocInst &I);
120 void visitAllocaInst(AllocaInst &I);
121 void visitFreeInst (FreeInst &I);
122 void visitLoadInst (LoadInst &I);
123 void visitStoreInst (StoreInst &I);
124 void visitGetElementPtrInst(GetElementPtrInst &I);
126 void visitInstruction(Instruction &I) {
127 std::cerr << "C Writer does not know about " << I;
131 void outputLValue(Instruction *I) {
132 Out << " " << getValueName(I) << " = ";
134 void printBranchToBlock(BasicBlock *CurBlock, BasicBlock *SuccBlock,
136 void printIndexingExpression(Value *Ptr, User::op_iterator I,
137 User::op_iterator E);
141 // We dont want identifier names with ., space, - in them.
142 // So we replace them with _
143 static string makeNameProper(string x) {
145 for (string::iterator sI = x.begin(), sEnd = x.end(); sI != sEnd; sI++)
147 case '.': tmp += "d_"; break;
148 case ' ': tmp += "s_"; break;
149 case '-': tmp += "D_"; break;
156 string CWriter::getValueName(const Value *V) {
157 if (V->hasName()) { // Print out the label if it exists...
158 if (isa<GlobalValue>(V) && // Do not mangle globals...
159 cast<GlobalValue>(V)->hasExternalLinkage())// && // Unless it's internal or
160 //!MangledGlobals.count(V)) // Unless the name would collide if we don't
161 return makeNameProper(V->getName());
163 return "l" + utostr(V->getType()->getUniqueID()) + "_" +
164 makeNameProper(V->getName());
167 int Slot = Table->getValSlot(V);
168 assert(Slot >= 0 && "Invalid value!");
169 return "ltmp_" + itostr(Slot) + "_" + utostr(V->getType()->getUniqueID());
172 // A pointer type should not use parens around *'s alone, e.g., (**)
173 inline bool ptrTypeNameNeedsParens(const string &NameSoFar) {
174 return (NameSoFar.find_last_not_of('*') != std::string::npos);
177 // Pass the Type* and the variable name and this prints out the variable
180 ostream &CWriter::printType(std::ostream &Out, const Type *Ty, const string &NameSoFar,
181 bool IgnoreName, bool namedContext) {
182 if (Ty->isPrimitiveType())
183 switch (Ty->getPrimitiveID()) {
184 case Type::VoidTyID: return Out << "void " << NameSoFar;
185 case Type::BoolTyID: return Out << "bool " << NameSoFar;
186 case Type::UByteTyID: return Out << "unsigned char " << NameSoFar;
187 case Type::SByteTyID: return Out << "signed char " << NameSoFar;
188 case Type::UShortTyID: return Out << "unsigned short " << NameSoFar;
189 case Type::ShortTyID: return Out << "short " << NameSoFar;
190 case Type::UIntTyID: return Out << "unsigned " << NameSoFar;
191 case Type::IntTyID: return Out << "int " << NameSoFar;
192 case Type::ULongTyID: return Out << "unsigned long long " << NameSoFar;
193 case Type::LongTyID: return Out << "signed long long " << NameSoFar;
194 case Type::FloatTyID: return Out << "float " << NameSoFar;
195 case Type::DoubleTyID: return Out << "double " << NameSoFar;
197 std::cerr << "Unknown primitive type: " << Ty << "\n";
201 // Check to see if the type is named.
202 if (!IgnoreName || isa<OpaqueType>(Ty)) {
203 map<const Type *, string>::iterator I = TypeNames.find(Ty);
204 if (I != TypeNames.end()) {
205 return Out << I->second << " " << NameSoFar;
209 switch (Ty->getPrimitiveID()) {
210 case Type::FunctionTyID: {
211 const FunctionType *MTy = cast<FunctionType>(Ty);
212 std::stringstream FunctionInards;
213 FunctionInards << " (" << NameSoFar << ") (";
214 for (FunctionType::ParamTypes::const_iterator
215 I = MTy->getParamTypes().begin(),
216 E = MTy->getParamTypes().end(); I != E; ++I) {
217 if (I != MTy->getParamTypes().begin())
218 FunctionInards << ", ";
219 printType(FunctionInards, *I, "");
221 if (MTy->isVarArg()) {
222 if (!MTy->getParamTypes().empty())
223 FunctionInards << ", ";
224 FunctionInards << "...";
226 FunctionInards << ")";
227 string tstr = FunctionInards.str();
228 printType(Out, MTy->getReturnType(), tstr);
231 case Type::StructTyID: {
232 const StructType *STy = cast<StructType>(Ty);
233 Out << NameSoFar + " {\n";
235 for (StructType::ElementTypes::const_iterator
236 I = STy->getElementTypes().begin(),
237 E = STy->getElementTypes().end(); I != E; ++I) {
239 printType(Out, *I, "field" + utostr(Idx++));
245 case Type::PointerTyID: {
246 const PointerType *PTy = cast<PointerType>(Ty);
247 std::string ptrName = "*" + NameSoFar;
249 // Do not need parens around "* NameSoFar" if NameSoFar consists only
250 // of zero or more '*' chars *and* this is not an unnamed pointer type
251 // such as the result type in a cast statement. Otherwise, enclose in ( ).
252 if (ptrTypeNameNeedsParens(NameSoFar) || !namedContext ||
253 PTy->getElementType()->getPrimitiveID() == Type::ArrayTyID)
254 ptrName = "(" + ptrName + ")"; //
256 return printType(Out, PTy->getElementType(), ptrName);
259 case Type::ArrayTyID: {
260 const ArrayType *ATy = cast<ArrayType>(Ty);
261 unsigned NumElements = ATy->getNumElements();
262 return printType(Out, ATy->getElementType(),
263 NameSoFar + "[" + utostr(NumElements) + "]");
266 case Type::OpaqueTyID: {
267 static int Count = 0;
268 string TyName = "struct opaque_" + itostr(Count++);
269 assert(TypeNames.find(Ty) == TypeNames.end());
270 TypeNames[Ty] = TyName;
271 return Out << TyName << " " << NameSoFar;
274 assert(0 && "Unhandled case in getTypeProps!");
281 void CWriter::printConstantArray(ConstantArray *CPA) {
283 // As a special case, print the array as a string if it is an array of
284 // ubytes or an array of sbytes with positive values.
286 const Type *ETy = CPA->getType()->getElementType();
287 bool isString = (ETy == Type::SByteTy || ETy == Type::UByteTy);
289 // Make sure the last character is a null char, as automatically added by C
290 if (CPA->getNumOperands() == 0 ||
291 !cast<Constant>(*(CPA->op_end()-1))->isNullValue())
296 // Do not include the last character, which we know is null
297 for (unsigned i = 0, e = CPA->getNumOperands()-1; i != e; ++i) {
298 unsigned char C = (ETy == Type::SByteTy) ?
299 (unsigned char)cast<ConstantSInt>(CPA->getOperand(i))->getValue() :
300 (unsigned char)cast<ConstantUInt>(CPA->getOperand(i))->getValue();
303 if (C == '"' || C == '\\')
309 case '\n': Out << "\\n"; break;
310 case '\t': Out << "\\t"; break;
311 case '\r': Out << "\\r"; break;
312 case '\v': Out << "\\v"; break;
313 case '\a': Out << "\\a"; break;
314 case '\"': Out << "\\\""; break;
315 case '\'': Out << "\\\'"; break;
318 Out << ( C/16 < 10) ? ( C/16 +'0') : ( C/16 -10+'A');
319 Out << ((C&15) < 10) ? ((C&15)+'0') : ((C&15)-10+'A');
327 if (CPA->getNumOperands()) {
329 printConstant(cast<Constant>(CPA->getOperand(0)));
330 for (unsigned i = 1, e = CPA->getNumOperands(); i != e; ++i) {
332 printConstant(cast<Constant>(CPA->getOperand(i)));
340 // printConstant - The LLVM Constant to C Constant converter.
341 void CWriter::printConstant(Constant *CPV) {
342 if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(CPV)) {
343 switch (CE->getOpcode()) {
344 case Instruction::Cast:
346 printType(Out, CPV->getType());
348 printConstant(cast<Constant>(CPV->getOperand(0)));
352 case Instruction::GetElementPtr:
354 printIndexingExpression(CPV->getOperand(0),
355 CPV->op_begin()+1, CPV->op_end());
358 case Instruction::Add:
360 printConstant(cast<Constant>(CPV->getOperand(0)));
362 printConstant(cast<Constant>(CPV->getOperand(1)));
365 case Instruction::Sub:
367 printConstant(cast<Constant>(CPV->getOperand(0)));
369 printConstant(cast<Constant>(CPV->getOperand(1)));
374 std::cerr << "CWriter Error: Unhandled constant expression: "
380 switch (CPV->getType()->getPrimitiveID()) {
382 Out << (CPV == ConstantBool::False ? "0" : "1"); break;
383 case Type::SByteTyID:
384 case Type::ShortTyID:
386 Out << cast<ConstantSInt>(CPV)->getValue(); break;
388 Out << cast<ConstantSInt>(CPV)->getValue() << "ll"; break;
390 case Type::UByteTyID:
391 case Type::UShortTyID:
392 Out << cast<ConstantUInt>(CPV)->getValue(); break;
394 Out << cast<ConstantUInt>(CPV)->getValue() << "u"; break;
395 case Type::ULongTyID:
396 Out << cast<ConstantUInt>(CPV)->getValue() << "ull"; break;
398 case Type::FloatTyID:
399 case Type::DoubleTyID: {
400 ConstantFP *FPC = cast<ConstantFP>(CPV);
401 map<const ConstantFP *, unsigned>::iterator I = FPConstantMap.find(FPC);
402 if (I != FPConstantMap.end()) {
403 // Because of FP precision problems we must load from a stack allocated
404 // value that holds the value in hex.
405 Out << "(*(" << (FPC->getType() == Type::FloatTy ? "float" : "double")
406 << "*)&FloatConstant" << I->second << ")";
408 Out << FPC->getValue();
413 case Type::ArrayTyID:
414 printConstantArray(cast<ConstantArray>(CPV));
417 case Type::StructTyID: {
419 if (CPV->getNumOperands()) {
421 printConstant(cast<Constant>(CPV->getOperand(0)));
422 for (unsigned i = 1, e = CPV->getNumOperands(); i != e; ++i) {
424 printConstant(cast<Constant>(CPV->getOperand(i)));
431 case Type::PointerTyID:
432 if (isa<ConstantPointerNull>(CPV)) {
435 } else if (ConstantPointerRef *CPR = dyn_cast<ConstantPointerRef>(CPV)) {
436 writeOperand(CPR->getValue());
441 std::cerr << "Unknown constant type: " << CPV << "\n";
446 void CWriter::writeOperandInternal(Value *Operand) {
447 if (Instruction *I = dyn_cast<Instruction>(Operand))
448 if (isInlinableInst(*I)) {
449 // Should we inline this instruction to build a tree?
456 if (Operand->hasName()) {
457 Out << getValueName(Operand);
458 } else if (Constant *CPV = dyn_cast<Constant>(Operand)) {
461 int Slot = Table->getValSlot(Operand);
462 assert(Slot >= 0 && "Malformed LLVM!");
463 Out << "ltmp_" << Slot << "_" << Operand->getType()->getUniqueID();
467 void CWriter::writeOperand(Value *Operand) {
468 if (isa<GlobalVariable>(Operand))
469 Out << "(&"; // Global variables are references as their addresses by llvm
471 writeOperandInternal(Operand);
473 if (isa<GlobalVariable>(Operand))
477 // nameAllUsedStructureTypes - If there are structure types in the module that
478 // are used but do not have names assigned to them in the symbol table yet then
479 // we assign them names now.
481 bool CWriter::nameAllUsedStructureTypes(Module &M) {
482 // Get a set of types that are used by the program...
483 std::set<const Type *> UT = getAnalysis<FindUsedTypes>().getTypes();
485 // Loop over the module symbol table, removing types from UT that are already
488 SymbolTable &MST = M.getSymbolTable();
489 if (MST.find(Type::TypeTy) != MST.end())
490 for (SymbolTable::type_iterator I = MST.type_begin(Type::TypeTy),
491 E = MST.type_end(Type::TypeTy); I != E; ++I)
492 UT.erase(cast<Type>(I->second));
494 // UT now contains types that are not named. Loop over it, naming structure
497 bool Changed = false;
498 for (std::set<const Type *>::const_iterator I = UT.begin(), E = UT.end();
500 if (const StructType *ST = dyn_cast<StructType>(*I)) {
501 ((Value*)ST)->setName("unnamed", &MST);
507 static void generateAllocaDecl(ostream& Out)
509 // On SunOS, we need to insert the alloca macro & proto for the builtin.
510 Out << "#ifdef sun\n"
511 << "extern void *__builtin_alloca(unsigned long);\n"
512 << "#define alloca(x) __builtin_alloca(x)\n"
514 << "#include <alloca.h>\n"
518 void CWriter::printModule(Module *M) {
519 // Calculate which global values have names that will collide when we throw
520 // away type information.
521 { // Scope to delete the FoundNames set when we are done with it...
522 std::set<string> FoundNames;
523 for (Module::iterator I = M->begin(), E = M->end(); I != E; ++I)
524 if (I->hasName()) // If the global has a name...
525 if (FoundNames.count(I->getName())) // And the name is already used
526 MangledGlobals.insert(I); // Mangle the name
528 FoundNames.insert(I->getName()); // Otherwise, keep track of name
530 for (Module::giterator I = M->gbegin(), E = M->gend(); I != E; ++I)
531 if (I->hasName()) // If the global has a name...
532 if (FoundNames.count(I->getName())) // And the name is already used
533 MangledGlobals.insert(I); // Mangle the name
535 FoundNames.insert(I->getName()); // Otherwise, keep track of name
538 // printing stdlib inclusion
539 //Out << "#include <stdlib.h>\n";
541 // get declaration for alloca
542 Out << "/* Provide Declarations */\n";
543 generateAllocaDecl(Out);
545 // Provide a definition for null if one does not already exist,
546 // and for `bool' if not compiling with a C++ compiler.
547 Out << "#ifndef NULL\n#define NULL 0\n#endif\n\n"
548 << "#ifndef __cplusplus\ntypedef unsigned char bool;\n#endif\n"
550 << "\n\n/* Support for floating point constants */\n"
551 << "typedef unsigned long long ConstantDoubleTy;\n"
552 << "typedef unsigned int ConstantFloatTy;\n"
554 << "\n\n/* Global Declarations */\n";
556 // First output all the declarations for the program, because C requires
557 // Functions & globals to be declared before they are used.
560 // Loop over the symbol table, emitting all named constants...
561 printSymbolTable(M->getSymbolTable());
563 // Global variable declarations...
565 Out << "\n/* External Global Variable Declarations */\n";
566 for (Module::giterator I = M->gbegin(), E = M->gend(); I != E; ++I) {
567 if (I->hasExternalLinkage()) {
569 printType(Out, I->getType()->getElementType(), getValueName(I));
575 // Function declarations
577 Out << "\n/* Function Declarations */\n";
579 for (Module::iterator I = M->begin(), E = M->end(); I != E; ++I) {
580 // If the function is external and the name collides don't print it.
581 // Sometimes the bytecode likes to have multiple "declerations" for external functions
582 if (I->hasInternalLinkage() || !MangledGlobals.count(I)){
583 printFunctionSignature(I, true);
589 // Print Malloc prototype if needed
591 Out << "\n/* Malloc to make sun happy */\n";
592 Out << "extern void * malloc(size_t);\n\n";
595 // Output the global variable declerations
597 Out << "\n\n/* Global Variable Declerations */\n";
598 for (Module::giterator I = M->gbegin(), E = M->gend(); I != E; ++I)
599 if (!I->isExternal()) {
601 printType(Out, I->getType()->getElementType(), getValueName(I));
608 // Output the global variable definitions and contents...
610 Out << "\n\n/* Global Variable Definitions and Initialization */\n";
611 for (Module::giterator I = M->gbegin(), E = M->gend(); I != E; ++I)
612 if (!I->isExternal()) {
613 if (I->hasInternalLinkage())
615 printType(Out, I->getType()->getElementType(), getValueName(I));
618 writeOperand(I->getInitializer());
623 // Output all of the functions...
625 Out << "\n\n/* Function Bodies */\n";
626 for (Module::iterator I = M->begin(), E = M->end(); I != E; ++I)
632 /// printSymbolTable - Run through symbol table looking for type names. If a
633 /// type name is found, emit it's declaration...
635 void CWriter::printSymbolTable(const SymbolTable &ST) {
636 // If there are no type names, exit early.
637 if (ST.find(Type::TypeTy) == ST.end())
640 // We are only interested in the type plane of the symbol table...
641 SymbolTable::type_const_iterator I = ST.type_begin(Type::TypeTy);
642 SymbolTable::type_const_iterator End = ST.type_end(Type::TypeTy);
644 // Print out forward declarations for structure types before anything else!
645 Out << "/* Structure forward decls */\n";
646 for (; I != End; ++I)
647 if (const Type *STy = dyn_cast<StructType>(I->second)) {
648 string Name = "struct l_" + makeNameProper(I->first);
649 Out << Name << ";\n";
650 TypeNames.insert(std::make_pair(STy, Name));
655 // Now we can print out typedefs...
656 Out << "/* Typedefs */\n";
657 for (I = ST.type_begin(Type::TypeTy); I != End; ++I) {
658 const Type *Ty = cast<Type>(I->second);
659 string Name = "l_" + makeNameProper(I->first);
661 printType(Out, Ty, Name);
667 // Keep track of which structures have been printed so far...
668 std::set<const StructType *> StructPrinted;
670 // Loop over all structures then push them into the stack so they are
671 // printed in the correct order.
673 Out << "/* Structure contents */\n";
674 for (I = ST.type_begin(Type::TypeTy); I != End; ++I)
675 if (const StructType *STy = dyn_cast<StructType>(I->second))
676 printContainedStructs(STy, StructPrinted);
679 // Push the struct onto the stack and recursively push all structs
680 // this one depends on.
681 void CWriter::printContainedStructs(const Type *Ty,
682 std::set<const StructType*> &StructPrinted){
683 if (const StructType *STy = dyn_cast<StructType>(Ty)){
684 //Check to see if we have already printed this struct
685 if (StructPrinted.count(STy) == 0) {
686 // Print all contained types first...
687 for (StructType::ElementTypes::const_iterator
688 I = STy->getElementTypes().begin(),
689 E = STy->getElementTypes().end(); I != E; ++I) {
690 const Type *Ty1 = I->get();
691 if (isa<StructType>(Ty1) || isa<ArrayType>(Ty1))
692 printContainedStructs(Ty1, StructPrinted);
695 //Print structure type out..
696 StructPrinted.insert(STy);
697 string Name = TypeNames[STy];
698 printType(Out, STy, Name, true);
702 // If it is an array, check contained types and continue
703 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(Ty)){
704 const Type *Ty1 = ATy->getElementType();
705 if (isa<StructType>(Ty1) || isa<ArrayType>(Ty1))
706 printContainedStructs(Ty1, StructPrinted);
711 void CWriter::printFunctionSignature(const Function *F, bool Prototype) {
712 // If the program provides it's own malloc prototype we don't need
713 // to include the general one.
714 if (getValueName(F) == "malloc")
716 if (F->hasInternalLinkage()) Out << "static ";
717 // Loop over the arguments, printing them...
718 const FunctionType *FT = cast<FunctionType>(F->getFunctionType());
720 std::stringstream FunctionInards;
722 // Print out the name...
723 FunctionInards << getValueName(F) << "(";
725 if (!F->isExternal()) {
728 if (F->abegin()->hasName() || !Prototype)
729 ArgName = getValueName(F->abegin());
730 printType(FunctionInards, F->afront().getType(), ArgName);
731 for (Function::const_aiterator I = ++F->abegin(), E = F->aend();
733 FunctionInards << ", ";
734 if (I->hasName() || !Prototype)
735 ArgName = getValueName(I);
738 printType(FunctionInards, I->getType(), ArgName);
742 // Loop over the arguments, printing them...
743 for (FunctionType::ParamTypes::const_iterator I =
744 FT->getParamTypes().begin(),
745 E = FT->getParamTypes().end(); I != E; ++I) {
746 if (I != FT->getParamTypes().begin()) FunctionInards << ", ";
747 printType(FunctionInards, *I);
751 // Finish printing arguments... if this is a vararg function, print the ...,
752 // unless there are no known types, in which case, we just emit ().
754 if (FT->isVarArg() && !FT->getParamTypes().empty()) {
755 if (FT->getParamTypes().size()) FunctionInards << ", ";
756 FunctionInards << "..."; // Output varargs portion of signature!
758 FunctionInards << ")";
759 // Print out the return type and the entire signature for that matter
760 printType(Out, F->getReturnType(), FunctionInards.str());
765 void CWriter::printFunction(Function *F) {
766 if (F->isExternal()) return;
768 Table->incorporateFunction(F);
770 printFunctionSignature(F, false);
773 // print local variable information for the function
774 for (inst_iterator I = inst_begin(F), E = inst_end(F); I != E; ++I)
775 if ((*I)->getType() != Type::VoidTy && !isInlinableInst(**I)) {
777 printType(Out, (*I)->getType(), getValueName(*I));
783 // Scan the function for floating point constants. If any FP constant is used
784 // in the function, we want to redirect it here so that we do not depend on
785 // the precision of the printed form.
787 unsigned FPCounter = 0;
788 for (constant_iterator I = constant_begin(F), E = constant_end(F); I != E;++I)
789 if (const ConstantFP *FPC = dyn_cast<ConstantFP>(*I))
790 if (FPConstantMap.find(FPC) == FPConstantMap.end()) {
791 double Val = FPC->getValue();
793 FPConstantMap[FPC] = FPCounter; // Number the FP constants
795 if (FPC->getType() == Type::DoubleTy)
796 Out << " const ConstantDoubleTy FloatConstant" << FPCounter++
797 << " = 0x" << std::hex << *(unsigned long long*)&Val << std::dec
798 << "; /* " << Val << " */\n";
799 else if (FPC->getType() == Type::FloatTy) {
801 Out << " const ConstantFloatTy FloatConstant" << FPCounter++
802 << " = 0x" << std::hex << *(unsigned*)&fVal << std::dec
803 << "; /* " << Val << " */\n";
805 assert(0 && "Unknown float type!");
810 // print the basic blocks
811 for (Function::iterator BB = F->begin(), E = F->end(); BB != E; ++BB) {
812 BasicBlock *Prev = BB->getPrev();
814 // Don't print the label for the basic block if there are no uses, or if the
815 // only terminator use is the precessor basic block's terminator. We have
816 // to scan the use list because PHI nodes use basic blocks too but do not
817 // require a label to be generated.
819 bool NeedsLabel = false;
820 for (Value::use_iterator UI = BB->use_begin(), UE = BB->use_end();
822 if (TerminatorInst *TI = dyn_cast<TerminatorInst>(*UI))
823 if (TI != Prev->getTerminator()) {
828 if (NeedsLabel) Out << getValueName(BB) << ":\n";
830 // Output all of the instructions in the basic block...
831 for (BasicBlock::iterator II = BB->begin(), E = --BB->end(); II != E; ++II){
832 if (!isInlinableInst(*II) && !isa<PHINode>(*II)) {
833 if (II->getType() != Type::VoidTy)
842 // Don't emit prefix or suffix for the terminator...
843 visit(*BB->getTerminator());
847 Table->purgeFunction();
848 FPConstantMap.clear();
851 // Specific Instruction type classes... note that all of the casts are
852 // neccesary because we use the instruction classes as opaque types...
854 void CWriter::visitReturnInst(ReturnInst &I) {
855 // Don't output a void return if this is the last basic block in the function
856 if (I.getNumOperands() == 0 &&
857 &*--I.getParent()->getParent()->end() == I.getParent() &&
858 !I.getParent()->size() == 1) {
863 if (I.getNumOperands()) {
865 writeOperand(I.getOperand(0));
870 static bool isGotoCodeNeccessary(BasicBlock *From, BasicBlock *To) {
871 // If PHI nodes need copies, we need the copy code...
872 if (isa<PHINode>(To->front()) ||
873 From->getNext() != To) // Not directly successor, need goto
876 // Otherwise we don't need the code.
880 void CWriter::printBranchToBlock(BasicBlock *CurBB, BasicBlock *Succ,
882 for (BasicBlock::iterator I = Succ->begin();
883 PHINode *PN = dyn_cast<PHINode>(&*I); ++I) {
884 // now we have to do the printing
885 Out << string(Indent, ' ');
887 writeOperand(PN->getIncomingValue(PN->getBasicBlockIndex(CurBB)));
888 Out << "; /* for PHI node */\n";
891 if (CurBB->getNext() != Succ) {
892 Out << string(Indent, ' ') << " goto ";
898 // Brach instruction printing - Avoid printing out a brach to a basic block that
899 // immediately succeeds the current one.
901 void CWriter::visitBranchInst(BranchInst &I) {
902 if (I.isConditional()) {
903 if (isGotoCodeNeccessary(I.getParent(), I.getSuccessor(0))) {
905 writeOperand(I.getCondition());
908 printBranchToBlock(I.getParent(), I.getSuccessor(0), 2);
910 if (isGotoCodeNeccessary(I.getParent(), I.getSuccessor(1))) {
911 Out << " } else {\n";
912 printBranchToBlock(I.getParent(), I.getSuccessor(1), 2);
915 // First goto not neccesary, assume second one is...
917 writeOperand(I.getCondition());
920 printBranchToBlock(I.getParent(), I.getSuccessor(1), 2);
925 printBranchToBlock(I.getParent(), I.getSuccessor(0), 0);
931 void CWriter::visitBinaryOperator(Instruction &I) {
932 // binary instructions, shift instructions, setCond instructions.
933 if (isa<PointerType>(I.getType())) {
935 printType(Out, I.getType());
939 if (isa<PointerType>(I.getType())) Out << "(long long)";
940 writeOperand(I.getOperand(0));
942 switch (I.getOpcode()) {
943 case Instruction::Add: Out << " + "; break;
944 case Instruction::Sub: Out << " - "; break;
945 case Instruction::Mul: Out << "*"; break;
946 case Instruction::Div: Out << "/"; break;
947 case Instruction::Rem: Out << "%"; break;
948 case Instruction::And: Out << " & "; break;
949 case Instruction::Or: Out << " | "; break;
950 case Instruction::Xor: Out << " ^ "; break;
951 case Instruction::SetEQ: Out << " == "; break;
952 case Instruction::SetNE: Out << " != "; break;
953 case Instruction::SetLE: Out << " <= "; break;
954 case Instruction::SetGE: Out << " >= "; break;
955 case Instruction::SetLT: Out << " < "; break;
956 case Instruction::SetGT: Out << " > "; break;
957 case Instruction::Shl : Out << " << "; break;
958 case Instruction::Shr : Out << " >> "; break;
959 default: std::cerr << "Invalid operator type!" << I; abort();
962 if (isa<PointerType>(I.getType())) Out << "(long long)";
963 writeOperand(I.getOperand(1));
966 void CWriter::visitCastInst(CastInst &I) {
968 printType(Out, I.getType(), string(""),/*ignoreName*/false, /*namedContext*/false);
970 writeOperand(I.getOperand(0));
973 void CWriter::visitCallInst(CallInst &I) {
974 const PointerType *PTy = cast<PointerType>(I.getCalledValue()->getType());
975 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
976 const Type *RetTy = FTy->getReturnType();
978 writeOperand(I.getOperand(0));
981 if (I.getNumOperands() > 1) {
982 writeOperand(I.getOperand(1));
984 for (unsigned op = 2, Eop = I.getNumOperands(); op != Eop; ++op) {
986 writeOperand(I.getOperand(op));
992 void CWriter::visitMallocInst(MallocInst &I) {
994 printType(Out, I.getType());
995 Out << ")malloc(sizeof(";
996 printType(Out, I.getType()->getElementType());
999 if (I.isArrayAllocation()) {
1001 writeOperand(I.getOperand(0));
1006 void CWriter::visitAllocaInst(AllocaInst &I) {
1008 printType(Out, I.getType());
1009 Out << ") alloca(sizeof(";
1010 printType(Out, I.getType()->getElementType());
1012 if (I.isArrayAllocation()) {
1014 writeOperand(I.getOperand(0));
1019 void CWriter::visitFreeInst(FreeInst &I) {
1021 writeOperand(I.getOperand(0));
1025 void CWriter::printIndexingExpression(Value *Ptr, User::op_iterator I,
1026 User::op_iterator E) {
1027 bool HasImplicitAddress = false;
1028 // If accessing a global value with no indexing, avoid *(&GV) syndrome
1029 if (GlobalValue *V = dyn_cast<GlobalValue>(Ptr)) {
1030 HasImplicitAddress = true;
1031 } else if (ConstantPointerRef *CPR = dyn_cast<ConstantPointerRef>(Ptr)) {
1032 HasImplicitAddress = true;
1033 Ptr = CPR->getValue(); // Get to the global...
1037 if (!HasImplicitAddress)
1038 Out << "*"; // Implicit zero first argument: '*x' is equivalent to 'x[0]'
1040 writeOperandInternal(Ptr);
1044 const Constant *CI = dyn_cast<Constant>(I->get());
1045 if (HasImplicitAddress && (!CI || !CI->isNullValue()))
1048 writeOperandInternal(Ptr);
1050 if (HasImplicitAddress && (!CI || !CI->isNullValue())) {
1052 HasImplicitAddress = false; // HIA is only true if we haven't addressed yet
1055 assert(!HasImplicitAddress || (CI && CI->isNullValue()) &&
1056 "Can only have implicit address with direct accessing");
1058 if (HasImplicitAddress) {
1060 } else if (CI && CI->isNullValue() && I+1 != E) {
1061 // Print out the -> operator if possible...
1062 if ((*(I+1))->getType() == Type::UByteTy) {
1063 Out << (HasImplicitAddress ? "." : "->");
1064 Out << "field" << cast<ConstantUInt>(*(I+1))->getValue();
1070 if ((*I)->getType() == Type::LongTy) {
1075 Out << ".field" << cast<ConstantUInt>(*I)->getValue();
1079 void CWriter::visitLoadInst(LoadInst &I) {
1081 writeOperand(I.getOperand(0));
1084 void CWriter::visitStoreInst(StoreInst &I) {
1086 writeOperand(I.getPointerOperand());
1088 writeOperand(I.getOperand(0));
1091 void CWriter::visitGetElementPtrInst(GetElementPtrInst &I) {
1093 printIndexingExpression(I.getPointerOperand(), I.idx_begin(), I.idx_end());
1096 //===----------------------------------------------------------------------===//
1097 // External Interface declaration
1098 //===----------------------------------------------------------------------===//
1100 Pass *createWriteToCPass(std::ostream &o) { return new CWriter(o); }