1 //===-- Writer.cpp - Library for converting LLVM code to C ----------------===//
3 // This library converts LLVM code to C code, compilable by GCC.
5 //===----------------------------------------------------------------------===//
7 #include "llvm/Assembly/CWriter.h"
8 #include "llvm/Constants.h"
9 #include "llvm/DerivedTypes.h"
10 #include "llvm/Module.h"
11 #include "llvm/Instructions.h"
12 #include "llvm/Pass.h"
13 #include "llvm/SymbolTable.h"
14 #include "llvm/Intrinsics.h"
15 #include "llvm/SlotCalculator.h"
16 #include "llvm/Analysis/FindUsedTypes.h"
17 #include "llvm/Analysis/ConstantsScanner.h"
18 #include "llvm/Support/InstVisitor.h"
19 #include "llvm/Support/InstIterator.h"
20 #include "Support/StringExtras.h"
21 #include "Support/STLExtras.h"
27 class CWriter : public Pass, public InstVisitor<CWriter> {
29 SlotCalculator *Table;
30 const Module *TheModule;
31 std::map<const Type *, std::string> TypeNames;
32 std::set<const Value*> MangledGlobals;
35 std::map<const ConstantFP *, unsigned> FPConstantMap;
37 CWriter(std::ostream &o) : Out(o) {}
39 void getAnalysisUsage(AnalysisUsage &AU) const {
41 AU.addRequired<FindUsedTypes>();
44 virtual bool run(Module &M) {
46 Table = new SlotCalculator(&M, false);
49 // Ensure that all structure types have names...
50 bool Changed = nameAllUsedStructureTypes(M);
58 MangledGlobals.clear();
62 std::ostream &printType(std::ostream &Out, const Type *Ty,
63 const std::string &VariableName = "",
64 bool IgnoreName = false, bool namedContext = true);
66 void writeOperand(Value *Operand);
67 void writeOperandInternal(Value *Operand);
69 std::string getValueName(const Value *V);
72 bool nameAllUsedStructureTypes(Module &M);
73 void printModule(Module *M);
74 void printSymbolTable(const SymbolTable &ST);
75 void printContainedStructs(const Type *Ty, std::set<const StructType *> &);
76 void printGlobal(const GlobalVariable *GV);
77 void printFunctionSignature(const Function *F, bool Prototype);
79 void printFunction(Function *);
81 void printConstant(Constant *CPV);
82 void printConstantArray(ConstantArray *CPA);
84 // isInlinableInst - Attempt to inline instructions into their uses to build
85 // trees as much as possible. To do this, we have to consistently decide
86 // what is acceptable to inline, so that variable declarations don't get
87 // printed and an extra copy of the expr is not emitted.
89 static bool isInlinableInst(const Instruction &I) {
90 // Must be an expression, must be used exactly once. If it is dead, we
91 // emit it inline where it would go.
92 if (I.getType() == Type::VoidTy || I.use_size() != 1 ||
93 isa<TerminatorInst>(I) || isa<CallInst>(I) || isa<PHINode>(I) ||
94 isa<LoadInst>(I)) // Don't inline a load across a store!
97 // Only inline instruction it it's use is in the same BB as the inst.
98 return I.getParent() == cast<Instruction>(I.use_back())->getParent();
101 // Instruction visitation functions
102 friend class InstVisitor<CWriter>;
104 void visitReturnInst(ReturnInst &I);
105 void visitBranchInst(BranchInst &I);
106 void visitSwitchInst(SwitchInst &I);
108 void visitPHINode(PHINode &I);
109 void visitBinaryOperator(Instruction &I);
111 void visitCastInst (CastInst &I);
112 void visitCallInst (CallInst &I);
113 void visitShiftInst(ShiftInst &I) { visitBinaryOperator(I); }
115 void visitMallocInst(MallocInst &I);
116 void visitAllocaInst(AllocaInst &I);
117 void visitFreeInst (FreeInst &I);
118 void visitLoadInst (LoadInst &I);
119 void visitStoreInst (StoreInst &I);
120 void visitGetElementPtrInst(GetElementPtrInst &I);
121 void visitVarArgInst(VarArgInst &I);
123 void visitInstruction(Instruction &I) {
124 std::cerr << "C Writer does not know about " << I;
128 void outputLValue(Instruction *I) {
129 Out << " " << getValueName(I) << " = ";
131 void printBranchToBlock(BasicBlock *CurBlock, BasicBlock *SuccBlock,
133 void printIndexingExpression(Value *Ptr, User::op_iterator I,
134 User::op_iterator E);
138 // We dont want identifier names with ., space, - in them.
139 // So we replace them with _
140 static std::string makeNameProper(std::string x) {
142 for (std::string::iterator sI = x.begin(), sEnd = x.end(); sI != sEnd; sI++)
144 case '.': tmp += "d_"; break;
145 case ' ': tmp += "s_"; break;
146 case '-': tmp += "D_"; break;
153 std::string CWriter::getValueName(const Value *V) {
154 if (V->hasName()) { // Print out the label if it exists...
155 if (isa<GlobalValue>(V) && // Do not mangle globals...
156 (cast<GlobalValue>(V)->hasExternalLinkage() &&// Unless it's internal or
157 !MangledGlobals.count(V))) // Unless the name would collide if we don't
158 return makeNameProper(V->getName());
160 return "l" + utostr(V->getType()->getUniqueID()) + "_" +
161 makeNameProper(V->getName());
164 int Slot = Table->getValSlot(V);
165 assert(Slot >= 0 && "Invalid value!");
166 return "ltmp_" + itostr(Slot) + "_" + utostr(V->getType()->getUniqueID());
169 // A pointer type should not use parens around *'s alone, e.g., (**)
170 inline bool ptrTypeNameNeedsParens(const std::string &NameSoFar) {
171 return (NameSoFar.find_last_not_of('*') != std::string::npos);
174 // Pass the Type* and the variable name and this prints out the variable
177 std::ostream &CWriter::printType(std::ostream &Out, const Type *Ty,
178 const std::string &NameSoFar,
179 bool IgnoreName, bool namedContext) {
180 if (Ty->isPrimitiveType())
181 switch (Ty->getPrimitiveID()) {
182 case Type::VoidTyID: return Out << "void " << NameSoFar;
183 case Type::BoolTyID: return Out << "bool " << NameSoFar;
184 case Type::UByteTyID: return Out << "unsigned char " << NameSoFar;
185 case Type::SByteTyID: return Out << "signed char " << NameSoFar;
186 case Type::UShortTyID: return Out << "unsigned short " << NameSoFar;
187 case Type::ShortTyID: return Out << "short " << NameSoFar;
188 case Type::UIntTyID: return Out << "unsigned " << NameSoFar;
189 case Type::IntTyID: return Out << "int " << NameSoFar;
190 case Type::ULongTyID: return Out << "unsigned long long " << NameSoFar;
191 case Type::LongTyID: return Out << "signed long long " << NameSoFar;
192 case Type::FloatTyID: return Out << "float " << NameSoFar;
193 case Type::DoubleTyID: return Out << "double " << NameSoFar;
195 std::cerr << "Unknown primitive type: " << Ty << "\n";
199 // Check to see if the type is named.
200 if (!IgnoreName || isa<OpaqueType>(Ty)) {
201 std::map<const Type *, std::string>::iterator I = TypeNames.find(Ty);
202 if (I != TypeNames.end()) {
203 return Out << I->second << " " << NameSoFar;
207 switch (Ty->getPrimitiveID()) {
208 case Type::FunctionTyID: {
209 const FunctionType *MTy = cast<FunctionType>(Ty);
210 std::stringstream FunctionInards;
211 FunctionInards << " (" << NameSoFar << ") (";
212 for (FunctionType::ParamTypes::const_iterator
213 I = MTy->getParamTypes().begin(),
214 E = MTy->getParamTypes().end(); I != E; ++I) {
215 if (I != MTy->getParamTypes().begin())
216 FunctionInards << ", ";
217 printType(FunctionInards, *I, "");
219 if (MTy->isVarArg()) {
220 if (!MTy->getParamTypes().empty())
221 FunctionInards << ", ...";
222 } else if (MTy->getParamTypes().empty()) {
223 FunctionInards << "void";
225 FunctionInards << ")";
226 std::string tstr = FunctionInards.str();
227 printType(Out, MTy->getReturnType(), tstr);
230 case Type::StructTyID: {
231 const StructType *STy = cast<StructType>(Ty);
232 Out << NameSoFar + " {\n";
234 for (StructType::ElementTypes::const_iterator
235 I = STy->getElementTypes().begin(),
236 E = STy->getElementTypes().end(); I != E; ++I) {
238 printType(Out, *I, "field" + utostr(Idx++));
244 case Type::PointerTyID: {
245 const PointerType *PTy = cast<PointerType>(Ty);
246 std::string ptrName = "*" + NameSoFar;
248 // Do not need parens around "* NameSoFar" if NameSoFar consists only
249 // of zero or more '*' chars *and* this is not an unnamed pointer type
250 // such as the result type in a cast statement. Otherwise, enclose in ( ).
251 if (ptrTypeNameNeedsParens(NameSoFar) || !namedContext ||
252 PTy->getElementType()->getPrimitiveID() == Type::ArrayTyID)
253 ptrName = "(" + ptrName + ")"; //
255 return printType(Out, PTy->getElementType(), ptrName);
258 case Type::ArrayTyID: {
259 const ArrayType *ATy = cast<ArrayType>(Ty);
260 unsigned NumElements = ATy->getNumElements();
261 return printType(Out, ATy->getElementType(),
262 NameSoFar + "[" + utostr(NumElements) + "]");
265 case Type::OpaqueTyID: {
266 static int Count = 0;
267 std::string TyName = "struct opaque_" + itostr(Count++);
268 assert(TypeNames.find(Ty) == TypeNames.end());
269 TypeNames[Ty] = TyName;
270 return Out << TyName << " " << NameSoFar;
273 assert(0 && "Unhandled case in getTypeProps!");
280 void CWriter::printConstantArray(ConstantArray *CPA) {
282 // As a special case, print the array as a string if it is an array of
283 // ubytes or an array of sbytes with positive values.
285 const Type *ETy = CPA->getType()->getElementType();
286 bool isString = (ETy == Type::SByteTy || ETy == Type::UByteTy);
288 // Make sure the last character is a null char, as automatically added by C
289 if (CPA->getNumOperands() == 0 ||
290 !cast<Constant>(*(CPA->op_end()-1))->isNullValue())
295 // Do not include the last character, which we know is null
296 for (unsigned i = 0, e = CPA->getNumOperands()-1; i != e; ++i) {
297 unsigned char C = (ETy == Type::SByteTy) ?
298 (unsigned char)cast<ConstantSInt>(CPA->getOperand(i))->getValue() :
299 (unsigned char)cast<ConstantUInt>(CPA->getOperand(i))->getValue();
302 if (C == '"' || C == '\\')
308 case '\n': Out << "\\n"; break;
309 case '\t': Out << "\\t"; break;
310 case '\r': Out << "\\r"; break;
311 case '\v': Out << "\\v"; break;
312 case '\a': Out << "\\a"; break;
313 case '\"': Out << "\\\""; break;
314 case '\'': Out << "\\\'"; break;
317 Out << ( C/16 < 10) ? ( C/16 +'0') : ( C/16 -10+'A');
318 Out << ((C&15) < 10) ? ((C&15)+'0') : ((C&15)-10+'A');
326 if (CPA->getNumOperands()) {
328 printConstant(cast<Constant>(CPA->getOperand(0)));
329 for (unsigned i = 1, e = CPA->getNumOperands(); i != e; ++i) {
331 printConstant(cast<Constant>(CPA->getOperand(i)));
339 // printConstant - The LLVM Constant to C Constant converter.
340 void CWriter::printConstant(Constant *CPV) {
341 if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(CPV)) {
342 switch (CE->getOpcode()) {
343 case Instruction::Cast:
345 printType(Out, CPV->getType());
347 printConstant(CE->getOperand(0));
351 case Instruction::GetElementPtr:
353 printIndexingExpression(CE->getOperand(0),
354 CPV->op_begin()+1, CPV->op_end());
357 case Instruction::Add:
359 printConstant(CE->getOperand(0));
361 printConstant(CE->getOperand(1));
364 case Instruction::Sub:
366 printConstant(CE->getOperand(0));
368 printConstant(CE->getOperand(1));
373 std::cerr << "CWriter Error: Unhandled constant expression: "
379 switch (CPV->getType()->getPrimitiveID()) {
381 Out << (CPV == ConstantBool::False ? "0" : "1"); break;
382 case Type::SByteTyID:
383 case Type::ShortTyID:
384 Out << cast<ConstantSInt>(CPV)->getValue(); break;
386 if ((int)cast<ConstantSInt>(CPV)->getValue() == (int)0x80000000)
387 Out << "((int)0x80000000)"; // Handle MININT specially to avoid warning
389 Out << cast<ConstantSInt>(CPV)->getValue();
393 Out << cast<ConstantSInt>(CPV)->getValue() << "ll"; break;
395 case Type::UByteTyID:
396 case Type::UShortTyID:
397 Out << cast<ConstantUInt>(CPV)->getValue(); break;
399 Out << cast<ConstantUInt>(CPV)->getValue() << "u"; break;
400 case Type::ULongTyID:
401 Out << cast<ConstantUInt>(CPV)->getValue() << "ull"; break;
403 case Type::FloatTyID:
404 case Type::DoubleTyID: {
405 ConstantFP *FPC = cast<ConstantFP>(CPV);
406 std::map<const ConstantFP*, unsigned>::iterator I = FPConstantMap.find(FPC);
407 if (I != FPConstantMap.end()) {
408 // Because of FP precision problems we must load from a stack allocated
409 // value that holds the value in hex.
410 Out << "(*(" << (FPC->getType() == Type::FloatTy ? "float" : "double")
411 << "*)&FloatConstant" << I->second << ")";
413 Out << FPC->getValue();
418 case Type::ArrayTyID:
419 printConstantArray(cast<ConstantArray>(CPV));
422 case Type::StructTyID: {
424 if (CPV->getNumOperands()) {
426 printConstant(cast<Constant>(CPV->getOperand(0)));
427 for (unsigned i = 1, e = CPV->getNumOperands(); i != e; ++i) {
429 printConstant(cast<Constant>(CPV->getOperand(i)));
436 case Type::PointerTyID:
437 if (isa<ConstantPointerNull>(CPV)) {
439 printType(Out, CPV->getType());
440 Out << ")/*NULL*/0)";
442 } else if (ConstantPointerRef *CPR = dyn_cast<ConstantPointerRef>(CPV)) {
443 writeOperand(CPR->getValue());
448 std::cerr << "Unknown constant type: " << CPV << "\n";
453 void CWriter::writeOperandInternal(Value *Operand) {
454 if (Instruction *I = dyn_cast<Instruction>(Operand))
455 if (isInlinableInst(*I)) {
456 // Should we inline this instruction to build a tree?
463 if (Operand->hasName()) {
464 Out << getValueName(Operand);
465 } else if (Constant *CPV = dyn_cast<Constant>(Operand)) {
468 int Slot = Table->getValSlot(Operand);
469 assert(Slot >= 0 && "Malformed LLVM!");
470 Out << "ltmp_" << Slot << "_" << Operand->getType()->getUniqueID();
474 void CWriter::writeOperand(Value *Operand) {
475 if (isa<GlobalVariable>(Operand))
476 Out << "(&"; // Global variables are references as their addresses by llvm
478 writeOperandInternal(Operand);
480 if (isa<GlobalVariable>(Operand))
484 // nameAllUsedStructureTypes - If there are structure types in the module that
485 // are used but do not have names assigned to them in the symbol table yet then
486 // we assign them names now.
488 bool CWriter::nameAllUsedStructureTypes(Module &M) {
489 // Get a set of types that are used by the program...
490 std::set<const Type *> UT = getAnalysis<FindUsedTypes>().getTypes();
492 // Loop over the module symbol table, removing types from UT that are already
495 SymbolTable &MST = M.getSymbolTable();
496 if (MST.find(Type::TypeTy) != MST.end())
497 for (SymbolTable::type_iterator I = MST.type_begin(Type::TypeTy),
498 E = MST.type_end(Type::TypeTy); I != E; ++I)
499 UT.erase(cast<Type>(I->second));
501 // UT now contains types that are not named. Loop over it, naming structure
504 bool Changed = false;
505 for (std::set<const Type *>::const_iterator I = UT.begin(), E = UT.end();
507 if (const StructType *ST = dyn_cast<StructType>(*I)) {
508 ((Value*)ST)->setName("unnamed", &MST);
514 static void generateAllocaDecl(std::ostream& Out) {
515 // On SunOS, we need to insert the alloca macro & proto for the builtin.
516 Out << "#ifdef sun\n"
517 << "extern void *__builtin_alloca(unsigned long);\n"
518 << "#define alloca(x) __builtin_alloca(x)\n"
520 << "#include <alloca.h>\n"
524 void CWriter::printModule(Module *M) {
525 // Calculate which global values have names that will collide when we throw
526 // away type information.
527 { // Scope to delete the FoundNames set when we are done with it...
528 std::set<std::string> FoundNames;
529 for (Module::iterator I = M->begin(), E = M->end(); I != E; ++I)
530 if (I->hasName()) // If the global has a name...
531 if (FoundNames.count(I->getName())) // And the name is already used
532 MangledGlobals.insert(I); // Mangle the name
534 FoundNames.insert(I->getName()); // Otherwise, keep track of name
536 for (Module::giterator I = M->gbegin(), E = M->gend(); I != E; ++I)
537 if (I->hasName()) // If the global has a name...
538 if (FoundNames.count(I->getName())) // And the name is already used
539 MangledGlobals.insert(I); // Mangle the name
541 FoundNames.insert(I->getName()); // Otherwise, keep track of name
544 // get declaration for alloca
545 Out << "/* Provide Declarations */\n";
546 generateAllocaDecl(Out);
547 Out << "#include <stdarg.h>\n";
548 Out << "#include <setjmp.h>\n";
550 // Provide a definition for `bool' if not compiling with a C++ compiler.
552 << "#ifndef __cplusplus\ntypedef unsigned char bool;\n#endif\n"
554 << "\n\n/* Support for floating point constants */\n"
555 << "typedef unsigned long long ConstantDoubleTy;\n"
556 << "typedef unsigned int ConstantFloatTy;\n"
558 << "\n\n/* Global Declarations */\n";
560 // First output all the declarations for the program, because C requires
561 // Functions & globals to be declared before they are used.
564 // Loop over the symbol table, emitting all named constants...
565 printSymbolTable(M->getSymbolTable());
567 // Global variable declarations...
569 Out << "\n/* External Global Variable Declarations */\n";
570 for (Module::giterator I = M->gbegin(), E = M->gend(); I != E; ++I) {
571 if (I->hasExternalLinkage()) {
573 printType(Out, I->getType()->getElementType(), getValueName(I));
579 // Function declarations
581 Out << "\n/* Function Declarations */\n";
583 for (Module::iterator I = M->begin(), E = M->end(); I != E; ++I) {
584 // If the function is external and the name collides don't print it.
585 // Sometimes the bytecode likes to have multiple "declarations" for
586 // external functions
587 if ((I->hasInternalLinkage() || !MangledGlobals.count(I)) &&
588 !I->getIntrinsicID()) {
589 printFunctionSignature(I, true);
595 // Print Malloc prototype if needed
597 Out << "\n/* Malloc to make sun happy */\n";
598 Out << "extern void * malloc(size_t);\n\n";
601 // Output the global variable declerations
603 Out << "\n\n/* Global Variable Declerations */\n";
604 for (Module::giterator I = M->gbegin(), E = M->gend(); I != E; ++I)
605 if (!I->isExternal()) {
607 printType(Out, I->getType()->getElementType(), getValueName(I));
614 // Output the global variable definitions and contents...
616 Out << "\n\n/* Global Variable Definitions and Initialization */\n";
617 for (Module::giterator I = M->gbegin(), E = M->gend(); I != E; ++I)
618 if (!I->isExternal()) {
619 if (I->hasInternalLinkage())
621 printType(Out, I->getType()->getElementType(), getValueName(I));
624 writeOperand(I->getInitializer());
629 // Output all of the functions...
631 Out << "\n\n/* Function Bodies */\n";
632 for (Module::iterator I = M->begin(), E = M->end(); I != E; ++I)
638 /// printSymbolTable - Run through symbol table looking for type names. If a
639 /// type name is found, emit it's declaration...
641 void CWriter::printSymbolTable(const SymbolTable &ST) {
642 // If there are no type names, exit early.
643 if (ST.find(Type::TypeTy) == ST.end())
646 // We are only interested in the type plane of the symbol table...
647 SymbolTable::type_const_iterator I = ST.type_begin(Type::TypeTy);
648 SymbolTable::type_const_iterator End = ST.type_end(Type::TypeTy);
650 // Print out forward declarations for structure types before anything else!
651 Out << "/* Structure forward decls */\n";
652 for (; I != End; ++I)
653 if (const Type *STy = dyn_cast<StructType>(I->second)) {
654 std::string Name = "struct l_" + makeNameProper(I->first);
655 Out << Name << ";\n";
656 TypeNames.insert(std::make_pair(STy, Name));
661 // Now we can print out typedefs...
662 Out << "/* Typedefs */\n";
663 for (I = ST.type_begin(Type::TypeTy); I != End; ++I) {
664 const Type *Ty = cast<Type>(I->second);
665 std::string Name = "l_" + makeNameProper(I->first);
667 printType(Out, Ty, Name);
673 // Keep track of which structures have been printed so far...
674 std::set<const StructType *> StructPrinted;
676 // Loop over all structures then push them into the stack so they are
677 // printed in the correct order.
679 Out << "/* Structure contents */\n";
680 for (I = ST.type_begin(Type::TypeTy); I != End; ++I)
681 if (const StructType *STy = dyn_cast<StructType>(I->second))
682 printContainedStructs(STy, StructPrinted);
685 // Push the struct onto the stack and recursively push all structs
686 // this one depends on.
687 void CWriter::printContainedStructs(const Type *Ty,
688 std::set<const StructType*> &StructPrinted){
689 if (const StructType *STy = dyn_cast<StructType>(Ty)){
690 //Check to see if we have already printed this struct
691 if (StructPrinted.count(STy) == 0) {
692 // Print all contained types first...
693 for (StructType::ElementTypes::const_iterator
694 I = STy->getElementTypes().begin(),
695 E = STy->getElementTypes().end(); I != E; ++I) {
696 const Type *Ty1 = I->get();
697 if (isa<StructType>(Ty1) || isa<ArrayType>(Ty1))
698 printContainedStructs(*I, StructPrinted);
701 //Print structure type out..
702 StructPrinted.insert(STy);
703 std::string Name = TypeNames[STy];
704 printType(Out, STy, Name, true);
708 // If it is an array, check contained types and continue
709 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(Ty)){
710 const Type *Ty1 = ATy->getElementType();
711 if (isa<StructType>(Ty1) || isa<ArrayType>(Ty1))
712 printContainedStructs(Ty1, StructPrinted);
717 void CWriter::printFunctionSignature(const Function *F, bool Prototype) {
718 // If the program provides it's own malloc prototype we don't need
719 // to include the general one.
720 if (getValueName(F) == "malloc")
722 if (F->hasInternalLinkage()) Out << "static ";
723 // Loop over the arguments, printing them...
724 const FunctionType *FT = cast<FunctionType>(F->getFunctionType());
726 std::stringstream FunctionInards;
728 // Print out the name...
729 FunctionInards << getValueName(F) << "(";
731 if (!F->isExternal()) {
734 if (F->abegin()->hasName() || !Prototype)
735 ArgName = getValueName(F->abegin());
736 printType(FunctionInards, F->afront().getType(), ArgName);
737 for (Function::const_aiterator I = ++F->abegin(), E = F->aend();
739 FunctionInards << ", ";
740 if (I->hasName() || !Prototype)
741 ArgName = getValueName(I);
744 printType(FunctionInards, I->getType(), ArgName);
748 // Loop over the arguments, printing them...
749 for (FunctionType::ParamTypes::const_iterator I =
750 FT->getParamTypes().begin(),
751 E = FT->getParamTypes().end(); I != E; ++I) {
752 if (I != FT->getParamTypes().begin()) FunctionInards << ", ";
753 printType(FunctionInards, *I);
757 // Finish printing arguments... if this is a vararg function, print the ...,
758 // unless there are no known types, in which case, we just emit ().
760 if (FT->isVarArg() && !FT->getParamTypes().empty()) {
761 if (FT->getParamTypes().size()) FunctionInards << ", ";
762 FunctionInards << "..."; // Output varargs portion of signature!
764 FunctionInards << ")";
765 // Print out the return type and the entire signature for that matter
766 printType(Out, F->getReturnType(), FunctionInards.str());
771 void CWriter::printFunction(Function *F) {
772 if (F->isExternal()) return;
774 Table->incorporateFunction(F);
776 printFunctionSignature(F, false);
779 // print local variable information for the function
780 for (inst_iterator I = inst_begin(F), E = inst_end(F); I != E; ++I)
781 if ((*I)->getType() != Type::VoidTy && !isInlinableInst(**I)) {
783 printType(Out, (*I)->getType(), getValueName(*I));
786 if (isa<PHINode>(*I)) { // Print out PHI node temporaries as well...
788 printType(Out, (*I)->getType(), getValueName(*I)+"__PHI_TEMPORARY");
795 // Scan the function for floating point constants. If any FP constant is used
796 // in the function, we want to redirect it here so that we do not depend on
797 // the precision of the printed form.
799 unsigned FPCounter = 0;
800 for (constant_iterator I = constant_begin(F), E = constant_end(F); I != E;++I)
801 if (const ConstantFP *FPC = dyn_cast<ConstantFP>(*I))
802 if (FPConstantMap.find(FPC) == FPConstantMap.end()) {
803 double Val = FPC->getValue();
805 FPConstantMap[FPC] = FPCounter; // Number the FP constants
807 if (FPC->getType() == Type::DoubleTy)
808 Out << " const ConstantDoubleTy FloatConstant" << FPCounter++
809 << " = 0x" << std::hex << *(unsigned long long*)&Val << std::dec
810 << "; /* " << Val << " */\n";
811 else if (FPC->getType() == Type::FloatTy) {
813 Out << " const ConstantFloatTy FloatConstant" << FPCounter++
814 << " = 0x" << std::hex << *(unsigned*)&fVal << std::dec
815 << "; /* " << Val << " */\n";
817 assert(0 && "Unknown float type!");
822 // print the basic blocks
823 for (Function::iterator BB = F->begin(), E = F->end(); BB != E; ++BB) {
824 BasicBlock *Prev = BB->getPrev();
826 // Don't print the label for the basic block if there are no uses, or if the
827 // only terminator use is the precessor basic block's terminator. We have
828 // to scan the use list because PHI nodes use basic blocks too but do not
829 // require a label to be generated.
831 bool NeedsLabel = false;
832 for (Value::use_iterator UI = BB->use_begin(), UE = BB->use_end();
834 if (TerminatorInst *TI = dyn_cast<TerminatorInst>(*UI))
835 if (TI != Prev->getTerminator() ||
836 isa<SwitchInst>(Prev->getTerminator())) {
841 if (NeedsLabel) Out << getValueName(BB) << ":\n";
843 // Output all of the instructions in the basic block...
844 for (BasicBlock::iterator II = BB->begin(), E = --BB->end(); II != E; ++II){
845 if (!isInlinableInst(*II)) {
846 if (II->getType() != Type::VoidTy)
855 // Don't emit prefix or suffix for the terminator...
856 visit(*BB->getTerminator());
860 Table->purgeFunction();
861 FPConstantMap.clear();
864 // Specific Instruction type classes... note that all of the casts are
865 // neccesary because we use the instruction classes as opaque types...
867 void CWriter::visitReturnInst(ReturnInst &I) {
868 // Don't output a void return if this is the last basic block in the function
869 if (I.getNumOperands() == 0 &&
870 &*--I.getParent()->getParent()->end() == I.getParent() &&
871 !I.getParent()->size() == 1) {
876 if (I.getNumOperands()) {
878 writeOperand(I.getOperand(0));
883 void CWriter::visitSwitchInst(SwitchInst &SI) {
885 writeOperand(SI.getOperand(0));
886 Out << ") {\n default:\n";
887 printBranchToBlock(SI.getParent(), SI.getDefaultDest(), 2);
889 for (unsigned i = 2, e = SI.getNumOperands(); i != e; i += 2) {
891 writeOperand(SI.getOperand(i));
893 BasicBlock *Succ = cast<BasicBlock>(SI.getOperand(i+1));
894 printBranchToBlock(SI.getParent(), Succ, 2);
895 if (Succ == SI.getParent()->getNext())
902 static bool isGotoCodeNeccessary(BasicBlock *From, BasicBlock *To) {
903 // If PHI nodes need copies, we need the copy code...
904 if (isa<PHINode>(To->front()) ||
905 From->getNext() != To) // Not directly successor, need goto
908 // Otherwise we don't need the code.
912 void CWriter::printBranchToBlock(BasicBlock *CurBB, BasicBlock *Succ,
914 for (BasicBlock::iterator I = Succ->begin();
915 PHINode *PN = dyn_cast<PHINode>(I); ++I) {
916 // now we have to do the printing
917 Out << std::string(Indent, ' ');
918 Out << " " << getValueName(I) << "__PHI_TEMPORARY = ";
919 writeOperand(PN->getIncomingValue(PN->getBasicBlockIndex(CurBB)));
920 Out << "; /* for PHI node */\n";
923 if (CurBB->getNext() != Succ) {
924 Out << std::string(Indent, ' ') << " goto ";
930 // Brach instruction printing - Avoid printing out a brach to a basic block that
931 // immediately succeeds the current one.
933 void CWriter::visitBranchInst(BranchInst &I) {
934 if (I.isConditional()) {
935 if (isGotoCodeNeccessary(I.getParent(), I.getSuccessor(0))) {
937 writeOperand(I.getCondition());
940 printBranchToBlock(I.getParent(), I.getSuccessor(0), 2);
942 if (isGotoCodeNeccessary(I.getParent(), I.getSuccessor(1))) {
943 Out << " } else {\n";
944 printBranchToBlock(I.getParent(), I.getSuccessor(1), 2);
947 // First goto not neccesary, assume second one is...
949 writeOperand(I.getCondition());
952 printBranchToBlock(I.getParent(), I.getSuccessor(1), 2);
957 printBranchToBlock(I.getParent(), I.getSuccessor(0), 0);
962 // PHI nodes get copied into temporary values at the end of predecessor basic
963 // blocks. We now need to copy these temporary values into the REAL value for
965 void CWriter::visitPHINode(PHINode &I) {
967 Out << "__PHI_TEMPORARY";
971 void CWriter::visitBinaryOperator(Instruction &I) {
972 // binary instructions, shift instructions, setCond instructions.
973 assert(!isa<PointerType>(I.getType()));
975 writeOperand(I.getOperand(0));
977 switch (I.getOpcode()) {
978 case Instruction::Add: Out << " + "; break;
979 case Instruction::Sub: Out << " - "; break;
980 case Instruction::Mul: Out << "*"; break;
981 case Instruction::Div: Out << "/"; break;
982 case Instruction::Rem: Out << "%"; break;
983 case Instruction::And: Out << " & "; break;
984 case Instruction::Or: Out << " | "; break;
985 case Instruction::Xor: Out << " ^ "; break;
986 case Instruction::SetEQ: Out << " == "; break;
987 case Instruction::SetNE: Out << " != "; break;
988 case Instruction::SetLE: Out << " <= "; break;
989 case Instruction::SetGE: Out << " >= "; break;
990 case Instruction::SetLT: Out << " < "; break;
991 case Instruction::SetGT: Out << " > "; break;
992 case Instruction::Shl : Out << " << "; break;
993 case Instruction::Shr : Out << " >> "; break;
994 default: std::cerr << "Invalid operator type!" << I; abort();
997 writeOperand(I.getOperand(1));
1000 void CWriter::visitCastInst(CastInst &I) {
1001 if (I.getType() == Type::BoolTy) {
1003 writeOperand(I.getOperand(0));
1008 printType(Out, I.getType(), "", /*ignoreName*/false, /*namedContext*/false);
1010 if (isa<PointerType>(I.getType())&&I.getOperand(0)->getType()->isIntegral() ||
1011 isa<PointerType>(I.getOperand(0)->getType())&&I.getType()->isIntegral()) {
1012 // Avoid "cast to pointer from integer of different size" warnings
1016 writeOperand(I.getOperand(0));
1019 void CWriter::visitCallInst(CallInst &I) {
1020 // Handle intrinsic function calls first...
1021 if (Function *F = I.getCalledFunction())
1022 if (LLVMIntrinsic::ID ID = (LLVMIntrinsic::ID)F->getIntrinsicID()) {
1024 default: assert(0 && "Unknown LLVM intrinsic!");
1025 case LLVMIntrinsic::va_start:
1026 Out << "va_start((va_list)*";
1027 writeOperand(I.getOperand(1));
1029 // Output the last argument to the enclosing function...
1030 writeOperand(&I.getParent()->getParent()->aback());
1033 case LLVMIntrinsic::va_end:
1034 Out << "va_end((va_list)*";
1035 writeOperand(I.getOperand(1));
1038 case LLVMIntrinsic::va_copy:
1039 Out << "va_copy((va_list)*";
1040 writeOperand(I.getOperand(1));
1041 Out << ", (va_list)";
1042 writeOperand(I.getOperand(2));
1046 case LLVMIntrinsic::setjmp:
1047 Out << "setjmp((jmp_buf)";
1048 writeOperand(I.getOperand(1));
1051 case LLVMIntrinsic::longjmp:
1052 Out << "longjmp((jmp_buf)";
1053 writeOperand(I.getOperand(1));
1055 writeOperand(I.getOperand(2));
1061 const PointerType *PTy = cast<PointerType>(I.getCalledValue()->getType());
1062 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
1063 const Type *RetTy = FTy->getReturnType();
1065 writeOperand(I.getOperand(0));
1068 if (I.getNumOperands() > 1) {
1069 writeOperand(I.getOperand(1));
1071 for (unsigned op = 2, Eop = I.getNumOperands(); op != Eop; ++op) {
1073 writeOperand(I.getOperand(op));
1079 void CWriter::visitMallocInst(MallocInst &I) {
1081 printType(Out, I.getType());
1082 Out << ")malloc(sizeof(";
1083 printType(Out, I.getType()->getElementType());
1086 if (I.isArrayAllocation()) {
1088 writeOperand(I.getOperand(0));
1093 void CWriter::visitAllocaInst(AllocaInst &I) {
1095 printType(Out, I.getType());
1096 Out << ") alloca(sizeof(";
1097 printType(Out, I.getType()->getElementType());
1099 if (I.isArrayAllocation()) {
1101 writeOperand(I.getOperand(0));
1106 void CWriter::visitFreeInst(FreeInst &I) {
1108 writeOperand(I.getOperand(0));
1112 void CWriter::printIndexingExpression(Value *Ptr, User::op_iterator I,
1113 User::op_iterator E) {
1114 bool HasImplicitAddress = false;
1115 // If accessing a global value with no indexing, avoid *(&GV) syndrome
1116 if (GlobalValue *V = dyn_cast<GlobalValue>(Ptr)) {
1117 HasImplicitAddress = true;
1118 } else if (ConstantPointerRef *CPR = dyn_cast<ConstantPointerRef>(Ptr)) {
1119 HasImplicitAddress = true;
1120 Ptr = CPR->getValue(); // Get to the global...
1124 if (!HasImplicitAddress)
1125 Out << "*"; // Implicit zero first argument: '*x' is equivalent to 'x[0]'
1127 writeOperandInternal(Ptr);
1131 const Constant *CI = dyn_cast<Constant>(I);
1132 if (HasImplicitAddress && (!CI || !CI->isNullValue()))
1135 writeOperandInternal(Ptr);
1137 if (HasImplicitAddress && (!CI || !CI->isNullValue())) {
1139 HasImplicitAddress = false; // HIA is only true if we haven't addressed yet
1142 assert(!HasImplicitAddress || (CI && CI->isNullValue()) &&
1143 "Can only have implicit address with direct accessing");
1145 if (HasImplicitAddress) {
1147 } else if (CI && CI->isNullValue() && I+1 != E) {
1148 // Print out the -> operator if possible...
1149 if ((*(I+1))->getType() == Type::UByteTy) {
1150 Out << (HasImplicitAddress ? "." : "->");
1151 Out << "field" << cast<ConstantUInt>(*(I+1))->getValue();
1157 if ((*I)->getType() == Type::LongTy) {
1162 Out << ".field" << cast<ConstantUInt>(*I)->getValue();
1166 void CWriter::visitLoadInst(LoadInst &I) {
1168 writeOperand(I.getOperand(0));
1171 void CWriter::visitStoreInst(StoreInst &I) {
1173 writeOperand(I.getPointerOperand());
1175 writeOperand(I.getOperand(0));
1178 void CWriter::visitGetElementPtrInst(GetElementPtrInst &I) {
1180 printIndexingExpression(I.getPointerOperand(), I.idx_begin(), I.idx_end());
1183 void CWriter::visitVarArgInst(VarArgInst &I) {
1184 Out << "va_arg((va_list)*";
1185 writeOperand(I.getOperand(0));
1187 printType(Out, I.getType(), "", /*ignoreName*/false, /*namedContext*/false);
1192 //===----------------------------------------------------------------------===//
1193 // External Interface declaration
1194 //===----------------------------------------------------------------------===//
1196 Pass *createWriteToCPass(std::ostream &o) { return new CWriter(o); }