1 //===-- Writer.cpp - Library for converting LLVM code to C ----------------===//
3 // This library converts LLVM code to C code, compilable by GCC.
5 //===-----------------------------------------------------------------------==//
6 #include "llvm/Assembly/CWriter.h"
7 #include "llvm/Constants.h"
8 #include "llvm/DerivedTypes.h"
9 #include "llvm/Module.h"
10 #include "llvm/iMemory.h"
11 #include "llvm/iTerminators.h"
12 #include "llvm/iPHINode.h"
13 #include "llvm/iOther.h"
14 #include "llvm/iOperators.h"
15 #include "llvm/Pass.h"
16 #include "llvm/SymbolTable.h"
17 #include "llvm/SlotCalculator.h"
18 #include "llvm/Analysis/FindUsedTypes.h"
19 #include "llvm/Analysis/ConstantsScanner.h"
20 #include "llvm/Support/InstVisitor.h"
21 #include "llvm/Support/InstIterator.h"
22 #include "Support/StringExtras.h"
23 #include "Support/STLExtras.h"
32 class CWriter : public Pass, public InstVisitor<CWriter> {
34 SlotCalculator *Table;
35 const Module *TheModule;
36 map<const Type *, string> TypeNames;
37 std::set<const Value*> MangledGlobals;
40 map<const ConstantFP *, unsigned> FPConstantMap;
42 CWriter(ostream &o) : Out(o) {}
44 void getAnalysisUsage(AnalysisUsage &AU) const {
46 AU.addRequired<FindUsedTypes>();
49 virtual bool run(Module &M) {
51 Table = new SlotCalculator(&M, false);
54 // Ensure that all structure types have names...
55 bool Changed = nameAllUsedStructureTypes(M);
63 MangledGlobals.clear();
67 ostream &printType(const Type *Ty, const string &VariableName = "",
68 bool IgnoreName = false, bool namedContext = true);
70 void writeOperand(Value *Operand);
71 void writeOperandInternal(Value *Operand);
73 string getValueName(const Value *V);
76 bool nameAllUsedStructureTypes(Module &M);
77 void printModule(Module *M);
78 void printSymbolTable(const SymbolTable &ST);
79 void printContainedStructs(const Type *Ty, std::set<const StructType *> &);
80 void printGlobal(const GlobalVariable *GV);
81 void printFunctionSignature(const Function *F, bool Prototype);
83 void printFunction(Function *);
85 void printConstant(Constant *CPV);
86 void printConstantArray(ConstantArray *CPA);
88 // isInlinableInst - Attempt to inline instructions into their uses to build
89 // trees as much as possible. To do this, we have to consistently decide
90 // what is acceptable to inline, so that variable declarations don't get
91 // printed and an extra copy of the expr is not emitted.
93 static bool isInlinableInst(const Instruction &I) {
94 // Must be an expression, must be used exactly once. If it is dead, we
95 // emit it inline where it would go.
96 if (I.getType() == Type::VoidTy || I.use_size() != 1 ||
97 isa<TerminatorInst>(I) || isa<CallInst>(I) || isa<PHINode>(I))
100 // Only inline instruction it it's use is in the same BB as the inst.
101 return I.getParent() == cast<Instruction>(I.use_back())->getParent();
104 // Instruction visitation functions
105 friend class InstVisitor<CWriter>;
107 void visitReturnInst(ReturnInst &I);
108 void visitBranchInst(BranchInst &I);
110 void visitPHINode(PHINode &I) {}
111 void visitBinaryOperator(Instruction &I);
113 void visitCastInst (CastInst &I);
114 void visitCallInst (CallInst &I);
115 void visitShiftInst(ShiftInst &I) { visitBinaryOperator(I); }
117 void visitMallocInst(MallocInst &I);
118 void visitAllocaInst(AllocaInst &I);
119 void visitFreeInst (FreeInst &I);
120 void visitLoadInst (LoadInst &I);
121 void visitStoreInst (StoreInst &I);
122 void visitGetElementPtrInst(GetElementPtrInst &I);
124 void visitInstruction(Instruction &I) {
125 std::cerr << "C Writer does not know about " << I;
129 void outputLValue(Instruction *I) {
130 Out << " " << getValueName(I) << " = ";
132 void printBranchToBlock(BasicBlock *CurBlock, BasicBlock *SuccBlock,
134 void printIndexingExpression(Value *Ptr, User::op_iterator I,
135 User::op_iterator E);
139 // We dont want identifier names with ., space, - in them.
140 // So we replace them with _
141 static string makeNameProper(string x) {
143 for (string::iterator sI = x.begin(), sEnd = x.end(); sI != sEnd; sI++)
145 case '.': tmp += "d_"; break;
146 case ' ': tmp += "s_"; break;
147 case '-': tmp += "D_"; break;
154 string CWriter::getValueName(const Value *V) {
155 if (V->hasName()) { // Print out the label if it exists...
156 if (isa<GlobalValue>(V) && // Do not mangle globals...
157 cast<GlobalValue>(V)->hasExternalLinkage() && // Unless it's internal or
158 !MangledGlobals.count(V)) // Unless the name would collide if we don't
159 return makeNameProper(V->getName());
161 return "l" + utostr(V->getType()->getUniqueID()) + "_" +
162 makeNameProper(V->getName());
165 int Slot = Table->getValSlot(V);
166 assert(Slot >= 0 && "Invalid value!");
167 return "ltmp_" + itostr(Slot) + "_" + utostr(V->getType()->getUniqueID());
170 // A pointer type should not use parens around *'s alone, e.g., (**)
171 inline bool ptrTypeNameNeedsParens(const string &NameSoFar) {
172 return (NameSoFar.find_last_not_of('*') != std::string::npos);
175 // Pass the Type* and the variable name and this prints out the variable
178 ostream &CWriter::printType(const Type *Ty, const 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 map<const Type *, 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 printType(MTy->getReturnType(), "");
211 Out << " " << NameSoFar << " (";
213 for (FunctionType::ParamTypes::const_iterator
214 I = MTy->getParamTypes().begin(),
215 E = MTy->getParamTypes().end(); I != E; ++I) {
216 if (I != MTy->getParamTypes().begin())
220 if (MTy->isVarArg()) {
221 if (!MTy->getParamTypes().empty())
227 case Type::StructTyID: {
228 const StructType *STy = cast<StructType>(Ty);
229 Out << NameSoFar + " {\n";
231 for (StructType::ElementTypes::const_iterator
232 I = STy->getElementTypes().begin(),
233 E = STy->getElementTypes().end(); I != E; ++I) {
235 printType(*I, "field" + utostr(Idx++));
241 case Type::PointerTyID: {
242 const PointerType *PTy = cast<PointerType>(Ty);
243 std::string ptrName = "*" + NameSoFar;
245 // Do not need parens around "* NameSoFar" if NameSoFar consists only
246 // of zero or more '*' chars *and* this is not an unnamed pointer type
247 // such as the result type in a cast statement. Otherwise, enclose in ( ).
248 if (ptrTypeNameNeedsParens(NameSoFar) || !namedContext ||
249 PTy->getElementType()->getPrimitiveID() == Type::ArrayTyID)
250 ptrName = "(" + ptrName + ")"; //
252 return printType(PTy->getElementType(), ptrName);
255 case Type::ArrayTyID: {
256 const ArrayType *ATy = cast<ArrayType>(Ty);
257 unsigned NumElements = ATy->getNumElements();
258 return printType(ATy->getElementType(),
259 NameSoFar + "[" + utostr(NumElements) + "]");
262 case Type::OpaqueTyID: {
263 static int Count = 0;
264 string TyName = "struct opaque_" + itostr(Count++);
265 assert(TypeNames.find(Ty) == TypeNames.end());
266 TypeNames[Ty] = TyName;
267 return Out << TyName << " " << NameSoFar;
270 assert(0 && "Unhandled case in getTypeProps!");
277 void CWriter::printConstantArray(ConstantArray *CPA) {
279 // As a special case, print the array as a string if it is an array of
280 // ubytes or an array of sbytes with positive values.
282 const Type *ETy = CPA->getType()->getElementType();
283 bool isString = (ETy == Type::SByteTy || ETy == Type::UByteTy);
285 // Make sure the last character is a null char, as automatically added by C
286 if (CPA->getNumOperands() == 0 ||
287 !cast<Constant>(*(CPA->op_end()-1))->isNullValue())
292 // Do not include the last character, which we know is null
293 for (unsigned i = 0, e = CPA->getNumOperands()-1; i != e; ++i) {
294 unsigned char C = (ETy == Type::SByteTy) ?
295 (unsigned char)cast<ConstantSInt>(CPA->getOperand(i))->getValue() :
296 (unsigned char)cast<ConstantUInt>(CPA->getOperand(i))->getValue();
305 case '\n': Out << "\\n"; break;
306 case '\t': Out << "\\t"; break;
307 case '\r': Out << "\\r"; break;
308 case '\v': Out << "\\v"; break;
309 case '\a': Out << "\\a"; break;
310 case '\"': Out << "\\\""; break;
311 case '\'': Out << "\\\'"; break;
314 Out << ( C/16 < 10) ? ( C/16 +'0') : ( C/16 -10+'A');
315 Out << ((C&15) < 10) ? ((C&15)+'0') : ((C&15)-10+'A');
323 if (CPA->getNumOperands()) {
325 printConstant(cast<Constant>(CPA->getOperand(0)));
326 for (unsigned i = 1, e = CPA->getNumOperands(); i != e; ++i) {
328 printConstant(cast<Constant>(CPA->getOperand(i)));
336 // printConstant - The LLVM Constant to C Constant converter.
337 void CWriter::printConstant(Constant *CPV) {
338 if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(CPV)) {
339 switch (CE->getOpcode()) {
340 case Instruction::Cast:
342 printType(CPV->getType());
344 printConstant(cast<Constant>(CPV->getOperand(0)));
348 case Instruction::GetElementPtr:
350 printIndexingExpression(CPV->getOperand(0),
351 CPV->op_begin()+1, CPV->op_end());
354 case Instruction::Add:
356 printConstant(cast<Constant>(CPV->getOperand(0)));
358 printConstant(cast<Constant>(CPV->getOperand(1)));
361 case Instruction::Sub:
363 printConstant(cast<Constant>(CPV->getOperand(0)));
365 printConstant(cast<Constant>(CPV->getOperand(1)));
370 std::cerr << "CWriter Error: Unhandled constant expression: "
376 switch (CPV->getType()->getPrimitiveID()) {
378 Out << (CPV == ConstantBool::False ? "0" : "1"); break;
379 case Type::SByteTyID:
380 case Type::ShortTyID:
382 Out << cast<ConstantSInt>(CPV)->getValue(); break;
384 Out << cast<ConstantSInt>(CPV)->getValue() << "ll"; break;
386 case Type::UByteTyID:
387 case Type::UShortTyID:
388 Out << cast<ConstantUInt>(CPV)->getValue(); break;
390 Out << cast<ConstantUInt>(CPV)->getValue() << "u"; break;
391 case Type::ULongTyID:
392 Out << cast<ConstantUInt>(CPV)->getValue() << "ull"; break;
394 case Type::FloatTyID:
395 case Type::DoubleTyID: {
396 ConstantFP *FPC = cast<ConstantFP>(CPV);
397 map<const ConstantFP *, unsigned>::iterator I = FPConstantMap.find(FPC);
398 if (I != FPConstantMap.end()) {
399 // Because of FP precision problems we must load from a stack allocated
400 // value that holds the value in hex.
401 Out << "(*(" << (FPC->getType() == Type::FloatTy ? "float" : "double")
402 << "*)&FloatConstant" << I->second << ")";
404 Out << FPC->getValue();
409 case Type::ArrayTyID:
410 printConstantArray(cast<ConstantArray>(CPV));
413 case Type::StructTyID: {
415 if (CPV->getNumOperands()) {
417 printConstant(cast<Constant>(CPV->getOperand(0)));
418 for (unsigned i = 1, e = CPV->getNumOperands(); i != e; ++i) {
420 printConstant(cast<Constant>(CPV->getOperand(i)));
427 case Type::PointerTyID:
428 if (isa<ConstantPointerNull>(CPV)) {
430 printType(CPV->getType(), "");
433 } else if (ConstantPointerRef *CPR = dyn_cast<ConstantPointerRef>(CPV)) {
434 writeOperand(CPR->getValue());
439 std::cerr << "Unknown constant type: " << CPV << "\n";
444 void CWriter::writeOperandInternal(Value *Operand) {
445 if (Instruction *I = dyn_cast<Instruction>(Operand))
446 if (isInlinableInst(*I)) {
447 // Should we inline this instruction to build a tree?
454 if (Operand->hasName()) {
455 Out << getValueName(Operand);
456 } else if (Constant *CPV = dyn_cast<Constant>(Operand)) {
459 int Slot = Table->getValSlot(Operand);
460 assert(Slot >= 0 && "Malformed LLVM!");
461 Out << "ltmp_" << Slot << "_" << Operand->getType()->getUniqueID();
465 void CWriter::writeOperand(Value *Operand) {
466 if (isa<GlobalVariable>(Operand))
467 Out << "(&"; // Global variables are references as their addresses by llvm
469 writeOperandInternal(Operand);
471 if (isa<GlobalVariable>(Operand))
475 // nameAllUsedStructureTypes - If there are structure types in the module that
476 // are used but do not have names assigned to them in the symbol table yet then
477 // we assign them names now.
479 bool CWriter::nameAllUsedStructureTypes(Module &M) {
480 // Get a set of types that are used by the program...
481 std::set<const Type *> UT = getAnalysis<FindUsedTypes>().getTypes();
483 // Loop over the module symbol table, removing types from UT that are already
486 SymbolTable *MST = M.getSymbolTableSure();
487 if (MST->find(Type::TypeTy) != MST->end())
488 for (SymbolTable::type_iterator I = MST->type_begin(Type::TypeTy),
489 E = MST->type_end(Type::TypeTy); I != E; ++I)
490 UT.erase(cast<Type>(I->second));
492 // UT now contains types that are not named. Loop over it, naming structure
495 bool Changed = false;
496 for (std::set<const Type *>::const_iterator I = UT.begin(), E = UT.end();
498 if (const StructType *ST = dyn_cast<StructType>(*I)) {
499 ((Value*)ST)->setName("unnamed", MST);
505 void CWriter::printModule(Module *M) {
506 // Calculate which global values have names that will collide when we throw
507 // away type information.
508 { // Scope to delete the FoundNames set when we are done with it...
509 std::set<string> FoundNames;
510 for (Module::iterator I = M->begin(), E = M->end(); I != E; ++I)
511 if (I->hasName()) // If the global has a name...
512 if (FoundNames.count(I->getName())) // And the name is already used
513 MangledGlobals.insert(I); // Mangle the name
515 FoundNames.insert(I->getName()); // Otherwise, keep track of name
517 for (Module::giterator I = M->gbegin(), E = M->gend(); 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
525 // printing stdlib inclusion
526 //Out << "#include <stdlib.h>\n";
528 // get declaration for alloca
529 Out << "/* Provide Declarations */\n"
530 << "#include <alloca.h>\n\n"
532 // Provide a definition for null if one does not already exist,
533 // and for `bool' if not compiling with a C++ compiler.
534 << "#ifndef NULL\n#define NULL 0\n#endif\n\n"
535 << "#ifndef __cplusplus\ntypedef unsigned char bool;\n#endif\n"
537 << "\n\n/* Support for floating point constants */\n"
538 << "typedef unsigned long long ConstantDoubleTy;\n"
540 << "\n\n/* Global Declarations */\n";
542 // First output all the declarations for the program, because C requires
543 // Functions & globals to be declared before they are used.
546 // Loop over the symbol table, emitting all named constants...
547 if (M->hasSymbolTable())
548 printSymbolTable(*M->getSymbolTable());
550 // Global variable declarations...
552 Out << "\n/* External Global Variable Declarations */\n";
553 for (Module::giterator I = M->gbegin(), E = M->gend(); I != E; ++I) {
554 if (I->hasExternalLinkage()) {
556 printType(I->getType()->getElementType(), getValueName(I));
562 // Function declarations
564 Out << "\n/* Function Declarations */\n";
566 for (Module::iterator I = M->begin(), E = M->end(); I != E; ++I) {
567 printFunctionSignature(I, true);
572 // Print Malloc prototype if needed
574 Out << "\n/* Malloc to make sun happy */\n";
575 Out << "extern void * malloc(size_t);\n\n";
578 // Output the global variable definitions and contents...
580 Out << "\n\n/* Global Variable Definitions and Initialization */\n";
581 for (Module::giterator I = M->gbegin(), E = M->gend(); I != E; ++I)
582 if (!I->isExternal()) {
583 if (I->hasInternalLinkage())
585 printType(I->getType()->getElementType(), getValueName(I));
588 writeOperand(I->getInitializer());
593 // Output all of the functions...
595 Out << "\n\n/* Function Bodies */\n";
596 for (Module::iterator I = M->begin(), E = M->end(); I != E; ++I)
602 /// printSymbolTable - Run through symbol table looking for type names. If a
603 /// type name is found, emit it's declaration...
605 void CWriter::printSymbolTable(const SymbolTable &ST) {
606 // If there are no type names, exit early.
607 if (ST.find(Type::TypeTy) == ST.end())
610 // We are only interested in the type plane of the symbol table...
611 SymbolTable::type_const_iterator I = ST.type_begin(Type::TypeTy);
612 SymbolTable::type_const_iterator End = ST.type_end(Type::TypeTy);
614 // Print out forward declarations for structure types before anything else!
615 Out << "/* Structure forward decls */\n";
616 for (; I != End; ++I)
617 if (const Type *STy = dyn_cast<StructType>(I->second)) {
618 string Name = "struct l_" + makeNameProper(I->first);
619 Out << Name << ";\n";
620 TypeNames.insert(std::make_pair(STy, Name));
625 // Now we can print out typedefs...
626 Out << "/* Typedefs */\n";
627 for (I = ST.type_begin(Type::TypeTy); I != End; ++I) {
628 const Type *Ty = cast<Type>(I->second);
629 string Name = "l_" + makeNameProper(I->first);
637 // Keep track of which structures have been printed so far...
638 std::set<const StructType *> StructPrinted;
640 // Loop over all structures then push them into the stack so they are
641 // printed in the correct order.
643 Out << "/* Structure contents */\n";
644 for (I = ST.type_begin(Type::TypeTy); I != End; ++I)
645 if (const StructType *STy = dyn_cast<StructType>(I->second))
646 printContainedStructs(STy, StructPrinted);
649 // Push the struct onto the stack and recursively push all structs
650 // this one depends on.
651 void CWriter::printContainedStructs(const Type *Ty,
652 std::set<const StructType*> &StructPrinted){
653 if (const StructType *STy = dyn_cast<StructType>(Ty)){
654 //Check to see if we have already printed this struct
655 if (StructPrinted.count(STy) == 0) {
656 // Print all contained types first...
657 for (StructType::ElementTypes::const_iterator
658 I = STy->getElementTypes().begin(),
659 E = STy->getElementTypes().end(); I != E; ++I) {
660 const Type *Ty1 = I->get();
661 if (isa<StructType>(Ty1) || isa<ArrayType>(Ty1))
662 printContainedStructs(Ty1, StructPrinted);
665 //Print structure type out..
666 StructPrinted.insert(STy);
667 string Name = TypeNames[STy];
668 printType(STy, Name, true);
672 // If it is an array, check contained types and continue
673 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(Ty)){
674 const Type *Ty1 = ATy->getElementType();
675 if (isa<StructType>(Ty1) || isa<ArrayType>(Ty1))
676 printContainedStructs(Ty1, StructPrinted);
681 void CWriter::printFunctionSignature(const Function *F, bool Prototype) {
682 // If the program provides it's own malloc prototype we don't need
683 // to include the general one.
684 if (getValueName(F) == "malloc")
686 if (F->hasInternalLinkage()) Out << "static ";
688 // Loop over the arguments, printing them...
689 const FunctionType *FT = cast<FunctionType>(F->getFunctionType());
691 // Print out the return type and name...
692 printType(F->getReturnType());
693 Out << getValueName(F) << "(";
695 if (!F->isExternal()) {
698 if (F->abegin()->hasName() || !Prototype)
699 ArgName = getValueName(F->abegin());
701 printType(F->afront().getType(), ArgName);
703 for (Function::const_aiterator I = ++F->abegin(), E = F->aend();
706 if (I->hasName() || !Prototype)
707 ArgName = getValueName(I);
710 printType(I->getType(), ArgName);
714 // Loop over the arguments, printing them...
715 for (FunctionType::ParamTypes::const_iterator I =
716 FT->getParamTypes().begin(),
717 E = FT->getParamTypes().end(); I != E; ++I) {
718 if (I != FT->getParamTypes().begin()) Out << ", ";
723 // Finish printing arguments... if this is a vararg function, print the ...,
724 // unless there are no known types, in which case, we just emit ().
726 if (FT->isVarArg() && !FT->getParamTypes().empty()) {
727 if (FT->getParamTypes().size()) Out << ", ";
728 Out << "..."; // Output varargs portion of signature!
734 void CWriter::printFunction(Function *F) {
735 if (F->isExternal()) return;
737 Table->incorporateFunction(F);
739 printFunctionSignature(F, false);
742 // print local variable information for the function
743 for (inst_iterator I = inst_begin(F), E = inst_end(F); I != E; ++I)
744 if ((*I)->getType() != Type::VoidTy && !isInlinableInst(**I)) {
746 printType((*I)->getType(), getValueName(*I));
752 // Scan the function for floating point constants. If any FP constant is used
753 // in the function, we want to redirect it here so that we do not depend on
754 // the precision of the printed form.
756 unsigned FPCounter = 0;
757 for (constant_iterator I = constant_begin(F), E = constant_end(F); I != E;++I)
758 if (const ConstantFP *FPC = dyn_cast<ConstantFP>(*I))
759 if (FPConstantMap.find(FPC) == FPConstantMap.end()) {
760 double Val = FPC->getValue();
762 FPConstantMap[FPC] = FPCounter; // Number the FP constants
763 Out << " const ConstantDoubleTy FloatConstant" << FPCounter++
764 << " = 0x" << std::hex << *(unsigned long long*)&Val << std::dec
765 << "; /* " << Val << " */\n";
770 // print the basic blocks
771 for (Function::iterator BB = F->begin(), E = F->end(); BB != E; ++BB) {
772 BasicBlock *Prev = BB->getPrev();
774 // Don't print the label for the basic block if there are no uses, or if the
775 // only terminator use is the precessor basic block's terminator. We have
776 // to scan the use list because PHI nodes use basic blocks too but do not
777 // require a label to be generated.
779 bool NeedsLabel = false;
780 for (Value::use_iterator UI = BB->use_begin(), UE = BB->use_end();
782 if (TerminatorInst *TI = dyn_cast<TerminatorInst>(*UI))
783 if (TI != Prev->getTerminator()) {
788 if (NeedsLabel) Out << getValueName(BB) << ":\n";
790 // Output all of the instructions in the basic block...
791 for (BasicBlock::iterator II = BB->begin(), E = --BB->end(); II != E; ++II){
792 if (!isInlinableInst(*II) && !isa<PHINode>(*II)) {
793 if (II->getType() != Type::VoidTy)
802 // Don't emit prefix or suffix for the terminator...
803 visit(*BB->getTerminator());
807 Table->purgeFunction();
808 FPConstantMap.clear();
811 // Specific Instruction type classes... note that all of the casts are
812 // neccesary because we use the instruction classes as opaque types...
814 void CWriter::visitReturnInst(ReturnInst &I) {
815 // Don't output a void return if this is the last basic block in the function
816 if (I.getNumOperands() == 0 &&
817 &*--I.getParent()->getParent()->end() == I.getParent() &&
818 !I.getParent()->size() == 1) {
823 if (I.getNumOperands()) {
825 writeOperand(I.getOperand(0));
830 static bool isGotoCodeNeccessary(BasicBlock *From, BasicBlock *To) {
831 // If PHI nodes need copies, we need the copy code...
832 if (isa<PHINode>(To->front()) ||
833 From->getNext() != To) // Not directly successor, need goto
836 // Otherwise we don't need the code.
840 void CWriter::printBranchToBlock(BasicBlock *CurBB, BasicBlock *Succ,
842 for (BasicBlock::iterator I = Succ->begin();
843 PHINode *PN = dyn_cast<PHINode>(&*I); ++I) {
844 // now we have to do the printing
845 Out << string(Indent, ' ');
847 writeOperand(PN->getIncomingValue(PN->getBasicBlockIndex(CurBB)));
848 Out << "; /* for PHI node */\n";
851 if (CurBB->getNext() != Succ) {
852 Out << string(Indent, ' ') << " goto ";
858 // Brach instruction printing - Avoid printing out a brach to a basic block that
859 // immediately succeeds the current one.
861 void CWriter::visitBranchInst(BranchInst &I) {
862 if (I.isConditional()) {
863 if (isGotoCodeNeccessary(I.getParent(), I.getSuccessor(0))) {
865 writeOperand(I.getCondition());
868 printBranchToBlock(I.getParent(), I.getSuccessor(0), 2);
870 if (isGotoCodeNeccessary(I.getParent(), I.getSuccessor(1))) {
871 Out << " } else {\n";
872 printBranchToBlock(I.getParent(), I.getSuccessor(1), 2);
875 // First goto not neccesary, assume second one is...
877 writeOperand(I.getCondition());
880 printBranchToBlock(I.getParent(), I.getSuccessor(1), 2);
885 printBranchToBlock(I.getParent(), I.getSuccessor(0), 0);
891 void CWriter::visitBinaryOperator(Instruction &I) {
892 // binary instructions, shift instructions, setCond instructions.
893 if (isa<PointerType>(I.getType())) {
895 printType(I.getType());
899 if (isa<PointerType>(I.getType())) Out << "(long long)";
900 writeOperand(I.getOperand(0));
902 switch (I.getOpcode()) {
903 case Instruction::Add: Out << " + "; break;
904 case Instruction::Sub: Out << " - "; break;
905 case Instruction::Mul: Out << "*"; break;
906 case Instruction::Div: Out << "/"; break;
907 case Instruction::Rem: Out << "%"; break;
908 case Instruction::And: Out << " & "; break;
909 case Instruction::Or: Out << " | "; break;
910 case Instruction::Xor: Out << " ^ "; break;
911 case Instruction::SetEQ: Out << " == "; break;
912 case Instruction::SetNE: Out << " != "; break;
913 case Instruction::SetLE: Out << " <= "; break;
914 case Instruction::SetGE: Out << " >= "; break;
915 case Instruction::SetLT: Out << " < "; break;
916 case Instruction::SetGT: Out << " > "; break;
917 case Instruction::Shl : Out << " << "; break;
918 case Instruction::Shr : Out << " >> "; break;
919 default: std::cerr << "Invalid operator type!" << I; abort();
922 if (isa<PointerType>(I.getType())) Out << "(long long)";
923 writeOperand(I.getOperand(1));
926 void CWriter::visitCastInst(CastInst &I) {
928 printType(I.getType(), string(""),/*ignoreName*/false, /*namedContext*/false);
930 writeOperand(I.getOperand(0));
933 void CWriter::visitCallInst(CallInst &I) {
934 const PointerType *PTy = cast<PointerType>(I.getCalledValue()->getType());
935 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
936 const Type *RetTy = FTy->getReturnType();
938 writeOperand(I.getOperand(0));
941 if (I.getNumOperands() > 1) {
942 writeOperand(I.getOperand(1));
944 for (unsigned op = 2, Eop = I.getNumOperands(); op != Eop; ++op) {
946 writeOperand(I.getOperand(op));
952 void CWriter::visitMallocInst(MallocInst &I) {
954 printType(I.getType());
955 Out << ")malloc(sizeof(";
956 printType(I.getType()->getElementType());
959 if (I.isArrayAllocation()) {
961 writeOperand(I.getOperand(0));
966 void CWriter::visitAllocaInst(AllocaInst &I) {
968 printType(I.getType());
969 Out << ") alloca(sizeof(";
970 printType(I.getType()->getElementType());
972 if (I.isArrayAllocation()) {
974 writeOperand(I.getOperand(0));
979 void CWriter::visitFreeInst(FreeInst &I) {
981 writeOperand(I.getOperand(0));
985 void CWriter::printIndexingExpression(Value *Ptr, User::op_iterator I,
986 User::op_iterator E) {
987 bool HasImplicitAddress = false;
988 // If accessing a global value with no indexing, avoid *(&GV) syndrome
989 if (GlobalValue *V = dyn_cast<GlobalValue>(Ptr)) {
990 HasImplicitAddress = true;
991 } else if (ConstantPointerRef *CPR = dyn_cast<ConstantPointerRef>(Ptr)) {
992 HasImplicitAddress = true;
993 Ptr = CPR->getValue(); // Get to the global...
997 if (!HasImplicitAddress)
998 Out << "*"; // Implicit zero first argument: '*x' is equivalent to 'x[0]'
1000 writeOperandInternal(Ptr);
1004 const Constant *CI = dyn_cast<Constant>(I->get());
1005 if (HasImplicitAddress && (!CI || !CI->isNullValue()))
1008 writeOperandInternal(Ptr);
1010 if (HasImplicitAddress && (!CI || !CI->isNullValue())) {
1012 HasImplicitAddress = false; // HIA is only true if we haven't addressed yet
1015 assert(!HasImplicitAddress || (CI && CI->isNullValue()) &&
1016 "Can only have implicit address with direct accessing");
1018 if (HasImplicitAddress) {
1020 } else if (CI && CI->isNullValue() && I+1 != E) {
1021 // Print out the -> operator if possible...
1022 if ((*(I+1))->getType() == Type::UByteTy) {
1023 Out << (HasImplicitAddress ? "." : "->");
1024 Out << "field" << cast<ConstantUInt>(*(I+1))->getValue();
1030 if ((*I)->getType() == Type::LongTy) {
1035 Out << ".field" << cast<ConstantUInt>(*I)->getValue();
1039 void CWriter::visitLoadInst(LoadInst &I) {
1041 writeOperand(I.getOperand(0));
1044 void CWriter::visitStoreInst(StoreInst &I) {
1046 writeOperand(I.getPointerOperand());
1048 writeOperand(I.getOperand(0));
1051 void CWriter::visitGetElementPtrInst(GetElementPtrInst &I) {
1053 printIndexingExpression(I.getPointerOperand(), I.idx_begin(), I.idx_end());
1056 //===----------------------------------------------------------------------===//
1057 // External Interface declaration
1058 //===----------------------------------------------------------------------===//
1060 Pass *createWriteToCPass(std::ostream &o) { return new CWriter(o); }