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/iMemory.h"
12 #include "llvm/iTerminators.h"
13 #include "llvm/iPHINode.h"
14 #include "llvm/iOther.h"
15 #include "llvm/iOperators.h"
16 #include "llvm/Pass.h"
17 #include "llvm/SymbolTable.h"
18 #include "llvm/SlotCalculator.h"
19 #include "llvm/Analysis/FindUsedTypes.h"
20 #include "llvm/Analysis/ConstantsScanner.h"
21 #include "llvm/Support/InstVisitor.h"
22 #include "llvm/Support/InstIterator.h"
23 #include "Support/StringExtras.h"
24 #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;
39 map<const ConstantFP *, unsigned> FPConstantMap;
41 CWriter(ostream &o) : Out(o) {}
43 void getAnalysisUsage(AnalysisUsage &AU) const {
45 AU.addRequired<FindUsedTypes>();
48 virtual bool run(Module &M) {
50 Table = new SlotCalculator(&M, false);
53 // Ensure that all structure types have names...
54 bool Changed = nameAllUsedStructureTypes(M);
62 MangledGlobals.clear();
66 ostream &printType(const Type *Ty, const string &VariableName = "",
67 bool IgnoreName = false, bool namedContext = true);
69 void writeOperand(Value *Operand);
70 void writeOperandInternal(Value *Operand);
72 string getValueName(const Value *V);
75 bool nameAllUsedStructureTypes(Module &M);
76 void printModule(Module *M);
77 void printSymbolTable(const SymbolTable &ST);
78 void printContainedStructs(const Type *Ty, std::set<const StructType *> &);
79 void printGlobal(const GlobalVariable *GV);
80 void printFunctionSignature(const Function *F, bool Prototype);
82 void printFunction(Function *);
84 void printConstant(Constant *CPV);
85 void printConstantArray(ConstantArray *CPA);
87 // isInlinableInst - Attempt to inline instructions into their uses to build
88 // trees as much as possible. To do this, we have to consistently decide
89 // what is acceptable to inline, so that variable declarations don't get
90 // printed and an extra copy of the expr is not emitted.
92 static bool isInlinableInst(const Instruction &I) {
93 // Must be an expression, must be used exactly once. If it is dead, we
94 // emit it inline where it would go.
95 if (I.getType() == Type::VoidTy || I.use_size() != 1 ||
96 isa<TerminatorInst>(I) || isa<CallInst>(I) || isa<PHINode>(I))
99 // Only inline instruction it it's use is in the same BB as the inst.
100 return I.getParent() == cast<Instruction>(I.use_back())->getParent();
103 // Instruction visitation functions
104 friend class InstVisitor<CWriter>;
106 void visitReturnInst(ReturnInst &I);
107 void visitBranchInst(BranchInst &I);
109 void visitPHINode(PHINode &I) {}
110 void visitBinaryOperator(Instruction &I);
112 void visitCastInst (CastInst &I);
113 void visitCallInst (CallInst &I);
114 void visitShiftInst(ShiftInst &I) { visitBinaryOperator(I); }
116 void visitMallocInst(MallocInst &I);
117 void visitAllocaInst(AllocaInst &I);
118 void visitFreeInst (FreeInst &I);
119 void visitLoadInst (LoadInst &I);
120 void visitStoreInst (StoreInst &I);
121 void visitGetElementPtrInst(GetElementPtrInst &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 string makeNameProper(string x) {
142 for (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 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 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 ostream &CWriter::printType(const Type *Ty, const string &NameSoFar,
178 bool IgnoreName, bool namedContext) {
179 if (Ty->isPrimitiveType())
180 switch (Ty->getPrimitiveID()) {
181 case Type::VoidTyID: return Out << "void " << NameSoFar;
182 case Type::BoolTyID: return Out << "bool " << NameSoFar;
183 case Type::UByteTyID: return Out << "unsigned char " << NameSoFar;
184 case Type::SByteTyID: return Out << "signed char " << NameSoFar;
185 case Type::UShortTyID: return Out << "unsigned short " << NameSoFar;
186 case Type::ShortTyID: return Out << "short " << NameSoFar;
187 case Type::UIntTyID: return Out << "unsigned " << NameSoFar;
188 case Type::IntTyID: return Out << "int " << NameSoFar;
189 case Type::ULongTyID: return Out << "unsigned long long " << NameSoFar;
190 case Type::LongTyID: return Out << "signed long long " << NameSoFar;
191 case Type::FloatTyID: return Out << "float " << NameSoFar;
192 case Type::DoubleTyID: return Out << "double " << NameSoFar;
194 std::cerr << "Unknown primitive type: " << Ty << "\n";
198 // Check to see if the type is named.
200 map<const Type *, string>::iterator I = TypeNames.find(Ty);
201 if (I != TypeNames.end()) {
202 return Out << I->second << " " << NameSoFar;
206 switch (Ty->getPrimitiveID()) {
207 case Type::FunctionTyID: {
208 const FunctionType *MTy = cast<FunctionType>(Ty);
209 printType(MTy->getReturnType(), "");
210 Out << " " << 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())
219 if (MTy->isVarArg()) {
220 if (!MTy->getParamTypes().empty())
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(*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 ptrName = "(" + ptrName + ")"; //
250 return printType(PTy->getElementType(), ptrName);
253 case Type::ArrayTyID: {
254 const ArrayType *ATy = cast<ArrayType>(Ty);
255 unsigned NumElements = ATy->getNumElements();
256 return printType(ATy->getElementType(),
257 NameSoFar + "[" + utostr(NumElements) + "]");
260 assert(0 && "Unhandled case in getTypeProps!");
267 void CWriter::printConstantArray(ConstantArray *CPA) {
269 // As a special case, print the array as a string if it is an array of
270 // ubytes or an array of sbytes with positive values.
272 const Type *ETy = CPA->getType()->getElementType();
273 bool isString = (ETy == Type::SByteTy || ETy == Type::UByteTy);
275 // Make sure the last character is a null char, as automatically added by C
276 if (CPA->getNumOperands() == 0 ||
277 !cast<Constant>(*(CPA->op_end()-1))->isNullValue())
282 // Do not include the last character, which we know is null
283 for (unsigned i = 0, e = CPA->getNumOperands()-1; i != e; ++i) {
284 unsigned char C = (ETy == Type::SByteTy) ?
285 (unsigned char)cast<ConstantSInt>(CPA->getOperand(i))->getValue() :
286 (unsigned char)cast<ConstantUInt>(CPA->getOperand(i))->getValue();
292 case '\n': Out << "\\n"; break;
293 case '\t': Out << "\\t"; break;
294 case '\r': Out << "\\r"; break;
295 case '\v': Out << "\\v"; break;
296 case '\a': Out << "\\a"; break;
299 Out << ( C/16 < 10) ? ( C/16 +'0') : ( C/16 -10+'A');
300 Out << ((C&15) < 10) ? ((C&15)+'0') : ((C&15)-10+'A');
308 if (CPA->getNumOperands()) {
310 printConstant(cast<Constant>(CPA->getOperand(0)));
311 for (unsigned i = 1, e = CPA->getNumOperands(); i != e; ++i) {
313 printConstant(cast<Constant>(CPA->getOperand(i)));
321 // printConstant - The LLVM Constant to C Constant converter.
322 void CWriter::printConstant(Constant *CPV) {
323 if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(CPV)) {
324 switch (CE->getOpcode()) {
325 case Instruction::Cast:
327 printType(CPV->getType());
329 printConstant(cast<Constant>(CPV->getOperand(0)));
333 case Instruction::GetElementPtr:
335 printIndexingExpression(CPV->getOperand(0),
336 CPV->op_begin()+1, CPV->op_end());
339 case Instruction::Add:
341 printConstant(cast<Constant>(CPV->getOperand(0)));
343 printConstant(cast<Constant>(CPV->getOperand(1)));
346 case Instruction::Sub:
348 printConstant(cast<Constant>(CPV->getOperand(0)));
350 printConstant(cast<Constant>(CPV->getOperand(1)));
355 std::cerr << "CWriter Error: Unhandled constant expression: "
361 switch (CPV->getType()->getPrimitiveID()) {
363 Out << (CPV == ConstantBool::False ? "0" : "1"); break;
364 case Type::SByteTyID:
365 case Type::ShortTyID:
367 Out << cast<ConstantSInt>(CPV)->getValue(); break;
369 Out << cast<ConstantSInt>(CPV)->getValue() << "ll"; break;
371 case Type::UByteTyID:
372 case Type::UShortTyID:
373 Out << cast<ConstantUInt>(CPV)->getValue(); break;
375 Out << cast<ConstantUInt>(CPV)->getValue() << "u"; break;
376 case Type::ULongTyID:
377 Out << cast<ConstantUInt>(CPV)->getValue() << "ull"; break;
379 case Type::FloatTyID:
380 case Type::DoubleTyID: {
381 ConstantFP *FPC = cast<ConstantFP>(CPV);
382 map<const ConstantFP *, unsigned>::iterator I = FPConstantMap.find(FPC);
383 if (I != FPConstantMap.end()) {
384 // Because of FP precision problems we must load from a stack allocated
385 // value that holds the value in hex.
386 Out << "(*(" << (FPC->getType() == Type::FloatTy ? "float" : "double")
387 << "*)&FloatConstant" << I->second << ")";
389 Out << FPC->getValue();
394 case Type::ArrayTyID:
395 printConstantArray(cast<ConstantArray>(CPV));
398 case Type::StructTyID: {
400 if (CPV->getNumOperands()) {
402 printConstant(cast<Constant>(CPV->getOperand(0)));
403 for (unsigned i = 1, e = CPV->getNumOperands(); i != e; ++i) {
405 printConstant(cast<Constant>(CPV->getOperand(i)));
412 case Type::PointerTyID:
413 if (isa<ConstantPointerNull>(CPV)) {
415 printType(CPV->getType(), "");
418 } else if (ConstantPointerRef *CPR = dyn_cast<ConstantPointerRef>(CPV)) {
419 writeOperand(CPR->getValue());
424 std::cerr << "Unknown constant type: " << CPV << "\n";
429 void CWriter::writeOperandInternal(Value *Operand) {
430 if (Instruction *I = dyn_cast<Instruction>(Operand))
431 if (isInlinableInst(*I)) {
432 // Should we inline this instruction to build a tree?
439 if (Operand->hasName()) {
440 Out << getValueName(Operand);
441 } else if (Constant *CPV = dyn_cast<Constant>(Operand)) {
444 int Slot = Table->getValSlot(Operand);
445 assert(Slot >= 0 && "Malformed LLVM!");
446 Out << "ltmp_" << Slot << "_" << Operand->getType()->getUniqueID();
450 void CWriter::writeOperand(Value *Operand) {
451 if (isa<GlobalVariable>(Operand))
452 Out << "(&"; // Global variables are references as their addresses by llvm
454 writeOperandInternal(Operand);
456 if (isa<GlobalVariable>(Operand))
460 // nameAllUsedStructureTypes - If there are structure types in the module that
461 // are used but do not have names assigned to them in the symbol table yet then
462 // we assign them names now.
464 bool CWriter::nameAllUsedStructureTypes(Module &M) {
465 // Get a set of types that are used by the program...
466 std::set<const Type *> UT = getAnalysis<FindUsedTypes>().getTypes();
468 // Loop over the module symbol table, removing types from UT that are already
471 SymbolTable *MST = M.getSymbolTableSure();
472 if (MST->find(Type::TypeTy) != MST->end())
473 for (SymbolTable::type_iterator I = MST->type_begin(Type::TypeTy),
474 E = MST->type_end(Type::TypeTy); I != E; ++I)
475 UT.erase(cast<Type>(I->second));
477 // UT now contains types that are not named. Loop over it, naming structure
480 bool Changed = false;
481 for (std::set<const Type *>::const_iterator I = UT.begin(), E = UT.end();
483 if (const StructType *ST = dyn_cast<StructType>(*I)) {
484 ((Value*)ST)->setName("unnamed", MST);
490 void CWriter::printModule(Module *M) {
491 // Calculate which global values have names that will collide when we throw
492 // away type information.
493 { // Scope to delete the FoundNames set when we are done with it...
494 std::set<string> FoundNames;
495 for (Module::iterator I = M->begin(), E = M->end(); I != E; ++I)
496 if (I->hasName()) // If the global has a name...
497 if (FoundNames.count(I->getName())) // And the name is already used
498 MangledGlobals.insert(I); // Mangle the name
500 FoundNames.insert(I->getName()); // Otherwise, keep track of name
502 for (Module::giterator I = M->gbegin(), E = M->gend(); I != E; ++I)
503 if (I->hasName()) // If the global has a name...
504 if (FoundNames.count(I->getName())) // And the name is already used
505 MangledGlobals.insert(I); // Mangle the name
507 FoundNames.insert(I->getName()); // Otherwise, keep track of name
510 // printing stdlib inclusion
511 // Out << "#include <stdlib.h>\n";
513 // get declaration for alloca
514 Out << "/* Provide Declarations */\n"
515 << "#include <malloc.h>\n"
516 << "#include <alloca.h>\n\n"
518 // Provide a definition for null if one does not already exist,
519 // and for `bool' if not compiling with a C++ compiler.
520 << "#ifndef NULL\n#define NULL 0\n#endif\n\n"
521 << "#ifndef __cplusplus\ntypedef unsigned char bool;\n#endif\n"
523 << "\n\n/* Support for floating point constants */\n"
524 << "typedef unsigned long long ConstantDoubleTy;\n"
526 << "\n\n/* Global Declarations */\n";
528 // First output all the declarations for the program, because C requires
529 // Functions & globals to be declared before they are used.
532 // Loop over the symbol table, emitting all named constants...
533 if (M->hasSymbolTable())
534 printSymbolTable(*M->getSymbolTable());
536 // Global variable declarations...
538 Out << "\n/* External Global Variable Declarations */\n";
539 for (Module::giterator I = M->gbegin(), E = M->gend(); I != E; ++I) {
540 if (I->hasExternalLinkage()) {
542 printType(I->getType()->getElementType(), getValueName(I));
548 // Function declarations
550 Out << "\n/* Function Declarations */\n";
551 for (Module::iterator I = M->begin(), E = M->end(); I != E; ++I) {
552 printFunctionSignature(I, true);
557 // Output the global variable definitions and contents...
559 Out << "\n\n/* Global Variable Definitions and Initialization */\n";
560 for (Module::giterator I = M->gbegin(), E = M->gend(); I != E; ++I) {
561 if (I->hasExternalLinkage())
562 continue; // printed above!
564 printType(I->getType()->getElementType(), getValueName(I));
566 if (I->hasInitializer()) {
568 writeOperand(I->getInitializer());
574 // Output all of the functions...
576 Out << "\n\n/* Function Bodies */\n";
577 for (Module::iterator I = M->begin(), E = M->end(); I != E; ++I)
583 /// printSymbolTable - Run through symbol table looking for type names. If a
584 /// type name is found, emit it's declaration...
586 void CWriter::printSymbolTable(const SymbolTable &ST) {
587 // If there are no type names, exit early.
588 if (ST.find(Type::TypeTy) == ST.end())
591 // We are only interested in the type plane of the symbol table...
592 SymbolTable::type_const_iterator I = ST.type_begin(Type::TypeTy);
593 SymbolTable::type_const_iterator End = ST.type_end(Type::TypeTy);
595 // Print out forward declarations for structure types before anything else!
596 Out << "/* Structure forward decls */\n";
597 for (; I != End; ++I)
598 if (const Type *STy = dyn_cast<StructType>(I->second)) {
599 string Name = "struct l_" + makeNameProper(I->first);
600 Out << Name << ";\n";
601 TypeNames.insert(std::make_pair(STy, Name));
606 // Now we can print out typedefs...
607 Out << "/* Typedefs */\n";
608 for (I = ST.type_begin(Type::TypeTy); I != End; ++I) {
609 const Type *Ty = cast<Type>(I->second);
610 string Name = "l_" + makeNameProper(I->first);
618 // Keep track of which structures have been printed so far...
619 std::set<const StructType *> StructPrinted;
621 // Loop over all structures then push them into the stack so they are
622 // printed in the correct order.
624 Out << "/* Structure contents */\n";
625 for (I = ST.type_begin(Type::TypeTy); I != End; ++I)
626 if (const StructType *STy = dyn_cast<StructType>(I->second))
627 printContainedStructs(STy, StructPrinted);
630 // Push the struct onto the stack and recursively push all structs
631 // this one depends on.
632 void CWriter::printContainedStructs(const Type *Ty,
633 std::set<const StructType*> &StructPrinted){
634 if (const StructType *STy = dyn_cast<StructType>(Ty)){
635 //Check to see if we have already printed this struct
636 if (StructPrinted.count(STy) == 0) {
637 // Print all contained types first...
638 for (StructType::ElementTypes::const_iterator
639 I = STy->getElementTypes().begin(),
640 E = STy->getElementTypes().end(); I != E; ++I) {
641 const Type *Ty1 = I->get();
642 if (isa<StructType>(Ty1) || isa<ArrayType>(Ty1))
643 printContainedStructs(Ty1, StructPrinted);
646 //Print structure type out..
647 StructPrinted.insert(STy);
648 string Name = TypeNames[STy];
649 printType(STy, Name, true);
653 // If it is an array, check contained types and continue
654 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(Ty)){
655 const Type *Ty1 = ATy->getElementType();
656 if (isa<StructType>(Ty1) || isa<ArrayType>(Ty1))
657 printContainedStructs(Ty1, StructPrinted);
662 void CWriter::printFunctionSignature(const Function *F, bool Prototype) {
663 if (F->hasInternalLinkage()) Out << "static ";
665 // Loop over the arguments, printing them...
666 const FunctionType *FT = cast<FunctionType>(F->getFunctionType());
668 // Print out the return type and name...
669 printType(F->getReturnType());
670 Out << getValueName(F) << "(";
672 if (!F->isExternal()) {
675 if (F->abegin()->hasName() || !Prototype)
676 ArgName = getValueName(F->abegin());
678 printType(F->afront().getType(), ArgName);
680 for (Function::const_aiterator I = ++F->abegin(), E = F->aend();
683 if (I->hasName() || !Prototype)
684 ArgName = getValueName(I);
687 printType(I->getType(), ArgName);
691 // Loop over the arguments, printing them...
692 for (FunctionType::ParamTypes::const_iterator I =
693 FT->getParamTypes().begin(),
694 E = FT->getParamTypes().end(); I != E; ++I) {
695 if (I != FT->getParamTypes().begin()) Out << ", ";
700 // Finish printing arguments... if this is a vararg function, print the ...,
701 // unless there are no known types, in which case, we just emit ().
703 if (FT->isVarArg() && !FT->getParamTypes().empty()) {
704 if (FT->getParamTypes().size()) Out << ", ";
705 Out << "..."; // Output varargs portion of signature!
711 void CWriter::printFunction(Function *F) {
712 if (F->isExternal()) return;
714 Table->incorporateFunction(F);
716 printFunctionSignature(F, false);
719 // print local variable information for the function
720 for (inst_iterator I = inst_begin(F), E = inst_end(F); I != E; ++I)
721 if ((*I)->getType() != Type::VoidTy && !isInlinableInst(**I)) {
723 printType((*I)->getType(), getValueName(*I));
729 // Scan the function for floating point constants. If any FP constant is used
730 // in the function, we want to redirect it here so that we do not depend on
731 // the precision of the printed form.
733 unsigned FPCounter = 0;
734 for (constant_iterator I = constant_begin(F), E = constant_end(F); I != E;++I)
735 if (const ConstantFP *FPC = dyn_cast<ConstantFP>(*I))
736 if (FPConstantMap.find(FPC) == FPConstantMap.end()) {
737 double Val = FPC->getValue();
739 FPConstantMap[FPC] = FPCounter; // Number the FP constants
740 Out << " const ConstantDoubleTy FloatConstant" << FPCounter++
741 << " = 0x" << std::hex << *(unsigned long long*)&Val << std::dec
742 << "; /* " << Val << " */\n";
747 // print the basic blocks
748 for (Function::iterator BB = F->begin(), E = F->end(); BB != E; ++BB) {
749 BasicBlock *Prev = BB->getPrev();
751 // Don't print the label for the basic block if there are no uses, or if the
752 // only terminator use is the precessor basic block's terminator. We have
753 // to scan the use list because PHI nodes use basic blocks too but do not
754 // require a label to be generated.
756 bool NeedsLabel = false;
757 for (Value::use_iterator UI = BB->use_begin(), UE = BB->use_end();
759 if (TerminatorInst *TI = dyn_cast<TerminatorInst>(*UI))
760 if (TI != Prev->getTerminator()) {
765 if (NeedsLabel) Out << getValueName(BB) << ":\n";
767 // Output all of the instructions in the basic block...
768 for (BasicBlock::iterator II = BB->begin(), E = --BB->end(); II != E; ++II){
769 if (!isInlinableInst(*II) && !isa<PHINode>(*II)) {
770 if (II->getType() != Type::VoidTy)
779 // Don't emit prefix or suffix for the terminator...
780 visit(*BB->getTerminator());
784 Table->purgeFunction();
785 FPConstantMap.clear();
788 // Specific Instruction type classes... note that all of the casts are
789 // neccesary because we use the instruction classes as opaque types...
791 void CWriter::visitReturnInst(ReturnInst &I) {
792 // Don't output a void return if this is the last basic block in the function
793 if (I.getNumOperands() == 0 &&
794 &*--I.getParent()->getParent()->end() == I.getParent() &&
795 !I.getParent()->size() == 1) {
800 if (I.getNumOperands()) {
802 writeOperand(I.getOperand(0));
807 static bool isGotoCodeNeccessary(BasicBlock *From, BasicBlock *To) {
808 // If PHI nodes need copies, we need the copy code...
809 if (isa<PHINode>(To->front()) ||
810 From->getNext() != To) // Not directly successor, need goto
813 // Otherwise we don't need the code.
817 void CWriter::printBranchToBlock(BasicBlock *CurBB, BasicBlock *Succ,
819 for (BasicBlock::iterator I = Succ->begin();
820 PHINode *PN = dyn_cast<PHINode>(&*I); ++I) {
821 // now we have to do the printing
822 Out << string(Indent, ' ');
824 writeOperand(PN->getIncomingValue(PN->getBasicBlockIndex(CurBB)));
825 Out << "; /* for PHI node */\n";
828 if (CurBB->getNext() != Succ) {
829 Out << string(Indent, ' ') << " goto ";
835 // Brach instruction printing - Avoid printing out a brach to a basic block that
836 // immediately succeeds the current one.
838 void CWriter::visitBranchInst(BranchInst &I) {
839 if (I.isConditional()) {
840 if (isGotoCodeNeccessary(I.getParent(), I.getSuccessor(0))) {
842 writeOperand(I.getCondition());
845 printBranchToBlock(I.getParent(), I.getSuccessor(0), 2);
847 if (isGotoCodeNeccessary(I.getParent(), I.getSuccessor(1))) {
848 Out << " } else {\n";
849 printBranchToBlock(I.getParent(), I.getSuccessor(1), 2);
852 // First goto not neccesary, assume second one is...
854 writeOperand(I.getCondition());
857 printBranchToBlock(I.getParent(), I.getSuccessor(1), 2);
862 printBranchToBlock(I.getParent(), I.getSuccessor(0), 0);
868 void CWriter::visitBinaryOperator(Instruction &I) {
869 // binary instructions, shift instructions, setCond instructions.
870 if (isa<PointerType>(I.getType())) {
872 printType(I.getType());
876 if (isa<PointerType>(I.getType())) Out << "(long long)";
877 writeOperand(I.getOperand(0));
879 switch (I.getOpcode()) {
880 case Instruction::Add: Out << " + "; break;
881 case Instruction::Sub: Out << " - "; break;
882 case Instruction::Mul: Out << "*"; break;
883 case Instruction::Div: Out << "/"; break;
884 case Instruction::Rem: Out << "%"; break;
885 case Instruction::And: Out << " & "; break;
886 case Instruction::Or: Out << " | "; break;
887 case Instruction::Xor: Out << " ^ "; break;
888 case Instruction::SetEQ: Out << " == "; break;
889 case Instruction::SetNE: Out << " != "; break;
890 case Instruction::SetLE: Out << " <= "; break;
891 case Instruction::SetGE: Out << " >= "; break;
892 case Instruction::SetLT: Out << " < "; break;
893 case Instruction::SetGT: Out << " > "; break;
894 case Instruction::Shl : Out << " << "; break;
895 case Instruction::Shr : Out << " >> "; break;
896 default: std::cerr << "Invalid operator type!" << I; abort();
899 if (isa<PointerType>(I.getType())) Out << "(long long)";
900 writeOperand(I.getOperand(1));
903 void CWriter::visitCastInst(CastInst &I) {
905 printType(I.getType(), string(""),/*ignoreName*/false, /*namedContext*/false);
907 writeOperand(I.getOperand(0));
910 void CWriter::visitCallInst(CallInst &I) {
911 const PointerType *PTy = cast<PointerType>(I.getCalledValue()->getType());
912 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
913 const Type *RetTy = FTy->getReturnType();
915 writeOperand(I.getOperand(0));
918 if (I.getNumOperands() > 1) {
919 writeOperand(I.getOperand(1));
921 for (unsigned op = 2, Eop = I.getNumOperands(); op != Eop; ++op) {
923 writeOperand(I.getOperand(op));
929 void CWriter::visitMallocInst(MallocInst &I) {
931 printType(I.getType());
932 Out << ")malloc(sizeof(";
933 printType(I.getType()->getElementType());
936 if (I.isArrayAllocation()) {
938 writeOperand(I.getOperand(0));
943 void CWriter::visitAllocaInst(AllocaInst &I) {
945 printType(I.getType());
946 Out << ") alloca(sizeof(";
947 printType(I.getType()->getElementType());
949 if (I.isArrayAllocation()) {
951 writeOperand(I.getOperand(0));
956 void CWriter::visitFreeInst(FreeInst &I) {
958 writeOperand(I.getOperand(0));
962 void CWriter::printIndexingExpression(Value *Ptr, User::op_iterator I,
963 User::op_iterator E) {
964 bool HasImplicitAddress = false;
965 // If accessing a global value with no indexing, avoid *(&GV) syndrome
966 if (GlobalValue *V = dyn_cast<GlobalValue>(Ptr)) {
967 HasImplicitAddress = true;
968 } else if (ConstantPointerRef *CPR = dyn_cast<ConstantPointerRef>(Ptr)) {
969 HasImplicitAddress = true;
970 Ptr = CPR->getValue(); // Get to the global...
974 if (!HasImplicitAddress)
975 Out << "*"; // Implicit zero first argument: '*x' is equivalent to 'x[0]'
977 writeOperandInternal(Ptr);
981 const Constant *CI = dyn_cast<Constant>(I->get());
982 if (HasImplicitAddress && (!CI || !CI->isNullValue()))
985 writeOperandInternal(Ptr);
987 if (HasImplicitAddress && (!CI || !CI->isNullValue()))
990 // Print out the -> operator if possible...
991 if (CI && CI->isNullValue() && I+1 != E) {
992 if ((*(I+1))->getType() == Type::UByteTy) {
993 Out << (HasImplicitAddress ? "." : "->");
994 Out << "field" << cast<ConstantUInt>(*(I+1))->getValue();
996 } else { // First array index of 0: Just skip it
1002 if ((*I)->getType() == Type::LongTy) {
1007 Out << ".field" << cast<ConstantUInt>(*I)->getValue();
1011 void CWriter::visitLoadInst(LoadInst &I) {
1013 writeOperand(I.getOperand(0));
1016 void CWriter::visitStoreInst(StoreInst &I) {
1018 writeOperand(I.getPointerOperand());
1020 writeOperand(I.getOperand(0));
1023 void CWriter::visitGetElementPtrInst(GetElementPtrInst &I) {
1025 printIndexingExpression(I.getPointerOperand(), I.idx_begin(), I.idx_end());
1028 //===----------------------------------------------------------------------===//
1029 // External Interface declaration
1030 //===----------------------------------------------------------------------===//
1032 Pass *createWriteToCPass(std::ostream &o) { return new CWriter(o); }