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 FunctionInards << "...";
224 FunctionInards << ")";
225 std::string tstr = FunctionInards.str();
226 printType(Out, MTy->getReturnType(), tstr);
229 case Type::StructTyID: {
230 const StructType *STy = cast<StructType>(Ty);
231 Out << NameSoFar + " {\n";
233 for (StructType::ElementTypes::const_iterator
234 I = STy->getElementTypes().begin(),
235 E = STy->getElementTypes().end(); I != E; ++I) {
237 printType(Out, *I, "field" + utostr(Idx++));
243 case Type::PointerTyID: {
244 const PointerType *PTy = cast<PointerType>(Ty);
245 std::string ptrName = "*" + NameSoFar;
247 // Do not need parens around "* NameSoFar" if NameSoFar consists only
248 // of zero or more '*' chars *and* this is not an unnamed pointer type
249 // such as the result type in a cast statement. Otherwise, enclose in ( ).
250 if (ptrTypeNameNeedsParens(NameSoFar) || !namedContext ||
251 PTy->getElementType()->getPrimitiveID() == Type::ArrayTyID)
252 ptrName = "(" + ptrName + ")"; //
254 return printType(Out, PTy->getElementType(), ptrName);
257 case Type::ArrayTyID: {
258 const ArrayType *ATy = cast<ArrayType>(Ty);
259 unsigned NumElements = ATy->getNumElements();
260 return printType(Out, ATy->getElementType(),
261 NameSoFar + "[" + utostr(NumElements) + "]");
264 case Type::OpaqueTyID: {
265 static int Count = 0;
266 std::string TyName = "struct opaque_" + itostr(Count++);
267 assert(TypeNames.find(Ty) == TypeNames.end());
268 TypeNames[Ty] = TyName;
269 return Out << TyName << " " << NameSoFar;
272 assert(0 && "Unhandled case in getTypeProps!");
279 void CWriter::printConstantArray(ConstantArray *CPA) {
281 // As a special case, print the array as a string if it is an array of
282 // ubytes or an array of sbytes with positive values.
284 const Type *ETy = CPA->getType()->getElementType();
285 bool isString = (ETy == Type::SByteTy || ETy == Type::UByteTy);
287 // Make sure the last character is a null char, as automatically added by C
288 if (CPA->getNumOperands() == 0 ||
289 !cast<Constant>(*(CPA->op_end()-1))->isNullValue())
294 // Do not include the last character, which we know is null
295 for (unsigned i = 0, e = CPA->getNumOperands()-1; i != e; ++i) {
296 unsigned char C = (ETy == Type::SByteTy) ?
297 (unsigned char)cast<ConstantSInt>(CPA->getOperand(i))->getValue() :
298 (unsigned char)cast<ConstantUInt>(CPA->getOperand(i))->getValue();
301 if (C == '"' || C == '\\')
307 case '\n': Out << "\\n"; break;
308 case '\t': Out << "\\t"; break;
309 case '\r': Out << "\\r"; break;
310 case '\v': Out << "\\v"; break;
311 case '\a': Out << "\\a"; break;
312 case '\"': Out << "\\\""; break;
313 case '\'': Out << "\\\'"; break;
316 Out << ( C/16 < 10) ? ( C/16 +'0') : ( C/16 -10+'A');
317 Out << ((C&15) < 10) ? ((C&15)+'0') : ((C&15)-10+'A');
325 if (CPA->getNumOperands()) {
327 printConstant(cast<Constant>(CPA->getOperand(0)));
328 for (unsigned i = 1, e = CPA->getNumOperands(); i != e; ++i) {
330 printConstant(cast<Constant>(CPA->getOperand(i)));
338 // printConstant - The LLVM Constant to C Constant converter.
339 void CWriter::printConstant(Constant *CPV) {
340 if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(CPV)) {
341 switch (CE->getOpcode()) {
342 case Instruction::Cast:
344 printType(Out, CPV->getType());
346 printConstant(cast<Constant>(CPV->getOperand(0)));
350 case Instruction::GetElementPtr:
352 printIndexingExpression(CPV->getOperand(0),
353 CPV->op_begin()+1, CPV->op_end());
356 case Instruction::Add:
358 printConstant(cast<Constant>(CPV->getOperand(0)));
360 printConstant(cast<Constant>(CPV->getOperand(1)));
363 case Instruction::Sub:
365 printConstant(cast<Constant>(CPV->getOperand(0)));
367 printConstant(cast<Constant>(CPV->getOperand(1)));
372 std::cerr << "CWriter Error: Unhandled constant expression: "
378 switch (CPV->getType()->getPrimitiveID()) {
380 Out << (CPV == ConstantBool::False ? "0" : "1"); break;
381 case Type::SByteTyID:
382 case Type::ShortTyID:
383 Out << cast<ConstantSInt>(CPV)->getValue(); break;
385 if ((int)cast<ConstantSInt>(CPV)->getValue() == (int)0x80000000)
386 Out << "((int)0x80000000)"; // Handle MININT specially to avoid warning
388 Out << cast<ConstantSInt>(CPV)->getValue();
392 Out << cast<ConstantSInt>(CPV)->getValue() << "ll"; break;
394 case Type::UByteTyID:
395 case Type::UShortTyID:
396 Out << cast<ConstantUInt>(CPV)->getValue(); break;
398 Out << cast<ConstantUInt>(CPV)->getValue() << "u"; break;
399 case Type::ULongTyID:
400 Out << cast<ConstantUInt>(CPV)->getValue() << "ull"; break;
402 case Type::FloatTyID:
403 case Type::DoubleTyID: {
404 ConstantFP *FPC = cast<ConstantFP>(CPV);
405 std::map<const ConstantFP*, unsigned>::iterator I = FPConstantMap.find(FPC);
406 if (I != FPConstantMap.end()) {
407 // Because of FP precision problems we must load from a stack allocated
408 // value that holds the value in hex.
409 Out << "(*(" << (FPC->getType() == Type::FloatTy ? "float" : "double")
410 << "*)&FloatConstant" << I->second << ")";
412 Out << FPC->getValue();
417 case Type::ArrayTyID:
418 printConstantArray(cast<ConstantArray>(CPV));
421 case Type::StructTyID: {
423 if (CPV->getNumOperands()) {
425 printConstant(cast<Constant>(CPV->getOperand(0)));
426 for (unsigned i = 1, e = CPV->getNumOperands(); i != e; ++i) {
428 printConstant(cast<Constant>(CPV->getOperand(i)));
435 case Type::PointerTyID:
436 if (isa<ConstantPointerNull>(CPV)) {
439 } else if (ConstantPointerRef *CPR = dyn_cast<ConstantPointerRef>(CPV)) {
440 writeOperand(CPR->getValue());
445 std::cerr << "Unknown constant type: " << CPV << "\n";
450 void CWriter::writeOperandInternal(Value *Operand) {
451 if (Instruction *I = dyn_cast<Instruction>(Operand))
452 if (isInlinableInst(*I)) {
453 // Should we inline this instruction to build a tree?
460 if (Operand->hasName()) {
461 Out << getValueName(Operand);
462 } else if (Constant *CPV = dyn_cast<Constant>(Operand)) {
465 int Slot = Table->getValSlot(Operand);
466 assert(Slot >= 0 && "Malformed LLVM!");
467 Out << "ltmp_" << Slot << "_" << Operand->getType()->getUniqueID();
471 void CWriter::writeOperand(Value *Operand) {
472 if (isa<GlobalVariable>(Operand))
473 Out << "(&"; // Global variables are references as their addresses by llvm
475 writeOperandInternal(Operand);
477 if (isa<GlobalVariable>(Operand))
481 // nameAllUsedStructureTypes - If there are structure types in the module that
482 // are used but do not have names assigned to them in the symbol table yet then
483 // we assign them names now.
485 bool CWriter::nameAllUsedStructureTypes(Module &M) {
486 // Get a set of types that are used by the program...
487 std::set<const Type *> UT = getAnalysis<FindUsedTypes>().getTypes();
489 // Loop over the module symbol table, removing types from UT that are already
492 SymbolTable &MST = M.getSymbolTable();
493 if (MST.find(Type::TypeTy) != MST.end())
494 for (SymbolTable::type_iterator I = MST.type_begin(Type::TypeTy),
495 E = MST.type_end(Type::TypeTy); I != E; ++I)
496 UT.erase(cast<Type>(I->second));
498 // UT now contains types that are not named. Loop over it, naming structure
501 bool Changed = false;
502 for (std::set<const Type *>::const_iterator I = UT.begin(), E = UT.end();
504 if (const StructType *ST = dyn_cast<StructType>(*I)) {
505 ((Value*)ST)->setName("unnamed", &MST);
511 static void generateAllocaDecl(std::ostream& Out) {
512 // On SunOS, we need to insert the alloca macro & proto for the builtin.
513 Out << "#ifdef sun\n"
514 << "extern void *__builtin_alloca(unsigned long);\n"
515 << "#define alloca(x) __builtin_alloca(x)\n"
517 << "#include <alloca.h>\n"
521 void CWriter::printModule(Module *M) {
522 // Calculate which global values have names that will collide when we throw
523 // away type information.
524 { // Scope to delete the FoundNames set when we are done with it...
525 std::set<std::string> FoundNames;
526 for (Module::iterator I = M->begin(), E = M->end(); I != E; ++I)
527 if (I->hasName()) // If the global has a name...
528 if (FoundNames.count(I->getName())) // And the name is already used
529 MangledGlobals.insert(I); // Mangle the name
531 FoundNames.insert(I->getName()); // Otherwise, keep track of name
533 for (Module::giterator I = M->gbegin(), E = M->gend(); I != E; ++I)
534 if (I->hasName()) // If the global has a name...
535 if (FoundNames.count(I->getName())) // And the name is already used
536 MangledGlobals.insert(I); // Mangle the name
538 FoundNames.insert(I->getName()); // Otherwise, keep track of name
541 // get declaration for alloca
542 Out << "/* Provide Declarations */\n";
543 generateAllocaDecl(Out);
544 Out << "#include <stdarg.h>\n";
546 // Provide a definition for null if one does not already exist,
547 // and for `bool' if not compiling with a C++ compiler.
548 Out << "#ifndef NULL\n#define NULL 0\n#endif\n\n"
549 << "#ifndef __cplusplus\ntypedef unsigned char bool;\n#endif\n"
551 << "\n\n/* Support for floating point constants */\n"
552 << "typedef unsigned long long ConstantDoubleTy;\n"
553 << "typedef unsigned int ConstantFloatTy;\n"
555 << "\n\n/* Global Declarations */\n";
557 // First output all the declarations for the program, because C requires
558 // Functions & globals to be declared before they are used.
561 // Loop over the symbol table, emitting all named constants...
562 printSymbolTable(M->getSymbolTable());
564 // Global variable declarations...
566 Out << "\n/* External Global Variable Declarations */\n";
567 for (Module::giterator I = M->gbegin(), E = M->gend(); I != E; ++I) {
568 if (I->hasExternalLinkage()) {
570 printType(Out, I->getType()->getElementType(), getValueName(I));
576 // Function declarations
578 Out << "\n/* Function Declarations */\n";
580 for (Module::iterator I = M->begin(), E = M->end(); I != E; ++I) {
581 // If the function is external and the name collides don't print it.
582 // Sometimes the bytecode likes to have multiple "declarations" for
583 // external functions
584 if ((I->hasInternalLinkage() || !MangledGlobals.count(I)) &&
585 !I->getIntrinsicID()) {
586 printFunctionSignature(I, true);
592 // Print Malloc prototype if needed
594 Out << "\n/* Malloc to make sun happy */\n";
595 Out << "extern void * malloc(size_t);\n\n";
598 // Output the global variable declerations
600 Out << "\n\n/* Global Variable Declerations */\n";
601 for (Module::giterator I = M->gbegin(), E = M->gend(); I != E; ++I)
602 if (!I->isExternal()) {
604 printType(Out, I->getType()->getElementType(), getValueName(I));
611 // Output the global variable definitions and contents...
613 Out << "\n\n/* Global Variable Definitions and Initialization */\n";
614 for (Module::giterator I = M->gbegin(), E = M->gend(); I != E; ++I)
615 if (!I->isExternal()) {
616 if (I->hasInternalLinkage())
618 printType(Out, I->getType()->getElementType(), getValueName(I));
621 writeOperand(I->getInitializer());
626 // Output all of the functions...
628 Out << "\n\n/* Function Bodies */\n";
629 for (Module::iterator I = M->begin(), E = M->end(); I != E; ++I)
635 /// printSymbolTable - Run through symbol table looking for type names. If a
636 /// type name is found, emit it's declaration...
638 void CWriter::printSymbolTable(const SymbolTable &ST) {
639 // If there are no type names, exit early.
640 if (ST.find(Type::TypeTy) == ST.end())
643 // We are only interested in the type plane of the symbol table...
644 SymbolTable::type_const_iterator I = ST.type_begin(Type::TypeTy);
645 SymbolTable::type_const_iterator End = ST.type_end(Type::TypeTy);
647 // Print out forward declarations for structure types before anything else!
648 Out << "/* Structure forward decls */\n";
649 for (; I != End; ++I)
650 if (const Type *STy = dyn_cast<StructType>(I->second)) {
651 std::string Name = "struct l_" + makeNameProper(I->first);
652 Out << Name << ";\n";
653 TypeNames.insert(std::make_pair(STy, Name));
658 // Now we can print out typedefs...
659 Out << "/* Typedefs */\n";
660 for (I = ST.type_begin(Type::TypeTy); I != End; ++I) {
661 const Type *Ty = cast<Type>(I->second);
662 std::string Name = "l_" + makeNameProper(I->first);
664 printType(Out, Ty, Name);
670 // Keep track of which structures have been printed so far...
671 std::set<const StructType *> StructPrinted;
673 // Loop over all structures then push them into the stack so they are
674 // printed in the correct order.
676 Out << "/* Structure contents */\n";
677 for (I = ST.type_begin(Type::TypeTy); I != End; ++I)
678 if (const StructType *STy = dyn_cast<StructType>(I->second))
679 printContainedStructs(STy, StructPrinted);
682 // Push the struct onto the stack and recursively push all structs
683 // this one depends on.
684 void CWriter::printContainedStructs(const Type *Ty,
685 std::set<const StructType*> &StructPrinted){
686 if (const StructType *STy = dyn_cast<StructType>(Ty)){
687 //Check to see if we have already printed this struct
688 if (StructPrinted.count(STy) == 0) {
689 // Print all contained types first...
690 for (StructType::ElementTypes::const_iterator
691 I = STy->getElementTypes().begin(),
692 E = STy->getElementTypes().end(); I != E; ++I) {
693 const Type *Ty1 = I->get();
694 if (isa<StructType>(Ty1) || isa<ArrayType>(Ty1))
695 printContainedStructs(Ty1, StructPrinted);
698 //Print structure type out..
699 StructPrinted.insert(STy);
700 std::string Name = TypeNames[STy];
701 printType(Out, STy, Name, true);
705 // If it is an array, check contained types and continue
706 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(Ty)){
707 const Type *Ty1 = ATy->getElementType();
708 if (isa<StructType>(Ty1) || isa<ArrayType>(Ty1))
709 printContainedStructs(Ty1, StructPrinted);
714 void CWriter::printFunctionSignature(const Function *F, bool Prototype) {
715 // If the program provides it's own malloc prototype we don't need
716 // to include the general one.
717 if (getValueName(F) == "malloc")
719 if (F->hasInternalLinkage()) Out << "static ";
720 // Loop over the arguments, printing them...
721 const FunctionType *FT = cast<FunctionType>(F->getFunctionType());
723 std::stringstream FunctionInards;
725 // Print out the name...
726 FunctionInards << getValueName(F) << "(";
728 if (!F->isExternal()) {
731 if (F->abegin()->hasName() || !Prototype)
732 ArgName = getValueName(F->abegin());
733 printType(FunctionInards, F->afront().getType(), ArgName);
734 for (Function::const_aiterator I = ++F->abegin(), E = F->aend();
736 FunctionInards << ", ";
737 if (I->hasName() || !Prototype)
738 ArgName = getValueName(I);
741 printType(FunctionInards, I->getType(), ArgName);
745 // Loop over the arguments, printing them...
746 for (FunctionType::ParamTypes::const_iterator I =
747 FT->getParamTypes().begin(),
748 E = FT->getParamTypes().end(); I != E; ++I) {
749 if (I != FT->getParamTypes().begin()) FunctionInards << ", ";
750 printType(FunctionInards, *I);
754 // Finish printing arguments... if this is a vararg function, print the ...,
755 // unless there are no known types, in which case, we just emit ().
757 if (FT->isVarArg() && !FT->getParamTypes().empty()) {
758 if (FT->getParamTypes().size()) FunctionInards << ", ";
759 FunctionInards << "..."; // Output varargs portion of signature!
761 FunctionInards << ")";
762 // Print out the return type and the entire signature for that matter
763 printType(Out, F->getReturnType(), FunctionInards.str());
768 void CWriter::printFunction(Function *F) {
769 if (F->isExternal()) return;
771 Table->incorporateFunction(F);
773 printFunctionSignature(F, false);
776 // print local variable information for the function
777 for (inst_iterator I = inst_begin(F), E = inst_end(F); I != E; ++I)
778 if ((*I)->getType() != Type::VoidTy && !isInlinableInst(**I)) {
780 printType(Out, (*I)->getType(), getValueName(*I));
783 if (isa<PHINode>(*I)) { // Print out PHI node temporaries as well...
785 printType(Out, (*I)->getType(), getValueName(*I)+"__PHI_TEMPORARY");
792 // Scan the function for floating point constants. If any FP constant is used
793 // in the function, we want to redirect it here so that we do not depend on
794 // the precision of the printed form.
796 unsigned FPCounter = 0;
797 for (constant_iterator I = constant_begin(F), E = constant_end(F); I != E;++I)
798 if (const ConstantFP *FPC = dyn_cast<ConstantFP>(*I))
799 if (FPConstantMap.find(FPC) == FPConstantMap.end()) {
800 double Val = FPC->getValue();
802 FPConstantMap[FPC] = FPCounter; // Number the FP constants
804 if (FPC->getType() == Type::DoubleTy)
805 Out << " const ConstantDoubleTy FloatConstant" << FPCounter++
806 << " = 0x" << std::hex << *(unsigned long long*)&Val << std::dec
807 << "; /* " << Val << " */\n";
808 else if (FPC->getType() == Type::FloatTy) {
810 Out << " const ConstantFloatTy FloatConstant" << FPCounter++
811 << " = 0x" << std::hex << *(unsigned*)&fVal << std::dec
812 << "; /* " << Val << " */\n";
814 assert(0 && "Unknown float type!");
819 // print the basic blocks
820 for (Function::iterator BB = F->begin(), E = F->end(); BB != E; ++BB) {
821 BasicBlock *Prev = BB->getPrev();
823 // Don't print the label for the basic block if there are no uses, or if the
824 // only terminator use is the precessor basic block's terminator. We have
825 // to scan the use list because PHI nodes use basic blocks too but do not
826 // require a label to be generated.
828 bool NeedsLabel = false;
829 for (Value::use_iterator UI = BB->use_begin(), UE = BB->use_end();
831 if (TerminatorInst *TI = dyn_cast<TerminatorInst>(*UI))
832 if (TI != Prev->getTerminator() ||
833 isa<SwitchInst>(Prev->getTerminator())) {
838 if (NeedsLabel) Out << getValueName(BB) << ":\n";
840 // Output all of the instructions in the basic block...
841 for (BasicBlock::iterator II = BB->begin(), E = --BB->end(); II != E; ++II){
842 if (!isInlinableInst(*II)) {
843 if (II->getType() != Type::VoidTy)
852 // Don't emit prefix or suffix for the terminator...
853 visit(*BB->getTerminator());
857 Table->purgeFunction();
858 FPConstantMap.clear();
861 // Specific Instruction type classes... note that all of the casts are
862 // neccesary because we use the instruction classes as opaque types...
864 void CWriter::visitReturnInst(ReturnInst &I) {
865 // Don't output a void return if this is the last basic block in the function
866 if (I.getNumOperands() == 0 &&
867 &*--I.getParent()->getParent()->end() == I.getParent() &&
868 !I.getParent()->size() == 1) {
873 if (I.getNumOperands()) {
875 writeOperand(I.getOperand(0));
880 void CWriter::visitSwitchInst(SwitchInst &SI) {
882 writeOperand(SI.getOperand(0));
883 Out << ") {\n default:\n";
884 printBranchToBlock(SI.getParent(), SI.getDefaultDest(), 2);
886 for (unsigned i = 2, e = SI.getNumOperands(); i != e; i += 2) {
888 writeOperand(SI.getOperand(i));
890 BasicBlock *Succ = cast<BasicBlock>(SI.getOperand(i+1));
891 printBranchToBlock(SI.getParent(), Succ, 2);
892 if (Succ == SI.getParent()->getNext())
899 static bool isGotoCodeNeccessary(BasicBlock *From, BasicBlock *To) {
900 // If PHI nodes need copies, we need the copy code...
901 if (isa<PHINode>(To->front()) ||
902 From->getNext() != To) // Not directly successor, need goto
905 // Otherwise we don't need the code.
909 void CWriter::printBranchToBlock(BasicBlock *CurBB, BasicBlock *Succ,
911 for (BasicBlock::iterator I = Succ->begin();
912 PHINode *PN = dyn_cast<PHINode>(I); ++I) {
913 // now we have to do the printing
914 Out << std::string(Indent, ' ');
915 Out << " " << getValueName(I) << "__PHI_TEMPORARY = ";
916 writeOperand(PN->getIncomingValue(PN->getBasicBlockIndex(CurBB)));
917 Out << "; /* for PHI node */\n";
920 if (CurBB->getNext() != Succ) {
921 Out << std::string(Indent, ' ') << " goto ";
927 // Brach instruction printing - Avoid printing out a brach to a basic block that
928 // immediately succeeds the current one.
930 void CWriter::visitBranchInst(BranchInst &I) {
931 if (I.isConditional()) {
932 if (isGotoCodeNeccessary(I.getParent(), I.getSuccessor(0))) {
934 writeOperand(I.getCondition());
937 printBranchToBlock(I.getParent(), I.getSuccessor(0), 2);
939 if (isGotoCodeNeccessary(I.getParent(), I.getSuccessor(1))) {
940 Out << " } else {\n";
941 printBranchToBlock(I.getParent(), I.getSuccessor(1), 2);
944 // First goto not neccesary, assume second one is...
946 writeOperand(I.getCondition());
949 printBranchToBlock(I.getParent(), I.getSuccessor(1), 2);
954 printBranchToBlock(I.getParent(), I.getSuccessor(0), 0);
959 // PHI nodes get copied into temporary values at the end of predecessor basic
960 // blocks. We now need to copy these temporary values into the REAL value for
962 void CWriter::visitPHINode(PHINode &I) {
964 Out << "__PHI_TEMPORARY";
968 void CWriter::visitBinaryOperator(Instruction &I) {
969 // binary instructions, shift instructions, setCond instructions.
970 assert(!isa<PointerType>(I.getType()));
972 writeOperand(I.getOperand(0));
974 switch (I.getOpcode()) {
975 case Instruction::Add: Out << " + "; break;
976 case Instruction::Sub: Out << " - "; break;
977 case Instruction::Mul: Out << "*"; break;
978 case Instruction::Div: Out << "/"; break;
979 case Instruction::Rem: Out << "%"; break;
980 case Instruction::And: Out << " & "; break;
981 case Instruction::Or: Out << " | "; break;
982 case Instruction::Xor: Out << " ^ "; break;
983 case Instruction::SetEQ: Out << " == "; break;
984 case Instruction::SetNE: Out << " != "; break;
985 case Instruction::SetLE: Out << " <= "; break;
986 case Instruction::SetGE: Out << " >= "; break;
987 case Instruction::SetLT: Out << " < "; break;
988 case Instruction::SetGT: Out << " > "; break;
989 case Instruction::Shl : Out << " << "; break;
990 case Instruction::Shr : Out << " >> "; break;
991 default: std::cerr << "Invalid operator type!" << I; abort();
994 writeOperand(I.getOperand(1));
997 void CWriter::visitCastInst(CastInst &I) {
999 printType(Out, I.getType(), "", /*ignoreName*/false, /*namedContext*/false);
1001 if (isa<PointerType>(I.getType())&&I.getOperand(0)->getType()->isIntegral() ||
1002 isa<PointerType>(I.getOperand(0)->getType())&&I.getType()->isIntegral()) {
1003 // Avoid "cast to pointer from integer of different size" warnings
1007 writeOperand(I.getOperand(0));
1010 void CWriter::visitCallInst(CallInst &I) {
1011 // Handle intrinsic function calls first...
1012 if (Function *F = I.getCalledFunction())
1013 if (LLVMIntrinsic::ID ID = (LLVMIntrinsic::ID)F->getIntrinsicID()) {
1015 default: assert(0 && "Unknown LLVM intrinsic!");
1016 case LLVMIntrinsic::va_start:
1017 Out << "va_start((va_list)*";
1018 writeOperand(I.getOperand(1));
1020 // Output the last argument to the enclosing function...
1021 writeOperand(&I.getParent()->getParent()->aback());
1025 case LLVMIntrinsic::va_end:
1026 Out << "va_end((va_list)*";
1027 writeOperand(I.getOperand(1));
1030 case LLVMIntrinsic::va_copy:
1031 Out << "va_copy((va_list)*";
1032 writeOperand(I.getOperand(1));
1033 Out << ", (va_list)";
1034 writeOperand(I.getOperand(2));
1040 const PointerType *PTy = cast<PointerType>(I.getCalledValue()->getType());
1041 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
1042 const Type *RetTy = FTy->getReturnType();
1044 writeOperand(I.getOperand(0));
1047 if (I.getNumOperands() > 1) {
1048 writeOperand(I.getOperand(1));
1050 for (unsigned op = 2, Eop = I.getNumOperands(); op != Eop; ++op) {
1052 writeOperand(I.getOperand(op));
1058 void CWriter::visitMallocInst(MallocInst &I) {
1060 printType(Out, I.getType());
1061 Out << ")malloc(sizeof(";
1062 printType(Out, I.getType()->getElementType());
1065 if (I.isArrayAllocation()) {
1067 writeOperand(I.getOperand(0));
1072 void CWriter::visitAllocaInst(AllocaInst &I) {
1074 printType(Out, I.getType());
1075 Out << ") alloca(sizeof(";
1076 printType(Out, I.getType()->getElementType());
1078 if (I.isArrayAllocation()) {
1080 writeOperand(I.getOperand(0));
1085 void CWriter::visitFreeInst(FreeInst &I) {
1087 writeOperand(I.getOperand(0));
1091 void CWriter::printIndexingExpression(Value *Ptr, User::op_iterator I,
1092 User::op_iterator E) {
1093 bool HasImplicitAddress = false;
1094 // If accessing a global value with no indexing, avoid *(&GV) syndrome
1095 if (GlobalValue *V = dyn_cast<GlobalValue>(Ptr)) {
1096 HasImplicitAddress = true;
1097 } else if (ConstantPointerRef *CPR = dyn_cast<ConstantPointerRef>(Ptr)) {
1098 HasImplicitAddress = true;
1099 Ptr = CPR->getValue(); // Get to the global...
1103 if (!HasImplicitAddress)
1104 Out << "*"; // Implicit zero first argument: '*x' is equivalent to 'x[0]'
1106 writeOperandInternal(Ptr);
1110 const Constant *CI = dyn_cast<Constant>(I->get());
1111 if (HasImplicitAddress && (!CI || !CI->isNullValue()))
1114 writeOperandInternal(Ptr);
1116 if (HasImplicitAddress && (!CI || !CI->isNullValue())) {
1118 HasImplicitAddress = false; // HIA is only true if we haven't addressed yet
1121 assert(!HasImplicitAddress || (CI && CI->isNullValue()) &&
1122 "Can only have implicit address with direct accessing");
1124 if (HasImplicitAddress) {
1126 } else if (CI && CI->isNullValue() && I+1 != E) {
1127 // Print out the -> operator if possible...
1128 if ((*(I+1))->getType() == Type::UByteTy) {
1129 Out << (HasImplicitAddress ? "." : "->");
1130 Out << "field" << cast<ConstantUInt>(*(I+1))->getValue();
1136 if ((*I)->getType() == Type::LongTy) {
1141 Out << ".field" << cast<ConstantUInt>(*I)->getValue();
1145 void CWriter::visitLoadInst(LoadInst &I) {
1147 writeOperand(I.getOperand(0));
1150 void CWriter::visitStoreInst(StoreInst &I) {
1152 writeOperand(I.getPointerOperand());
1154 writeOperand(I.getOperand(0));
1157 void CWriter::visitGetElementPtrInst(GetElementPtrInst &I) {
1159 printIndexingExpression(I.getPointerOperand(), I.idx_begin(), I.idx_end());
1162 void CWriter::visitVarArgInst(VarArgInst &I) {
1163 Out << "va_arg((va_list)*";
1164 writeOperand(I.getOperand(0));
1166 printType(Out, I.getType(), "", /*ignoreName*/false, /*namedContext*/false);
1171 //===----------------------------------------------------------------------===//
1172 // External Interface declaration
1173 //===----------------------------------------------------------------------===//
1175 Pass *createWriteToCPass(std::ostream &o) { return new CWriter(o); }