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/Instructions.h"
11 #include "llvm/Pass.h"
12 #include "llvm/SymbolTable.h"
13 #include "llvm/SlotCalculator.h"
14 #include "llvm/Analysis/FindUsedTypes.h"
15 #include "llvm/Analysis/ConstantsScanner.h"
16 #include "llvm/Support/InstVisitor.h"
17 #include "llvm/Support/InstIterator.h"
18 #include "Support/StringExtras.h"
19 #include "Support/STLExtras.h"
25 class CWriter : public Pass, public InstVisitor<CWriter> {
27 SlotCalculator *Table;
28 const Module *TheModule;
29 std::map<const Type *, std::string> TypeNames;
30 std::set<const Value*> MangledGlobals;
33 std::map<const ConstantFP *, unsigned> FPConstantMap;
35 CWriter(std::ostream &o) : Out(o) {}
37 void getAnalysisUsage(AnalysisUsage &AU) const {
39 AU.addRequired<FindUsedTypes>();
42 virtual bool run(Module &M) {
44 Table = new SlotCalculator(&M, false);
47 // Ensure that all structure types have names...
48 bool Changed = nameAllUsedStructureTypes(M);
56 MangledGlobals.clear();
60 std::ostream &printType(std::ostream &Out, const Type *Ty,
61 const std::string &VariableName = "",
62 bool IgnoreName = false, bool namedContext = true);
64 void writeOperand(Value *Operand);
65 void writeOperandInternal(Value *Operand);
67 std::string getValueName(const Value *V);
70 bool nameAllUsedStructureTypes(Module &M);
71 void printModule(Module *M);
72 void printSymbolTable(const SymbolTable &ST);
73 void printContainedStructs(const Type *Ty, std::set<const StructType *> &);
74 void printGlobal(const GlobalVariable *GV);
75 void printFunctionSignature(const Function *F, bool Prototype);
77 void printFunction(Function *);
79 void printConstant(Constant *CPV);
80 void printConstantArray(ConstantArray *CPA);
82 // isInlinableInst - Attempt to inline instructions into their uses to build
83 // trees as much as possible. To do this, we have to consistently decide
84 // what is acceptable to inline, so that variable declarations don't get
85 // printed and an extra copy of the expr is not emitted.
87 static bool isInlinableInst(const Instruction &I) {
88 // Must be an expression, must be used exactly once. If it is dead, we
89 // emit it inline where it would go.
90 if (I.getType() == Type::VoidTy || I.use_size() != 1 ||
91 isa<TerminatorInst>(I) || isa<CallInst>(I) || isa<PHINode>(I) ||
92 isa<LoadInst>(I)) // Don't inline a load across a store!
95 // Only inline instruction it it's use is in the same BB as the inst.
96 return I.getParent() == cast<Instruction>(I.use_back())->getParent();
99 // Instruction visitation functions
100 friend class InstVisitor<CWriter>;
102 void visitReturnInst(ReturnInst &I);
103 void visitBranchInst(BranchInst &I);
104 void visitSwitchInst(SwitchInst &I);
106 void visitPHINode(PHINode &I) {}
107 void visitBinaryOperator(Instruction &I);
109 void visitCastInst (CastInst &I);
110 void visitCallInst (CallInst &I);
111 void visitShiftInst(ShiftInst &I) { visitBinaryOperator(I); }
113 void visitMallocInst(MallocInst &I);
114 void visitAllocaInst(AllocaInst &I);
115 void visitFreeInst (FreeInst &I);
116 void visitLoadInst (LoadInst &I);
117 void visitStoreInst (StoreInst &I);
118 void visitGetElementPtrInst(GetElementPtrInst &I);
120 void visitInstruction(Instruction &I) {
121 std::cerr << "C Writer does not know about " << I;
125 void outputLValue(Instruction *I) {
126 Out << " " << getValueName(I) << " = ";
128 void printBranchToBlock(BasicBlock *CurBlock, BasicBlock *SuccBlock,
130 void printIndexingExpression(Value *Ptr, User::op_iterator I,
131 User::op_iterator E);
135 // We dont want identifier names with ., space, - in them.
136 // So we replace them with _
137 static std::string makeNameProper(std::string x) {
139 for (std::string::iterator sI = x.begin(), sEnd = x.end(); sI != sEnd; sI++)
141 case '.': tmp += "d_"; break;
142 case ' ': tmp += "s_"; break;
143 case '-': tmp += "D_"; break;
150 std::string CWriter::getValueName(const Value *V) {
151 if (V->hasName()) { // Print out the label if it exists...
152 if (isa<GlobalValue>(V) && // Do not mangle globals...
153 (cast<GlobalValue>(V)->hasExternalLinkage() &&// Unless it's internal or
154 !MangledGlobals.count(V))) // Unless the name would collide if we don't
155 return makeNameProper(V->getName());
157 return "l" + utostr(V->getType()->getUniqueID()) + "_" +
158 makeNameProper(V->getName());
161 int Slot = Table->getValSlot(V);
162 assert(Slot >= 0 && "Invalid value!");
163 return "ltmp_" + itostr(Slot) + "_" + utostr(V->getType()->getUniqueID());
166 // A pointer type should not use parens around *'s alone, e.g., (**)
167 inline bool ptrTypeNameNeedsParens(const std::string &NameSoFar) {
168 return (NameSoFar.find_last_not_of('*') != std::string::npos);
171 // Pass the Type* and the variable name and this prints out the variable
174 std::ostream &CWriter::printType(std::ostream &Out, const Type *Ty,
175 const std::string &NameSoFar,
176 bool IgnoreName, bool namedContext) {
177 if (Ty->isPrimitiveType())
178 switch (Ty->getPrimitiveID()) {
179 case Type::VoidTyID: return Out << "void " << NameSoFar;
180 case Type::BoolTyID: return Out << "bool " << NameSoFar;
181 case Type::UByteTyID: return Out << "unsigned char " << NameSoFar;
182 case Type::SByteTyID: return Out << "signed char " << NameSoFar;
183 case Type::UShortTyID: return Out << "unsigned short " << NameSoFar;
184 case Type::ShortTyID: return Out << "short " << NameSoFar;
185 case Type::UIntTyID: return Out << "unsigned " << NameSoFar;
186 case Type::IntTyID: return Out << "int " << NameSoFar;
187 case Type::ULongTyID: return Out << "unsigned long long " << NameSoFar;
188 case Type::LongTyID: return Out << "signed long long " << NameSoFar;
189 case Type::FloatTyID: return Out << "float " << NameSoFar;
190 case Type::DoubleTyID: return Out << "double " << NameSoFar;
192 std::cerr << "Unknown primitive type: " << Ty << "\n";
196 // Check to see if the type is named.
197 if (!IgnoreName || isa<OpaqueType>(Ty)) {
198 std::map<const Type *, std::string>::iterator I = TypeNames.find(Ty);
199 if (I != TypeNames.end()) {
200 return Out << I->second << " " << NameSoFar;
204 switch (Ty->getPrimitiveID()) {
205 case Type::FunctionTyID: {
206 const FunctionType *MTy = cast<FunctionType>(Ty);
207 std::stringstream FunctionInards;
208 FunctionInards << " (" << NameSoFar << ") (";
209 for (FunctionType::ParamTypes::const_iterator
210 I = MTy->getParamTypes().begin(),
211 E = MTy->getParamTypes().end(); I != E; ++I) {
212 if (I != MTy->getParamTypes().begin())
213 FunctionInards << ", ";
214 printType(FunctionInards, *I, "");
216 if (MTy->isVarArg()) {
217 if (!MTy->getParamTypes().empty())
218 FunctionInards << ", ";
219 FunctionInards << "...";
221 FunctionInards << ")";
222 std::string tstr = FunctionInards.str();
223 printType(Out, MTy->getReturnType(), tstr);
226 case Type::StructTyID: {
227 const StructType *STy = cast<StructType>(Ty);
228 Out << NameSoFar + " {\n";
230 for (StructType::ElementTypes::const_iterator
231 I = STy->getElementTypes().begin(),
232 E = STy->getElementTypes().end(); I != E; ++I) {
234 printType(Out, *I, "field" + utostr(Idx++));
240 case Type::PointerTyID: {
241 const PointerType *PTy = cast<PointerType>(Ty);
242 std::string ptrName = "*" + NameSoFar;
244 // Do not need parens around "* NameSoFar" if NameSoFar consists only
245 // of zero or more '*' chars *and* this is not an unnamed pointer type
246 // such as the result type in a cast statement. Otherwise, enclose in ( ).
247 if (ptrTypeNameNeedsParens(NameSoFar) || !namedContext ||
248 PTy->getElementType()->getPrimitiveID() == Type::ArrayTyID)
249 ptrName = "(" + ptrName + ")"; //
251 return printType(Out, PTy->getElementType(), ptrName);
254 case Type::ArrayTyID: {
255 const ArrayType *ATy = cast<ArrayType>(Ty);
256 unsigned NumElements = ATy->getNumElements();
257 return printType(Out, ATy->getElementType(),
258 NameSoFar + "[" + utostr(NumElements) + "]");
261 case Type::OpaqueTyID: {
262 static int Count = 0;
263 std::string TyName = "struct opaque_" + itostr(Count++);
264 assert(TypeNames.find(Ty) == TypeNames.end());
265 TypeNames[Ty] = TyName;
266 return Out << TyName << " " << NameSoFar;
269 assert(0 && "Unhandled case in getTypeProps!");
276 void CWriter::printConstantArray(ConstantArray *CPA) {
278 // As a special case, print the array as a string if it is an array of
279 // ubytes or an array of sbytes with positive values.
281 const Type *ETy = CPA->getType()->getElementType();
282 bool isString = (ETy == Type::SByteTy || ETy == Type::UByteTy);
284 // Make sure the last character is a null char, as automatically added by C
285 if (CPA->getNumOperands() == 0 ||
286 !cast<Constant>(*(CPA->op_end()-1))->isNullValue())
291 // Do not include the last character, which we know is null
292 for (unsigned i = 0, e = CPA->getNumOperands()-1; i != e; ++i) {
293 unsigned char C = (ETy == Type::SByteTy) ?
294 (unsigned char)cast<ConstantSInt>(CPA->getOperand(i))->getValue() :
295 (unsigned char)cast<ConstantUInt>(CPA->getOperand(i))->getValue();
298 if (C == '"' || C == '\\')
304 case '\n': Out << "\\n"; break;
305 case '\t': Out << "\\t"; break;
306 case '\r': Out << "\\r"; break;
307 case '\v': Out << "\\v"; break;
308 case '\a': Out << "\\a"; break;
309 case '\"': Out << "\\\""; break;
310 case '\'': Out << "\\\'"; break;
313 Out << ( C/16 < 10) ? ( C/16 +'0') : ( C/16 -10+'A');
314 Out << ((C&15) < 10) ? ((C&15)+'0') : ((C&15)-10+'A');
322 if (CPA->getNumOperands()) {
324 printConstant(cast<Constant>(CPA->getOperand(0)));
325 for (unsigned i = 1, e = CPA->getNumOperands(); i != e; ++i) {
327 printConstant(cast<Constant>(CPA->getOperand(i)));
335 // printConstant - The LLVM Constant to C Constant converter.
336 void CWriter::printConstant(Constant *CPV) {
337 if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(CPV)) {
338 switch (CE->getOpcode()) {
339 case Instruction::Cast:
341 printType(Out, CPV->getType());
343 printConstant(cast<Constant>(CPV->getOperand(0)));
347 case Instruction::GetElementPtr:
349 printIndexingExpression(CPV->getOperand(0),
350 CPV->op_begin()+1, CPV->op_end());
353 case Instruction::Add:
355 printConstant(cast<Constant>(CPV->getOperand(0)));
357 printConstant(cast<Constant>(CPV->getOperand(1)));
360 case Instruction::Sub:
362 printConstant(cast<Constant>(CPV->getOperand(0)));
364 printConstant(cast<Constant>(CPV->getOperand(1)));
369 std::cerr << "CWriter Error: Unhandled constant expression: "
375 switch (CPV->getType()->getPrimitiveID()) {
377 Out << (CPV == ConstantBool::False ? "0" : "1"); break;
378 case Type::SByteTyID:
379 case Type::ShortTyID:
381 Out << cast<ConstantSInt>(CPV)->getValue(); break;
383 Out << cast<ConstantSInt>(CPV)->getValue() << "ll"; break;
385 case Type::UByteTyID:
386 case Type::UShortTyID:
387 Out << cast<ConstantUInt>(CPV)->getValue(); break;
389 Out << cast<ConstantUInt>(CPV)->getValue() << "u"; break;
390 case Type::ULongTyID:
391 Out << cast<ConstantUInt>(CPV)->getValue() << "ull"; break;
393 case Type::FloatTyID:
394 case Type::DoubleTyID: {
395 ConstantFP *FPC = cast<ConstantFP>(CPV);
396 std::map<const ConstantFP*, unsigned>::iterator I = FPConstantMap.find(FPC);
397 if (I != FPConstantMap.end()) {
398 // Because of FP precision problems we must load from a stack allocated
399 // value that holds the value in hex.
400 Out << "(*(" << (FPC->getType() == Type::FloatTy ? "float" : "double")
401 << "*)&FloatConstant" << I->second << ")";
403 Out << FPC->getValue();
408 case Type::ArrayTyID:
409 printConstantArray(cast<ConstantArray>(CPV));
412 case Type::StructTyID: {
414 if (CPV->getNumOperands()) {
416 printConstant(cast<Constant>(CPV->getOperand(0)));
417 for (unsigned i = 1, e = CPV->getNumOperands(); i != e; ++i) {
419 printConstant(cast<Constant>(CPV->getOperand(i)));
426 case Type::PointerTyID:
427 if (isa<ConstantPointerNull>(CPV)) {
430 } else if (ConstantPointerRef *CPR = dyn_cast<ConstantPointerRef>(CPV)) {
431 writeOperand(CPR->getValue());
436 std::cerr << "Unknown constant type: " << CPV << "\n";
441 void CWriter::writeOperandInternal(Value *Operand) {
442 if (Instruction *I = dyn_cast<Instruction>(Operand))
443 if (isInlinableInst(*I)) {
444 // Should we inline this instruction to build a tree?
451 if (Operand->hasName()) {
452 Out << getValueName(Operand);
453 } else if (Constant *CPV = dyn_cast<Constant>(Operand)) {
456 int Slot = Table->getValSlot(Operand);
457 assert(Slot >= 0 && "Malformed LLVM!");
458 Out << "ltmp_" << Slot << "_" << Operand->getType()->getUniqueID();
462 void CWriter::writeOperand(Value *Operand) {
463 if (isa<GlobalVariable>(Operand))
464 Out << "(&"; // Global variables are references as their addresses by llvm
466 writeOperandInternal(Operand);
468 if (isa<GlobalVariable>(Operand))
472 // nameAllUsedStructureTypes - If there are structure types in the module that
473 // are used but do not have names assigned to them in the symbol table yet then
474 // we assign them names now.
476 bool CWriter::nameAllUsedStructureTypes(Module &M) {
477 // Get a set of types that are used by the program...
478 std::set<const Type *> UT = getAnalysis<FindUsedTypes>().getTypes();
480 // Loop over the module symbol table, removing types from UT that are already
483 SymbolTable &MST = M.getSymbolTable();
484 if (MST.find(Type::TypeTy) != MST.end())
485 for (SymbolTable::type_iterator I = MST.type_begin(Type::TypeTy),
486 E = MST.type_end(Type::TypeTy); I != E; ++I)
487 UT.erase(cast<Type>(I->second));
489 // UT now contains types that are not named. Loop over it, naming structure
492 bool Changed = false;
493 for (std::set<const Type *>::const_iterator I = UT.begin(), E = UT.end();
495 if (const StructType *ST = dyn_cast<StructType>(*I)) {
496 ((Value*)ST)->setName("unnamed", &MST);
502 static void generateAllocaDecl(std::ostream& Out) {
503 // On SunOS, we need to insert the alloca macro & proto for the builtin.
504 Out << "#ifdef sun\n"
505 << "extern void *__builtin_alloca(unsigned long);\n"
506 << "#define alloca(x) __builtin_alloca(x)\n"
508 << "#include <alloca.h>\n"
512 void CWriter::printModule(Module *M) {
513 // Calculate which global values have names that will collide when we throw
514 // away type information.
515 { // Scope to delete the FoundNames set when we are done with it...
516 std::set<std::string> FoundNames;
517 for (Module::iterator I = M->begin(), E = M->end(); I != E; ++I)
518 if (I->hasName()) // If the global has a name...
519 if (FoundNames.count(I->getName())) // And the name is already used
520 MangledGlobals.insert(I); // Mangle the name
522 FoundNames.insert(I->getName()); // Otherwise, keep track of name
524 for (Module::giterator I = M->gbegin(), E = M->gend(); I != E; ++I)
525 if (I->hasName()) // If the global has a name...
526 if (FoundNames.count(I->getName())) // And the name is already used
527 MangledGlobals.insert(I); // Mangle the name
529 FoundNames.insert(I->getName()); // Otherwise, keep track of name
532 // printing stdlib inclusion
533 //Out << "#include <stdlib.h>\n";
535 // get declaration for alloca
536 Out << "/* Provide Declarations */\n";
537 generateAllocaDecl(Out);
539 // Provide a definition for null if one does not already exist,
540 // and for `bool' if not compiling with a C++ compiler.
541 Out << "#ifndef NULL\n#define NULL 0\n#endif\n\n"
542 << "#ifndef __cplusplus\ntypedef unsigned char bool;\n#endif\n"
544 << "\n\n/* Support for floating point constants */\n"
545 << "typedef unsigned long long ConstantDoubleTy;\n"
546 << "typedef unsigned int ConstantFloatTy;\n"
548 << "\n\n/* Global Declarations */\n";
550 // First output all the declarations for the program, because C requires
551 // Functions & globals to be declared before they are used.
554 // Loop over the symbol table, emitting all named constants...
555 printSymbolTable(M->getSymbolTable());
557 // Global variable declarations...
559 Out << "\n/* External Global Variable Declarations */\n";
560 for (Module::giterator I = M->gbegin(), E = M->gend(); I != E; ++I) {
561 if (I->hasExternalLinkage()) {
563 printType(Out, I->getType()->getElementType(), getValueName(I));
569 // Function declarations
571 Out << "\n/* Function Declarations */\n";
573 for (Module::iterator I = M->begin(), E = M->end(); I != E; ++I) {
574 // If the function is external and the name collides don't print it.
575 // Sometimes the bytecode likes to have multiple "declerations" for
576 // external functions
577 if (I->hasInternalLinkage() || !MangledGlobals.count(I)){
578 printFunctionSignature(I, true);
584 // Print Malloc prototype if needed
586 Out << "\n/* Malloc to make sun happy */\n";
587 Out << "extern void * malloc(size_t);\n\n";
590 // Output the global variable declerations
592 Out << "\n\n/* Global Variable Declerations */\n";
593 for (Module::giterator I = M->gbegin(), E = M->gend(); I != E; ++I)
594 if (!I->isExternal()) {
596 printType(Out, I->getType()->getElementType(), getValueName(I));
603 // Output the global variable definitions and contents...
605 Out << "\n\n/* Global Variable Definitions and Initialization */\n";
606 for (Module::giterator I = M->gbegin(), E = M->gend(); I != E; ++I)
607 if (!I->isExternal()) {
608 if (I->hasInternalLinkage())
610 printType(Out, I->getType()->getElementType(), getValueName(I));
613 writeOperand(I->getInitializer());
618 // Output all of the functions...
620 Out << "\n\n/* Function Bodies */\n";
621 for (Module::iterator I = M->begin(), E = M->end(); I != E; ++I)
627 /// printSymbolTable - Run through symbol table looking for type names. If a
628 /// type name is found, emit it's declaration...
630 void CWriter::printSymbolTable(const SymbolTable &ST) {
631 // If there are no type names, exit early.
632 if (ST.find(Type::TypeTy) == ST.end())
635 // We are only interested in the type plane of the symbol table...
636 SymbolTable::type_const_iterator I = ST.type_begin(Type::TypeTy);
637 SymbolTable::type_const_iterator End = ST.type_end(Type::TypeTy);
639 // Print out forward declarations for structure types before anything else!
640 Out << "/* Structure forward decls */\n";
641 for (; I != End; ++I)
642 if (const Type *STy = dyn_cast<StructType>(I->second)) {
643 std::string Name = "struct l_" + makeNameProper(I->first);
644 Out << Name << ";\n";
645 TypeNames.insert(std::make_pair(STy, Name));
650 // Now we can print out typedefs...
651 Out << "/* Typedefs */\n";
652 for (I = ST.type_begin(Type::TypeTy); I != End; ++I) {
653 const Type *Ty = cast<Type>(I->second);
654 std::string Name = "l_" + makeNameProper(I->first);
656 printType(Out, Ty, Name);
662 // Keep track of which structures have been printed so far...
663 std::set<const StructType *> StructPrinted;
665 // Loop over all structures then push them into the stack so they are
666 // printed in the correct order.
668 Out << "/* Structure contents */\n";
669 for (I = ST.type_begin(Type::TypeTy); I != End; ++I)
670 if (const StructType *STy = dyn_cast<StructType>(I->second))
671 printContainedStructs(STy, StructPrinted);
674 // Push the struct onto the stack and recursively push all structs
675 // this one depends on.
676 void CWriter::printContainedStructs(const Type *Ty,
677 std::set<const StructType*> &StructPrinted){
678 if (const StructType *STy = dyn_cast<StructType>(Ty)){
679 //Check to see if we have already printed this struct
680 if (StructPrinted.count(STy) == 0) {
681 // Print all contained types first...
682 for (StructType::ElementTypes::const_iterator
683 I = STy->getElementTypes().begin(),
684 E = STy->getElementTypes().end(); I != E; ++I) {
685 const Type *Ty1 = I->get();
686 if (isa<StructType>(Ty1) || isa<ArrayType>(Ty1))
687 printContainedStructs(Ty1, StructPrinted);
690 //Print structure type out..
691 StructPrinted.insert(STy);
692 std::string Name = TypeNames[STy];
693 printType(Out, STy, Name, true);
697 // If it is an array, check contained types and continue
698 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(Ty)){
699 const Type *Ty1 = ATy->getElementType();
700 if (isa<StructType>(Ty1) || isa<ArrayType>(Ty1))
701 printContainedStructs(Ty1, StructPrinted);
706 void CWriter::printFunctionSignature(const Function *F, bool Prototype) {
707 // If the program provides it's own malloc prototype we don't need
708 // to include the general one.
709 if (getValueName(F) == "malloc")
711 if (F->hasInternalLinkage()) Out << "static ";
712 // Loop over the arguments, printing them...
713 const FunctionType *FT = cast<FunctionType>(F->getFunctionType());
715 std::stringstream FunctionInards;
717 // Print out the name...
718 FunctionInards << getValueName(F) << "(";
720 if (!F->isExternal()) {
723 if (F->abegin()->hasName() || !Prototype)
724 ArgName = getValueName(F->abegin());
725 printType(FunctionInards, F->afront().getType(), ArgName);
726 for (Function::const_aiterator I = ++F->abegin(), E = F->aend();
728 FunctionInards << ", ";
729 if (I->hasName() || !Prototype)
730 ArgName = getValueName(I);
733 printType(FunctionInards, I->getType(), ArgName);
737 // Loop over the arguments, printing them...
738 for (FunctionType::ParamTypes::const_iterator I =
739 FT->getParamTypes().begin(),
740 E = FT->getParamTypes().end(); I != E; ++I) {
741 if (I != FT->getParamTypes().begin()) FunctionInards << ", ";
742 printType(FunctionInards, *I);
746 // Finish printing arguments... if this is a vararg function, print the ...,
747 // unless there are no known types, in which case, we just emit ().
749 if (FT->isVarArg() && !FT->getParamTypes().empty()) {
750 if (FT->getParamTypes().size()) FunctionInards << ", ";
751 FunctionInards << "..."; // Output varargs portion of signature!
753 FunctionInards << ")";
754 // Print out the return type and the entire signature for that matter
755 printType(Out, F->getReturnType(), FunctionInards.str());
760 void CWriter::printFunction(Function *F) {
761 if (F->isExternal()) return;
763 Table->incorporateFunction(F);
765 printFunctionSignature(F, false);
768 // print local variable information for the function
769 for (inst_iterator I = inst_begin(F), E = inst_end(F); I != E; ++I)
770 if ((*I)->getType() != Type::VoidTy && !isInlinableInst(**I)) {
772 printType(Out, (*I)->getType(), getValueName(*I));
778 // Scan the function for floating point constants. If any FP constant is used
779 // in the function, we want to redirect it here so that we do not depend on
780 // the precision of the printed form.
782 unsigned FPCounter = 0;
783 for (constant_iterator I = constant_begin(F), E = constant_end(F); I != E;++I)
784 if (const ConstantFP *FPC = dyn_cast<ConstantFP>(*I))
785 if (FPConstantMap.find(FPC) == FPConstantMap.end()) {
786 double Val = FPC->getValue();
788 FPConstantMap[FPC] = FPCounter; // Number the FP constants
790 if (FPC->getType() == Type::DoubleTy)
791 Out << " const ConstantDoubleTy FloatConstant" << FPCounter++
792 << " = 0x" << std::hex << *(unsigned long long*)&Val << std::dec
793 << "; /* " << Val << " */\n";
794 else if (FPC->getType() == Type::FloatTy) {
796 Out << " const ConstantFloatTy FloatConstant" << FPCounter++
797 << " = 0x" << std::hex << *(unsigned*)&fVal << std::dec
798 << "; /* " << Val << " */\n";
800 assert(0 && "Unknown float type!");
805 // print the basic blocks
806 for (Function::iterator BB = F->begin(), E = F->end(); BB != E; ++BB) {
807 BasicBlock *Prev = BB->getPrev();
809 // Don't print the label for the basic block if there are no uses, or if the
810 // only terminator use is the precessor basic block's terminator. We have
811 // to scan the use list because PHI nodes use basic blocks too but do not
812 // require a label to be generated.
814 bool NeedsLabel = false;
815 for (Value::use_iterator UI = BB->use_begin(), UE = BB->use_end();
817 if (TerminatorInst *TI = dyn_cast<TerminatorInst>(*UI))
818 if (TI != Prev->getTerminator() ||
819 isa<SwitchInst>(Prev->getTerminator())) {
824 if (NeedsLabel) Out << getValueName(BB) << ":\n";
826 // Output all of the instructions in the basic block...
827 for (BasicBlock::iterator II = BB->begin(), E = --BB->end(); II != E; ++II){
828 if (!isInlinableInst(*II) && !isa<PHINode>(*II)) {
829 if (II->getType() != Type::VoidTy)
838 // Don't emit prefix or suffix for the terminator...
839 visit(*BB->getTerminator());
843 Table->purgeFunction();
844 FPConstantMap.clear();
847 // Specific Instruction type classes... note that all of the casts are
848 // neccesary because we use the instruction classes as opaque types...
850 void CWriter::visitReturnInst(ReturnInst &I) {
851 // Don't output a void return if this is the last basic block in the function
852 if (I.getNumOperands() == 0 &&
853 &*--I.getParent()->getParent()->end() == I.getParent() &&
854 !I.getParent()->size() == 1) {
859 if (I.getNumOperands()) {
861 writeOperand(I.getOperand(0));
866 void CWriter::visitSwitchInst(SwitchInst &SI) {
868 writeOperand(SI.getOperand(0));
869 Out << ") {\n default:\n";
870 printBranchToBlock(SI.getParent(), SI.getDefaultDest(), 2);
872 for (unsigned i = 2, e = SI.getNumOperands(); i != e; i += 2) {
874 writeOperand(SI.getOperand(i));
876 BasicBlock *Succ = cast<BasicBlock>(SI.getOperand(i+1));
877 printBranchToBlock(SI.getParent(), Succ, 2);
878 if (Succ == SI.getParent()->getNext())
885 static bool isGotoCodeNeccessary(BasicBlock *From, BasicBlock *To) {
886 // If PHI nodes need copies, we need the copy code...
887 if (isa<PHINode>(To->front()) ||
888 From->getNext() != To) // Not directly successor, need goto
891 // Otherwise we don't need the code.
895 void CWriter::printBranchToBlock(BasicBlock *CurBB, BasicBlock *Succ,
897 for (BasicBlock::iterator I = Succ->begin();
898 PHINode *PN = dyn_cast<PHINode>(I); ++I) {
899 // now we have to do the printing
900 Out << std::string(Indent, ' ');
902 writeOperand(PN->getIncomingValue(PN->getBasicBlockIndex(CurBB)));
903 Out << "; /* for PHI node */\n";
906 if (CurBB->getNext() != Succ) {
907 Out << std::string(Indent, ' ') << " goto ";
913 // Brach instruction printing - Avoid printing out a brach to a basic block that
914 // immediately succeeds the current one.
916 void CWriter::visitBranchInst(BranchInst &I) {
917 if (I.isConditional()) {
918 if (isGotoCodeNeccessary(I.getParent(), I.getSuccessor(0))) {
920 writeOperand(I.getCondition());
923 printBranchToBlock(I.getParent(), I.getSuccessor(0), 2);
925 if (isGotoCodeNeccessary(I.getParent(), I.getSuccessor(1))) {
926 Out << " } else {\n";
927 printBranchToBlock(I.getParent(), I.getSuccessor(1), 2);
930 // First goto not neccesary, assume second one is...
932 writeOperand(I.getCondition());
935 printBranchToBlock(I.getParent(), I.getSuccessor(1), 2);
940 printBranchToBlock(I.getParent(), I.getSuccessor(0), 0);
946 void CWriter::visitBinaryOperator(Instruction &I) {
947 // binary instructions, shift instructions, setCond instructions.
948 assert(!isa<PointerType>(I.getType()));
950 writeOperand(I.getOperand(0));
952 switch (I.getOpcode()) {
953 case Instruction::Add: Out << " + "; break;
954 case Instruction::Sub: Out << " - "; break;
955 case Instruction::Mul: Out << "*"; break;
956 case Instruction::Div: Out << "/"; break;
957 case Instruction::Rem: Out << "%"; break;
958 case Instruction::And: Out << " & "; break;
959 case Instruction::Or: Out << " | "; break;
960 case Instruction::Xor: Out << " ^ "; break;
961 case Instruction::SetEQ: Out << " == "; break;
962 case Instruction::SetNE: Out << " != "; break;
963 case Instruction::SetLE: Out << " <= "; break;
964 case Instruction::SetGE: Out << " >= "; break;
965 case Instruction::SetLT: Out << " < "; break;
966 case Instruction::SetGT: Out << " > "; break;
967 case Instruction::Shl : Out << " << "; break;
968 case Instruction::Shr : Out << " >> "; break;
969 default: std::cerr << "Invalid operator type!" << I; abort();
972 writeOperand(I.getOperand(1));
975 void CWriter::visitCastInst(CastInst &I) {
977 printType(Out, I.getType(), "", /*ignoreName*/false, /*namedContext*/false);
979 if (isa<PointerType>(I.getType())&&I.getOperand(0)->getType()->isIntegral() ||
980 isa<PointerType>(I.getOperand(0)->getType())&&I.getType()->isIntegral()) {
981 // Avoid "cast to pointer from integer of different size" warnings
985 writeOperand(I.getOperand(0));
988 void CWriter::visitCallInst(CallInst &I) {
989 const PointerType *PTy = cast<PointerType>(I.getCalledValue()->getType());
990 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
991 const Type *RetTy = FTy->getReturnType();
993 writeOperand(I.getOperand(0));
996 if (I.getNumOperands() > 1) {
997 writeOperand(I.getOperand(1));
999 for (unsigned op = 2, Eop = I.getNumOperands(); op != Eop; ++op) {
1001 writeOperand(I.getOperand(op));
1007 void CWriter::visitMallocInst(MallocInst &I) {
1009 printType(Out, I.getType());
1010 Out << ")malloc(sizeof(";
1011 printType(Out, I.getType()->getElementType());
1014 if (I.isArrayAllocation()) {
1016 writeOperand(I.getOperand(0));
1021 void CWriter::visitAllocaInst(AllocaInst &I) {
1023 printType(Out, I.getType());
1024 Out << ") alloca(sizeof(";
1025 printType(Out, I.getType()->getElementType());
1027 if (I.isArrayAllocation()) {
1029 writeOperand(I.getOperand(0));
1034 void CWriter::visitFreeInst(FreeInst &I) {
1036 writeOperand(I.getOperand(0));
1040 void CWriter::printIndexingExpression(Value *Ptr, User::op_iterator I,
1041 User::op_iterator E) {
1042 bool HasImplicitAddress = false;
1043 // If accessing a global value with no indexing, avoid *(&GV) syndrome
1044 if (GlobalValue *V = dyn_cast<GlobalValue>(Ptr)) {
1045 HasImplicitAddress = true;
1046 } else if (ConstantPointerRef *CPR = dyn_cast<ConstantPointerRef>(Ptr)) {
1047 HasImplicitAddress = true;
1048 Ptr = CPR->getValue(); // Get to the global...
1052 if (!HasImplicitAddress)
1053 Out << "*"; // Implicit zero first argument: '*x' is equivalent to 'x[0]'
1055 writeOperandInternal(Ptr);
1059 const Constant *CI = dyn_cast<Constant>(I->get());
1060 if (HasImplicitAddress && (!CI || !CI->isNullValue()))
1063 writeOperandInternal(Ptr);
1065 if (HasImplicitAddress && (!CI || !CI->isNullValue())) {
1067 HasImplicitAddress = false; // HIA is only true if we haven't addressed yet
1070 assert(!HasImplicitAddress || (CI && CI->isNullValue()) &&
1071 "Can only have implicit address with direct accessing");
1073 if (HasImplicitAddress) {
1075 } else if (CI && CI->isNullValue() && I+1 != E) {
1076 // Print out the -> operator if possible...
1077 if ((*(I+1))->getType() == Type::UByteTy) {
1078 Out << (HasImplicitAddress ? "." : "->");
1079 Out << "field" << cast<ConstantUInt>(*(I+1))->getValue();
1085 if ((*I)->getType() == Type::LongTy) {
1090 Out << ".field" << cast<ConstantUInt>(*I)->getValue();
1094 void CWriter::visitLoadInst(LoadInst &I) {
1096 writeOperand(I.getOperand(0));
1099 void CWriter::visitStoreInst(StoreInst &I) {
1101 writeOperand(I.getPointerOperand());
1103 writeOperand(I.getOperand(0));
1106 void CWriter::visitGetElementPtrInst(GetElementPtrInst &I) {
1108 printIndexingExpression(I.getPointerOperand(), I.idx_begin(), I.idx_end());
1111 //===----------------------------------------------------------------------===//
1112 // External Interface declaration
1113 //===----------------------------------------------------------------------===//
1115 Pass *createWriteToCPass(std::ostream &o) { return new CWriter(o); }